2021-07-19 18:08:41 +00:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
2021-09-14 14:44:02 +00:00
|
|
|
"context"
|
2021-07-19 18:08:41 +00:00
|
|
|
"database/sql"
|
|
|
|
"time"
|
2021-11-15 14:11:38 +00:00
|
|
|
|
|
|
|
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
2021-07-19 18:08:41 +00:00
|
|
|
)
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
func (d *Datastore) Lock(ctx context.Context, name string, owner string, expiration time.Duration) (bool, error) {
|
|
|
|
lockObtainers := []func(context.Context, string, string, time.Duration) (sql.Result, error){
|
2021-07-19 18:08:41 +00:00
|
|
|
d.extendLockIfAlreadyAcquired,
|
|
|
|
d.overwriteLockIfExpired,
|
|
|
|
d.createLock,
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, lockFunc := range lockObtainers {
|
2021-09-14 14:44:02 +00:00
|
|
|
res, err := lockFunc(ctx, name, owner, expiration)
|
2021-07-19 18:08:41 +00:00
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return false, ctxerr.Wrap(ctx, err, "lock")
|
2021-07-19 18:08:41 +00:00
|
|
|
}
|
|
|
|
rowsAffected, err := res.RowsAffected()
|
|
|
|
if err != nil {
|
2021-11-15 14:11:38 +00:00
|
|
|
return false, ctxerr.Wrap(ctx, err, "rows affected")
|
2021-07-19 18:08:41 +00:00
|
|
|
}
|
|
|
|
if rowsAffected > 0 {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
func (d *Datastore) createLock(ctx context.Context, name string, owner string, expiration time.Duration) (sql.Result, error) {
|
|
|
|
return d.writer.ExecContext(ctx,
|
2021-07-19 18:08:41 +00:00
|
|
|
`INSERT IGNORE INTO locks (name, owner, expires_at) VALUES (?, ?, ?)`,
|
|
|
|
name, owner, time.Now().Add(expiration),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
func (d *Datastore) extendLockIfAlreadyAcquired(ctx context.Context, name string, owner string, expiration time.Duration) (sql.Result, error) {
|
|
|
|
return d.writer.ExecContext(ctx,
|
2021-07-19 18:08:41 +00:00
|
|
|
`UPDATE locks SET name = ?, owner = ?, expires_at = ? WHERE name = ? and owner = ?`,
|
|
|
|
name, owner, time.Now().Add(expiration), name, owner,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
func (d *Datastore) overwriteLockIfExpired(ctx context.Context, name string, owner string, expiration time.Duration) (sql.Result, error) {
|
|
|
|
return d.writer.ExecContext(ctx,
|
2021-07-19 18:08:41 +00:00
|
|
|
`UPDATE locks SET name = ?, owner = ?, expires_at = ? WHERE expires_at < CURRENT_TIMESTAMP and name = ?`,
|
|
|
|
name, owner, time.Now().Add(expiration), name,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-09-14 14:44:02 +00:00
|
|
|
func (d *Datastore) Unlock(ctx context.Context, name string, owner string) error {
|
|
|
|
_, err := d.writer.ExecContext(ctx, `DELETE FROM locks WHERE name = ? and owner = ?`, name, owner)
|
2021-07-19 18:08:41 +00:00
|
|
|
return err
|
|
|
|
}
|