Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,13 +430,15 @@ different arrays). The FlashArray host object is per node: it is found by
the node's IQN/NQN and created as `FA_HOST_NAME` (hostname) if missing.

A block volume is single-writer. On a drain swarm starts the new task while
the old one is still stopping, so a mount first waits (up to 30s per attempt)
for the other host to release the volume itself, which its unmount does once
the old container is gone. Only a host that keeps it past `FA_PREEMPT_GRACE`,
counted across Docker's retries and restarted whenever the holder changes,
is presumed dead and has its connection
taken over (`FA_PREEMPT_RWO=true`); until then the mount fails with a
"waiting for … to release" error and swarm retries. A grace of `0` restores
the old one is still stopping, so a mount first waits for the other host to
release the volume itself, which its unmount does once the old container is
gone. Only a host that keeps it past `FA_PREEMPT_GRACE`, counted across
Docker's retries and restarted whenever the holder changes, is presumed dead
and has its connection taken over (`FA_PREEMPT_RWO=true`). One mount attempt
waits until 15 seconds short of Docker's 2-minute limit, so the default grace
of 90 seconds is waited out and the takeover done in one attempt; with a
longer grace the attempt fails with a "waiting for … to release" error and
swarm retries. A grace of `0` restores
immediate takeover, which cut writes a live node was still flushing and
corrupted XFS. Two nodes that mount a free volume at the same moment both
connect it; each then looks for the other, and one that sees it disconnects
Expand Down Expand Up @@ -466,7 +468,9 @@ is 0), so no other node preempts a volume that is only lingering.
**Services on these volumes must update and roll back `stop-first`** (swarm's
default). With `start-first` the old task keeps the volume until the new one
is healthy, the new one cannot mount until the old one lets go, and after
`FA_PREEMPT_GRACE` the old, still-live task is preempted mid-write.
`FA_PREEMPT_GRACE` the old, still-live task is preempted mid-write. Because
the new task's mount waits out the grace in one attempt, the update itself
does not fail on the way.

## Migrating from the Pure plugin

Expand Down
4 changes: 2 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ func ValidateTimeouts(attach, grace time.Duration) error {
}

// ValidateLinger keeps a lingering volume clear of preemption: another node
// waiting for it gives up a Mount attempt after 30s and preempts after the
// grace, and a lingering volume is still mounted on this one.
// waiting for it preempts after the grace, and a lingering volume is still
// mounted on this one.
func ValidateLinger(linger, grace time.Duration) error {
switch {
case linger < 0:
Expand Down
41 changes: 32 additions & 9 deletions internal/driver/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ func (d *Driver) ctxWithin(limit time.Duration) (context.Context, context.Cancel
}

func (d *Driver) budget(limit time.Duration) time.Duration {
return min(d.cfg.AttachTimeout+maxReleaseWait+30*time.Second, limit)
return min(d.cfg.AttachTimeout+time.Minute, limit)
}

// Create implements plugin.Driver.
Expand Down Expand Up @@ -964,7 +964,8 @@ func (d *Driver) Remove(req *plugin.RemoveRequest) error {

// Mount implements plugin.Driver.
func (d *Driver) Mount(req *plugin.MountRequest) (*plugin.MountResponse, error) {
ctx, cancel := d.ctxWithin(mountBudget)
// All of it, not budget(): takeOver may spend most of it waiting out the grace.
ctx, cancel := context.WithTimeout(context.Background(), mountBudget)
defer cancel()
an, vol, unlock, err := d.resolveLocked(ctx, req.Name)
defer unlock()
Expand Down Expand Up @@ -1320,10 +1321,15 @@ func (d *Driver) releaseHost(ctx context.Context, an, serial, dev string) (detac
return detachErr, disconnectErr
}

// releasePoll and maxReleaseWait are variables so tests needn't wait.
// A Mount waits for the other host up to its deadline less attachReserve, the
// time kept to attach after a preempt, so the default grace fits one attempt.
// Each failed attempt is a failed task, which pauses or rolls back a
// start-first update that moves a volume to another node. maxReleaseWait caps
// the wait for tests. Variables so tests needn't wait.
var (
releasePoll = 2 * time.Second
maxReleaseWait = 30 * time.Second
attachReserve = 15 * time.Second
maxReleaseWait = mountBudget
)

// takeOver makes sure no other host holds an. A block volume is single-writer.
Expand All @@ -1342,19 +1348,36 @@ func (d *Driver) takeOver(ctx context.Context, an, dockerName string) error {
}
held := d.markHeld(an, others)
wait := min(d.cfg.PreemptGrace-time.Since(held), maxReleaseWait)
deadline := time.Now().Add(wait)
for len(others) > 0 && time.Now().Before(deadline) && ctx.Err() == nil {
if dl, ok := ctx.Deadline(); ok {
wait = min(wait, time.Until(dl)-attachReserve)
}
// The polls run on their own deadline so a slow answer can't eat the
// attach reserve.
waitCtx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
for len(others) > 0 {
select {
case <-ctx.Done():
case <-waitCtx.Done():
case <-time.After(releasePoll):
}
if others, err = d.otherHosts(ctx, an); err != nil {
if waitCtx.Err() != nil {
break
}
cur, err := d.otherHosts(waitCtx, an)
if err != nil {
if ctx.Err() == nil && waitCtx.Err() != nil {
// Whether the holder let go is unknown, so neither release nor preempt.
return fmt.Errorf("volume %s is attached to host %s and the array did not answer before the wait ran out: %w", dockerName, strings.Join(others, ","), err)
}
return err
}
if len(others) > 0 {
if others = cur; len(others) > 0 {
held = d.markHeld(an, others)
}
}
if err := ctx.Err(); err != nil {
return err
}
if len(others) == 0 {
d.clearHeld(an)
d.log.Info("other host released the volume", "volume", dockerName, "waited", time.Since(held).Round(time.Second))
Expand Down
76 changes: 76 additions & 0 deletions internal/driver/driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,82 @@ func TestMountPreemptsOnlyAfterGrace(t *testing.T) {
}
}

// A grace that fits the Mount's budget is waited out in one attempt: a failed
// attempt fails the task, which pauses or rolls back a start-first update.
func TestMountWaitsOutTheGraceInOneAttempt(t *testing.T) {
releasePoll, maxReleaseWait = time.Millisecond, time.Minute
fa, tr, fm := newFakeArray(), &fakeTransport{}, newFakeMounter()
d := newTestDriver(t, fa, tr, fm)
d.cfg.PreemptGrace = 50 * time.Millisecond
_ = d.Create(&plugin.CreateRequest{Name: "v"})
an := d.arrayName("v")
fa.conns[an] = map[string]int{"fenced-node": 7}

if _, err := d.Mount(&plugin.MountRequest{Name: "v", ID: "c"}); err != nil {
t.Fatal(err)
}
if fa.connected(an, "fenced-node") {
t.Fatal("fenced-node not preempted")
}
}

// The wait stops short of the Mount's deadline, keeping time to attach.
func TestReleaseWaitLeavesTimeToAttach(t *testing.T) {
releasePoll, maxReleaseWait = time.Millisecond, time.Minute
oldBudget, oldReserve := mountBudget, attachReserve
mountBudget, attachReserve = 300*time.Millisecond, 250*time.Millisecond
t.Cleanup(func() { mountBudget, attachReserve = oldBudget, oldReserve })
fa, tr, fm := newFakeArray(), &fakeTransport{}, newFakeMounter()
d := newTestDriver(t, fa, tr, fm)
d.cfg.PreemptGrace = time.Hour
_ = d.Create(&plugin.CreateRequest{Name: "v"})
an := d.arrayName("v")
fa.conns[an] = map[string]int{"other": 7}

start := time.Now()
_, err := d.Mount(&plugin.MountRequest{Name: "v", ID: "c"})
if err == nil || !strings.Contains(err.Error(), "waiting up to") {
t.Fatalf("expected to wait for other, got %v", err)
}
if waited := time.Since(start); waited >= mountBudget {
t.Fatalf("waited %s, past the mount budget", waited)
}
}

// A poll the array is slow to answer ends with the wait, not the Mount, and
// neither releases nor preempts on what it never learned.
func TestSlowPollStopsAtTheWaitCutoff(t *testing.T) {
releasePoll, maxReleaseWait = time.Millisecond, time.Minute
oldBudget, oldReserve := mountBudget, attachReserve
mountBudget, attachReserve = 2*time.Second, 1900*time.Millisecond
t.Cleanup(func() { mountBudget, attachReserve = oldBudget, oldReserve })
fa, tr, fm := newFakeArray(), &fakeTransport{}, newFakeMounter()
d := newTestDriver(t, fa, tr, fm)
d.cfg.PreemptGrace = time.Hour
_ = d.Create(&plugin.CreateRequest{Name: "v"})
an := d.arrayName("v")
fa.conns[an] = map[string]int{"other": 7}
fa.slowConns = map[string]bool{}
go func() {
time.Sleep(20 * time.Millisecond)
fa.mu.Lock()
fa.slowConns[an] = true
fa.mu.Unlock()
}()

start := time.Now()
_, err := d.Mount(&plugin.MountRequest{Name: "v", ID: "c"})
if err == nil || !strings.Contains(err.Error(), "did not answer before the wait ran out") {
t.Fatalf("expected the wait to end on the slow poll, got %v", err)
}
if waited := time.Since(start); waited > time.Second {
t.Fatalf("waited %s: the slow poll ran into the attach reserve", waited)
}
if !fa.connected(an, "other") {
t.Fatal("preempted on a poll that never answered")
}
}

// The grace belongs to the holder: a host that only just took the volume is
// live and must get the full grace, however long an earlier holder kept it.
func TestPreemptGraceRestartsWhenHolderChanges(t *testing.T) {
Expand Down
27 changes: 16 additions & 11 deletions internal/mounter/mounter.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,20 @@ func (m *execMounter) FilesystemMounted(target string) (bool, error) {
return src != "" && src != guardSource, nil
}

// topMountSource returns the source of the most recent mount on target (later
// mountinfo lines stack on earlier ones), or "" when nothing is mounted there.
func topMountSource(target string) (string, error) {
src, _, err := topMount(target)
return src, err
}

// topMount returns the source and major:minor of the most recent mount on
// target (later mountinfo lines stack on earlier ones), or "" when nothing is
// mounted there.
func topMount(target string) (src, majmin string, err error) {
f, err := os.Open(mountinfoPath)
if err != nil {
return "", err
return "", "", err
}
defer f.Close()
var top string
sc := bufio.NewScanner(f)
for sc.Scan() {
fields := strings.Fields(sc.Text())
Expand All @@ -178,12 +183,12 @@ func topMountSource(target string) (string, error) {
}
for i := 6; i+2 < len(fields); i++ {
if fields[i] == "-" {
top = unescape(fields[i+2])
src, majmin = unescape(fields[i+2]), fields[2]
break
}
}
}
return top, sc.Err()
return src, majmin, sc.Err()
}

func (m *execMounter) IsMounted(target string) (bool, error) {
Expand Down Expand Up @@ -279,14 +284,14 @@ func (m *execMounter) Shutdown(target string) error {
}

// InUseByContainer only sees namespaces that still have a process in them,
// which is what matters: a stopped container's namespace has none.
// which is what matters: a stopped container's namespace has none. The device
// comes from mountinfo, not stat: stat fails with EIO on a filesystem shut
// down by a preempt, and teardown then retried forever.
func (m *execMounter) InUseByContainer(mountpoint string) (bool, error) {
var st syscall.Stat_t
if err := syscall.Stat(mountpoint, &st); err != nil {
_, want, err := topMount(mountpoint)
if err != nil || want == "" {
return false, err
}
dev := uint64(st.Dev) // uint32 on some arches
want := fmt.Sprintf("%d:%d", (dev>>8)&0xfff|(dev>>32)&^0xfff, dev&0xff|(dev>>12)&^0xff)

seen := map[string]bool{}
for _, p := range []string{"1", "self"} {
Expand Down
24 changes: 13 additions & 11 deletions internal/mounter/mounter_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package mounter

import (
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
)

Expand Down Expand Up @@ -63,19 +61,20 @@ func TestMountedAt(t *testing.T) {
}
}

// The device comes from mountinfo, so a filesystem shut down by a preempt,
// whose mountpoint stat fails with EIO, is still checked.
func TestInUseByContainer(t *testing.T) {
mp := t.TempDir()
var st syscall.Stat_t
if err := syscall.Stat(mp, &st); err != nil {
const mp, majmin = "/mnt/flasharray/v", "253:3"
fixture := filepath.Join(t.TempDir(), "mountinfo")
info := "300 29 0:90 / " + mp + " ro,relatime shared:149 - tmpfs " + guardSource + " ro,size=4k,mode=555\n" +
"301 300 " + majmin + " / " + mp + " rw,relatime shared:150 - xfs /dev/mapper/mpatha rw,attr2\n"
if err := os.WriteFile(fixture, []byte(info), 0o644); err != nil {
t.Fatal(err)
}
dev := uint64(st.Dev)
majmin := fmt.Sprintf("%d:%d", (dev>>8)&0xfff|(dev>>32)&^0xfff, dev&0xff|(dev>>12)&^0xff)

proc := t.TempDir()
old := procRoot
procRoot = proc
t.Cleanup(func() { procRoot = old })
oldInfo, oldProc := mountinfoPath, procRoot
mountinfoPath, procRoot = fixture, proc
t.Cleanup(func() { mountinfoPath, procRoot = oldInfo, oldProc })
addProc := func(pid, ns, mountinfo string) {
t.Helper()
if err := os.MkdirAll(filepath.Join(proc, pid, "ns"), 0o755); err != nil {
Expand Down Expand Up @@ -105,6 +104,9 @@ func TestInUseByContainer(t *testing.T) {
if used, err := m.InUseByContainer(mp); err != nil || !used {
t.Fatalf("container namespace missed: used=%v err=%v", used, err)
}
if used, err := m.InUseByContainer("/mnt/flasharray/gone"); err != nil || used {
t.Fatalf("nothing mounted there: used=%v err=%v", used, err)
}
}

func TestFilesystemMountedLooksPastTheGuard(t *testing.T) {
Expand Down