2021-07-19 18:08:41 +00:00
|
|
|
package mysql
|
|
|
|
|
|
|
|
import (
|
2021-09-14 14:44:02 +00:00
|
|
|
"context"
|
2021-07-29 16:10:34 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2021-07-19 18:08:41 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestLocks(t *testing.T) {
|
2021-07-29 16:10:34 +00:00
|
|
|
ds := CreateMySQLDS(t)
|
|
|
|
defer ds.Close()
|
|
|
|
|
|
|
|
owner1, err := server.GenerateRandomText(64)
|
|
|
|
require.NoError(t, err)
|
|
|
|
owner2, err := server.GenerateRandomText(64)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
// get first lock
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err := ds.Lock(context.Background(), "test", owner1, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
|
|
|
|
|
|
|
// renew current lock
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test", owner1, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
|
|
|
|
|
|
|
// owner2 tries to get the lock but fails
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test", owner2, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.False(t, locked)
|
|
|
|
|
|
|
|
// owner2 gets a new lock that expires quickly
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test-expired", owner2, 1*time.Second)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
|
|
|
|
|
|
|
time.Sleep(3 * time.Second)
|
|
|
|
|
|
|
|
// owner1 gets the same lock because it's now expired
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test-expired", owner1, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
|
|
|
|
|
|
|
// unlocking clears the lock
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test", owner1, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
2021-09-14 14:44:02 +00:00
|
|
|
err = ds.Unlock(context.Background(), "test", owner1)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
// owner2 tries to get the lock but fails
|
2021-09-14 14:44:02 +00:00
|
|
|
locked, err = ds.Lock(context.Background(), "test", owner2, 1*time.Minute)
|
2021-07-29 16:10:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
assert.True(t, locked)
|
2021-07-19 18:08:41 +00:00
|
|
|
}
|