mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
mount: take a live mount over without unmounting it (#13382)
* go.mod: take seaweedfs/go-fuse from #5 until it is released The handover builds on the server API of seaweedfs/go-fuse#5: Server.Stop, Start and Shutdown, Server.Dev and NewServerFromDev. Until that pull request is merged and tagged, go-fuse is replaced by its branch; the replace goes with the release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: quiesce the background writers, pause and resume the metadata subscription, and give a takeover its own cache directories The periodic metadata flush, the proactive chunk flush and the idle directory eviction check a gate before each tick, so a handover can stop them and wait for the work they run. PauseMetadataFollow and ResumeMetadataFollow end the subscription and start it again from the position of the last event it handled, with the filer.conf follower it had. A successor keeps the subscription's client id (the signature crosses), so it subscribes at an epoch above its predecessor's: the filer then replaces the old subscription instead of refusing the new one as a duplicate and making it wait for a retry. A process that takes a mount over (Option.Takeover) uses <id>.t<pid> for its read and swap directories, as the predecessor still uses <id>. A normal start removes the stale <id>.t* siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: the handover protocol, old side and new side A running mount listens on a unix socket (0600; the peer's uid is checked with SO_PEERCRED on both ends, ours or root). A successor connects, says hello, receives the FUSE fd with the INIT negotiation and the exported state, answers ready, and is told go. The hello carries the mount directory, the filer path and the options the state depends on (writeback cache, routed locks, nfs export): the running mount refuses a mismatch, a blocked lock request and a peer chunk server before it flushes or pauses. A connection closed before its hello is a probe (HandoverAnswers), logged at V(1). Until go the old side rolls back at every step (pre-flush, quiesce, stop, final flush, pause of the subscription, export, ready) and keeps serving: the subscription restarts from its position, the background writers and the nfs export writer resume, the server reads again. After go it closes its server without unmounting and marks itself committed, so its exit leaves the mount and the successor's sockets alone. The fd is carried by a fixed-size header written with one sendmsg and read with one recvmsg; control messages are length-prefixed JSON, and the state stream and the go frame are read through one bufio.Reader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: a new mount on a live mount directory takes it over A weed mount started on a directory that is mounted already, whose weed mount answers on the handover socket, takes that mount over instead of replacing it: open files, locks and working directories inside it carry on. - Every Linux mount listens on a socket next to its local gRPC socket, <localSocket without .sock>.handover.sock, /tmp/seaweedfs-mount-<hash>.handover.sock by default; a deployment that keeps the local socket where the next mount process can reach it gets the same for this one. Not with -peer.enable, whose listen port has a single owner, nor with -filer.tokenFile, as read tokens and chunk proofs do not cross. - Those mounts read /dev/fuse in the stoppable way. - A new mount takes over when its directory is in the mount table and a process answers on the socket. When none answers (none runs, it crashed, it is an older weed), the mount proceeds as before. - A takeover skips the pre-mount unmount and the mount point check, binds the local gRPC socket and the handover socket only after the old process said go, and uses cache directories of its own. One that does not go through exits non-zero and leaves the running mount serving; to mount anew, stop that weed mount or unmount first, as for a busy mount today. - After go, a socket the new process cannot bind is logged, not fatal: the mount goes on without mount.configure or without a next handover, rather than going down. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: end-to-end handover test test/fuse_handover starts a real weed mini and weed mount processes with the same arguments, and lets each new one take the live mount over, twice in a row and once more after a refusal. An appending writer, a streaming reader, an mmap, an unlinked temp file, an unclosed new file, a directory walk and a listing in progress, a held flock and POSIX lock, a process working inside the mount and a renamed open file run through it. It checks that the mount was never unmounted (mount id and st_dev), that the old processes exit 0, that a takeover refused because a SETLKW is blocked, or because the options differ, leaves the mount serving without a pause, and prints the pause. With HANDOVER_SCALE_FILES=<n> a second test creates n files, takes the mount over, and logs the pause and the size of the state. On a 2-vCPU VM: 10k files 18 ms and 360 KB, 100k files 134 ms and 2.9 MB, 300k files 410 ms and 7.1 MB. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: answer the first review of the handover The checks before anything pauses: - The hello carries the filer addresses, sorted, and -defaultPermissions: the running mount refuses a successor of other filers (its open files and inode table name entries and chunks of this filer) or of another default_permissions (without it the kernel leaves the permission checks to the mount, and a successor that counts on the kernel would make none). - A successor finds the live mount for a relative -dir and for a path with a space: the mount table is read with the absolute path, and its octal escapes (\040 ...) are undone, which checkMountPointAvailable gets too. The local socket keeps its name. Rollback and commitment: - A rolled back handover starts the FUSE server first. A subscription that did not end in time may wait for a request to be served, and the rollback waited for it before the server read again. The subscription now starts again in the background once the old one has ended; until then a new handover is refused before anything pauses. - A successor reads the filer configuration (PrepareBackgroundTasks) before it connects, since a failure there after go would end the process with nobody serving the mount, and it does not create the mount root, which the running mount serves. - A reconnecting subscription publishes its epoch, so that a later one with the same client id starts above it instead of being refused as a duplicate. - A takeover's cache directories are <id>.t<pid>-<random>: two processes that each run as pid 1 of a container sharing the cache base got the same directory. Tests: - The protocol tests run on Linux only, as the protocol does; those of the background gate and of the cache directories run everywhere. - The end-to-end harness bounds the probes that go into the mount, waits until the SETLKW helper sleeps in FUSE before it asks for a takeover, counts only complete reader passes, closes the retained files on failure, rechecks a log after its process exited, and cleans up only mounts below its own directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read the filer configuration again after a takeover A successor reads the filer configuration before it connects, so that nothing that can fail is left for after go. A change that the predecessor applied in between does not come again with the subscription, which starts where the predecessor stopped, and the successor kept the configuration it had read. It now reads it once more when it starts its background tasks; on failure the one read before stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: build the moved handover tests where their helpers are handover_quiesce_test.go uses newHandoverWFS, which is defined in a test file built everywhere but on Windows; it gets the same constraint. The mount readiness probe of the end-to-end test is also capped at the remaining deadline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: renew the routed lock leases before the background tasks wait on the filer A successor with -dlm holds the routed locks its predecessor took, and the filer drops their leases 15 s after the last renewal. StartBackgroundTasks began renewing only after it had read the filer configuration again, a filer call that can take longer than that. The renewal now starts first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare -readOnly and -allowOthers in the hello, and drop a filer configuration that is gone - -readOnly and -allowOthers are kernel mount options, fixed when the mount was made: a successor started with others would run with the old ones without knowing. The hello carries them and the running mount refuses a mismatch before anything pauses. - The filer configuration read again after a takeover clears the one read before when the file is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: close the held lock files of the handover workload on failure The flock and POSIX lock files are opened before the takeovers and closed in finish(); an assertion that fails in between left them open. They get a cleanup right after they open, like the other retained files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare the kernel's mount options as -o sets them too, and retry the filer configuration read after a takeover - allow_other, ro and default_permissions can come from -o as well as from their flags. The hello compared the flags only, so a successor started with -allowOthers=false could take over a mount made with -o allow_other. The mount now records the kernel's options from both (KernelReadOnly, KernelAllowOther, KernelDefaultPermissions), and the hello compares those. - The read of the filer configuration after a takeover is tried three times before the subscription starts, which can wait: it starts where the predecessor stopped. Only if all fail does the configuration read before the takeover stay until its next change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: drop the WEED_MOUNT_HANDOVER_STOP_TIMEOUT test hook The drain bound stays at its 10 s default; the end-to-end tests wait well over that for a refusal, so they do not need a setting of their own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: close a descriptor that comes with a refused handover Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: take a mount over when the new process shares a filer with it The hello required the sorted -filer list to match exactly, so a successor started after filers were added to the cluster or taken out of it was refused, and the old mount kept serving. A filer serves one filer store: one filer in common means the store that the open files, the inode table and the chunks belong to. Compare the filers as host:port, as ServerAddress.Equals does, so that an address written with its gRPC port counts as the same filer, and refuse only lists with no filer in common. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: run the FUSE mount handover end-to-end tests test/fuse_handover starts a real weed mini and weed mount processes and lets each new mount take the live one over; no workflow ran it, so only the unit tests guarded the handover in CI. The job follows the FUSE DLM one: it repairs the fusermount3 setuid bit, builds weed and runs the tests with WEED_BINARY. The tests mount as the runner user without allow_other, so fuse.conf is left alone. A failed run uploads the weed logs, which the harness keeps in /tmp/fuse_handover_*. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: compare the kernel's mount flags in the hello, resolved in order The hello compared ro as "-readOnly or -o ro", and no other mount flag. -readOnly puts ro before the -o options, and both fusermount3 and go-fuse's direct mount apply the options in order, so -readOnly with -o rw mounts read-write while the hello said ro. A successor started with -o noexec, nosuid or nodev also got the old mount's flags without knowing. Resolve the generic flags from the option list go-fuse mounts with, in order, from nosuid and nodev as both mount paths start, and refuse a successor whose flags differ before anything pauses. relatime is left out: the kernel uses it unless noatime or strictatime is set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: do not send a handover control frame the peer would refuse writeControl sized its buffer from the encoded message without a bound, while readControl refuses a frame over maxControlFrame. Refuse the larger frame before allocating, as the reading side does (CodeQL go/allocation-size-overflow). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: unmount the handover e2e mounts with fusermount when fusermount3 is missing The harness detached leftover mounts with fusermount3 only. A fuse2 host, such as CentOS 7 or an Alpine image with the fuse package, has only fusermount, so the last step of TestHandoverEndToEnd failed there after every handover had passed. Try fusermount3, then fusermount. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * go.mod: use go-fuse v2.9.6 instead of the branch of seaweedfs/go-fuse#5 seaweedfs/go-fuse#5 is merged and tagged v2.9.6, whose tree is the one this pull request was tested with (1eec9a8). Drop the replace with the fork and require the release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: whitebear009 <whitebear009@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
28 files changed
+3764
-62
No files matched your search
@@ -0,0 +1,65 @@
|
||||
name: "FUSE Mount Handover Tests"
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'weed/command/mount*.go'
|
||||
- 'weed/mount/**'
|
||||
- 'weed/pb/mount_handover_pb/**'
|
||||
- 'test/fuse_handover/**'
|
||||
- '.github/workflows/fuse-handover.yml'
|
||||
- '.github/actions/fix-fusermount-setuid/**'
|
||||
push:
|
||||
branches: [master]
|
||||
paths:
|
||||
- 'weed/command/mount*.go'
|
||||
- 'weed/mount/**'
|
||||
- 'weed/pb/mount_handover_pb/**'
|
||||
- 'test/fuse_handover/**'
|
||||
- '.github/actions/fix-fusermount-setuid/**'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
fuse-handover:
|
||||
name: FUSE Mount Handover Tests
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
cache: ${{ runner.environment == 'github-hosted' }}
|
||||
|
||||
# The tests mount as the runner user through fusermount3, without
|
||||
# allow_other: nothing to install or configure besides the setuid bit.
|
||||
- name: Repair the fusermount3 setuid bit
|
||||
uses: ./.github/actions/fix-fusermount-setuid
|
||||
|
||||
- name: Build SeaweedFS
|
||||
run: go build -o weed/weed -buildvcs=false ./weed
|
||||
|
||||
- name: Run handover tests
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
WEED_BINARY: ${{ github.workspace }}/weed/weed
|
||||
run: go test -v -count=1 -timeout=20m ./test/fuse_handover/...
|
||||
|
||||
# A failed test keeps the weed logs in /tmp/fuse_handover_*.
|
||||
- name: Upload logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: fuse-handover-test-logs
|
||||
path: /tmp/fuse_handover_*/*.log
|
||||
retention-days: 3
|
||||
@@ -84,7 +84,7 @@ require (
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
github.com/schollz/progressbar/v3 v3.19.1
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.5
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.6
|
||||
github.com/seaweedfs/goexif v1.0.3
|
||||
github.com/seaweedfs/raft v1.2.4
|
||||
github.com/shirou/gopsutil/v4 v4.26.10
|
||||
|
||||
@@ -1104,8 +1104,8 @@ github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vP
|
||||
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
|
||||
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.5 h1:qz3tuAGbUJOPJtaxyP35xW3JT23utywXKer0hoTiJPU=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.5/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.6 h1:sayH13ylR54GXfjqXdZ0RE074FiBNJXxVVs/HFu+t7Q=
|
||||
github.com/seaweedfs/go-fuse/v2 v2.9.6/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
|
||||
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
|
||||
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
|
||||
github.com/seaweedfs/raft v1.2.4 h1:lEBQ9seDSGrJNs2WitMgfYpaDxLgh9qukm1IJTEV1hk=
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
//go:build linux
|
||||
|
||||
package fuse_handover
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/testutil"
|
||||
)
|
||||
|
||||
// weedProc is a weed process of the test, with its output in a log file.
|
||||
type weedProc struct {
|
||||
name string
|
||||
cmd *exec.Cmd
|
||||
logPath string
|
||||
done chan struct{}
|
||||
err error // set before done is closed
|
||||
}
|
||||
|
||||
func (p *weedProc) exited() (bool, error) {
|
||||
select {
|
||||
case <-p.done:
|
||||
return true, p.err
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *weedProc) log() string {
|
||||
b, _ := os.ReadFile(p.logPath)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// waitLog waits for a line containing substr in the log and returns the last such line.
|
||||
func (p *weedProc) waitLog(substr string, timeout time.Duration) (string, error) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
last := ""
|
||||
for _, line := range strings.Split(p.log(), "\n") {
|
||||
if strings.Contains(line, substr) {
|
||||
last = line
|
||||
}
|
||||
}
|
||||
if last != "" {
|
||||
return last, nil
|
||||
}
|
||||
if exited, err := p.exited(); exited {
|
||||
// It may have logged and exited between the read above and now.
|
||||
for _, line := range strings.Split(p.log(), "\n") {
|
||||
if strings.Contains(line, substr) {
|
||||
last = line
|
||||
}
|
||||
}
|
||||
if last != "" {
|
||||
return last, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s exited (%v) before logging %q", p.name, err, substr)
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return "", fmt.Errorf("%s did not log %q within %v", p.name, substr, timeout)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *weedProc) wait(timeout time.Duration) (error, bool) {
|
||||
select {
|
||||
case <-p.done:
|
||||
return p.err, true
|
||||
case <-time.After(timeout):
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
type cluster struct {
|
||||
t testing.TB
|
||||
weed string
|
||||
base string
|
||||
filer string // host:port.grpcPort, as -filer takes it
|
||||
filerURL string
|
||||
mini *weedProc
|
||||
|
||||
mu sync.Mutex
|
||||
procs []*weedProc
|
||||
}
|
||||
|
||||
func findWeed(t testing.TB) string {
|
||||
if p := os.Getenv("WEED_BINARY"); p != "" {
|
||||
return p
|
||||
}
|
||||
if p, err := exec.LookPath("weed"); err == nil {
|
||||
return p
|
||||
}
|
||||
t.Skip("weed binary not found: build one with `go build -o /path/weed ./weed` and set WEED_BINARY")
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c *cluster) start(name string, env []string, args ...string) *weedProc {
|
||||
logPath := filepath.Join(c.base, name+".log")
|
||||
lf, err := os.Create(logPath)
|
||||
require.NoError(c.t, err)
|
||||
cmd := exec.Command(c.weed, args...)
|
||||
cmd.Stdout, cmd.Stderr = lf, lf
|
||||
cmd.Env = append(os.Environ(), env...)
|
||||
require.NoError(c.t, cmd.Start())
|
||||
p := &weedProc{name: name, cmd: cmd, logPath: logPath, done: make(chan struct{})}
|
||||
go func() {
|
||||
p.err = cmd.Wait()
|
||||
lf.Close()
|
||||
close(p.done)
|
||||
}()
|
||||
c.mu.Lock()
|
||||
c.procs = append(c.procs, p)
|
||||
c.mu.Unlock()
|
||||
return p
|
||||
}
|
||||
|
||||
// startCluster starts weed mini, and arranges for everything the test starts
|
||||
// to be stopped, and every mount below the test directory to be unmounted.
|
||||
func startCluster(t *testing.T) *cluster {
|
||||
c := &cluster{t: t, weed: findWeed(t)}
|
||||
if _, err := os.Stat("/dev/fuse"); err != nil {
|
||||
t.Skip("no /dev/fuse")
|
||||
}
|
||||
var err error
|
||||
c.base, err = os.MkdirTemp("", "fuse_handover_")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(c.stop)
|
||||
|
||||
ports, err := testutil.AllocatePorts(11)
|
||||
require.NoError(t, err)
|
||||
filerPort, filerGrpc := ports[0], ports[1]
|
||||
c.filer = fmt.Sprintf("127.0.0.1:%d.%d", filerPort, filerGrpc)
|
||||
c.filerURL = fmt.Sprintf("127.0.0.1:%d", filerPort)
|
||||
dataDir := filepath.Join(c.base, "data")
|
||||
require.NoError(t, os.MkdirAll(dataDir, 0o755))
|
||||
c.mini = c.start("mini", nil,
|
||||
"-logtostderr=true",
|
||||
"mini",
|
||||
"-dir="+dataDir,
|
||||
"-ip=127.0.0.1", "-ip.bind=127.0.0.1",
|
||||
"-master.port="+strconv.Itoa(ports[2]), "-master.port.grpc="+strconv.Itoa(ports[3]),
|
||||
"-volume.port="+strconv.Itoa(ports[4]), "-volume.port.grpc="+strconv.Itoa(ports[5]),
|
||||
"-filer.port="+strconv.Itoa(filerPort), "-filer.port.grpc="+strconv.Itoa(filerGrpc),
|
||||
"-mq.broker.port="+strconv.Itoa(ports[6]),
|
||||
"-admin.port="+strconv.Itoa(ports[7]), "-admin.port.grpc="+strconv.Itoa(ports[8]), "-admin.port.legacy=0",
|
||||
"-debug.port="+strconv.Itoa(ports[9]),
|
||||
"-s3=false", "-webdav=false", "-admin.ui=false", "-vector=false",
|
||||
"-master.telemetry=false",
|
||||
)
|
||||
require.NoError(t, c.waitHealthy(60*time.Second), "weed mini not ready:\n%s", c.mini.log())
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *cluster) waitHealthy(timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
client := &http.Client{Timeout: time.Second}
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := client.Get("http://" + c.filerURL + "/healthz")
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if exited, err := c.mini.exited(); exited {
|
||||
return fmt.Errorf("mini exited: %v", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("filer not healthy within %v", timeout)
|
||||
}
|
||||
|
||||
func (c *cluster) stop() {
|
||||
c.mu.Lock()
|
||||
procs := append([]*weedProc(nil), c.procs...)
|
||||
c.mu.Unlock()
|
||||
if c.t.Failed() {
|
||||
for _, p := range procs {
|
||||
c.t.Logf("---- %s log (tail) ----\n%s", p.name, tail(p.log(), 60))
|
||||
}
|
||||
}
|
||||
// Mounts first, so unmounting does not wait for a filer that is gone.
|
||||
for i := len(procs) - 1; i >= 0; i-- {
|
||||
p := procs[i]
|
||||
if p.name == "mini" {
|
||||
continue
|
||||
}
|
||||
terminate(p)
|
||||
}
|
||||
for _, mp := range mountsUnder(c.base) {
|
||||
unmountLazily(mp)
|
||||
}
|
||||
if c.mini != nil {
|
||||
terminate(c.mini)
|
||||
}
|
||||
if c.t.Failed() {
|
||||
// /tmp is often memory: keep the logs, not the data.
|
||||
for _, d := range []string{"data", "cache", "mnt"} {
|
||||
os.RemoveAll(filepath.Join(c.base, d))
|
||||
}
|
||||
c.t.Logf("logs kept in %s", c.base)
|
||||
return
|
||||
}
|
||||
os.RemoveAll(c.base)
|
||||
}
|
||||
|
||||
// unmountLazily detaches a mount with whichever fusermount the host has: a
|
||||
// fuse3 host has fusermount3, and a fuse2 host, such as CentOS 7 or an Alpine
|
||||
// image with the fuse package, only fusermount.
|
||||
func unmountLazily(dir string) {
|
||||
for _, helper := range []string{"fusermount3", "fusermount"} {
|
||||
if exec.Command(helper, "-uz", dir).Run() == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func terminate(p *weedProc) {
|
||||
if exited, _ := p.exited(); exited {
|
||||
return
|
||||
}
|
||||
p.cmd.Process.Signal(syscall.SIGTERM)
|
||||
select {
|
||||
case <-p.done:
|
||||
case <-time.After(15 * time.Second):
|
||||
p.cmd.Process.Kill()
|
||||
<-p.done
|
||||
}
|
||||
}
|
||||
|
||||
// withinTimeout runs f and returns its error, or an error once timeout has
|
||||
// passed: a call into a FUSE mount that stopped answering would block for
|
||||
// good. The goroutine of a call that timed out is left behind.
|
||||
func withinTimeout(timeout time.Duration, f func() error) error {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- f() }()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(timeout):
|
||||
return fmt.Errorf("no answer within %v", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
func tail(s string, lines int) string {
|
||||
all := strings.Split(strings.TrimRight(s, "\n"), "\n")
|
||||
if len(all) > lines {
|
||||
all = all[len(all)-lines:]
|
||||
}
|
||||
return strings.Join(all, "\n")
|
||||
}
|
||||
|
||||
// mountInfo is a line of /proc/self/mountinfo.
|
||||
type mountInfo struct {
|
||||
id string
|
||||
dev string
|
||||
point string
|
||||
fstype string
|
||||
}
|
||||
|
||||
func readMountInfo() []mountInfo {
|
||||
f, err := os.Open("/proc/self/mountinfo")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer f.Close()
|
||||
var out []mountInfo
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
fields := strings.Fields(sc.Text())
|
||||
if len(fields) < 10 {
|
||||
continue
|
||||
}
|
||||
sep := 0
|
||||
for i, f := range fields {
|
||||
if f == "-" {
|
||||
sep = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if sep == 0 || sep+1 >= len(fields) {
|
||||
continue
|
||||
}
|
||||
out = append(out, mountInfo{id: fields[0], dev: fields[2], point: fields[4], fstype: fields[sep+1]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mountAt(dir string) (mountInfo, bool) {
|
||||
for _, m := range readMountInfo() {
|
||||
if m.point == dir {
|
||||
return m, true
|
||||
}
|
||||
}
|
||||
return mountInfo{}, false
|
||||
}
|
||||
|
||||
func mountsUnder(dir string) []string {
|
||||
var out []string
|
||||
for _, m := range readMountInfo() {
|
||||
if m.point == dir || strings.HasPrefix(m.point, dir+string(filepath.Separator)) {
|
||||
out = append(out, m.point)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *cluster) mountArgs(dir, localSock, cacheDir string, extra ...string) []string {
|
||||
return append([]string{
|
||||
"-logtostderr=true",
|
||||
"mount",
|
||||
"-filer=" + c.filer,
|
||||
"-dir=" + dir,
|
||||
"-filer.path=/",
|
||||
"-dirAutoCreate",
|
||||
"-allowOthers=false",
|
||||
"-localSocket=" + localSock,
|
||||
"-cacheDir=" + cacheDir,
|
||||
"-cacheCapacityMB=64",
|
||||
"-chunkSizeLimitMB=2",
|
||||
}, extra...)
|
||||
}
|
||||
|
||||
// waitMounted waits until a filesystem is mounted at dir and answers.
|
||||
func waitMounted(p *weedProc, dir string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if m, ok := mountAt(dir); ok && strings.HasPrefix(m.fstype, "fuse") {
|
||||
// A mount that does not answer must not hold this loop up, nor
|
||||
// keep it past its deadline.
|
||||
probe := min(5*time.Second, time.Until(deadline))
|
||||
if err := withinTimeout(probe, func() error { _, err := os.ReadDir(dir); return err }); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if exited, err := p.exited(); exited {
|
||||
return fmt.Errorf("%s exited (%v):\n%s", p.name, err, tail(p.log(), 30))
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("%s: nothing mounted at %s within %v", p.name, dir, timeout)
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//go:build linux
|
||||
|
||||
// Package fuse_handover tests, with real FUSE, a real weed mini and real weed
|
||||
// mount processes, that a running mount can be taken over by a new weed mount
|
||||
// process without unmounting.
|
||||
//
|
||||
// Run it with a weed binary built from the tree:
|
||||
//
|
||||
// go build -o /tmp/weed-handover ./weed
|
||||
// WEED_BINARY=/tmp/weed-handover go test ./test/fuse_handover/ -count=1 -v
|
||||
package fuse_handover
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var unixNs = regexp.MustCompile(`unix_ns=(\d+)`)
|
||||
|
||||
func logNs(t *testing.T, p *weedProc, marker string) int64 {
|
||||
t.Helper()
|
||||
line, err := p.waitLog(marker, 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
m := unixNs.FindStringSubmatch(line)
|
||||
require.NotNil(t, m, "no timestamp in %q", line)
|
||||
ns, err := strconv.ParseInt(m[1], 10, 64)
|
||||
require.NoError(t, err)
|
||||
return ns
|
||||
}
|
||||
|
||||
type mountSetup struct {
|
||||
c *cluster
|
||||
mnt string
|
||||
handoverSock string
|
||||
localSock, cache string
|
||||
env []string
|
||||
gen int
|
||||
}
|
||||
|
||||
func newMountSetup(c *cluster) *mountSetup {
|
||||
return &mountSetup{
|
||||
c: c, mnt: filepath.Join(c.base, "mnt"),
|
||||
// The handover socket is derived from the local socket.
|
||||
handoverSock: filepath.Join(c.base, "local.handover.sock"),
|
||||
localSock: filepath.Join(c.base, "local.sock"),
|
||||
cache: filepath.Join(c.base, "cache"),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mountSetup) args(extra ...string) []string {
|
||||
return m.c.mountArgs(m.mnt, m.localSock, m.cache, extra...)
|
||||
}
|
||||
|
||||
func (m *mountSetup) name() string { m.gen++; return fmt.Sprintf("mount%d", m.gen) }
|
||||
|
||||
// takeover starts a new mount on the live directory, with the same options,
|
||||
// waits until it serves and the old one has exited, and returns the new
|
||||
// process and the pause between the old one stopping to read requests and the
|
||||
// new one serving.
|
||||
func (m *mountSetup) takeover(t *testing.T, old *weedProc) (*weedProc, time.Duration) {
|
||||
t.Helper()
|
||||
p := m.c.start(m.name(), m.env, m.args()...)
|
||||
_, err := p.waitLog("taking the mount over", 30*time.Second)
|
||||
require.NoError(t, err, "%s did not see the live mount:\n%s", p.name, tail(p.log(), 30))
|
||||
served := logNs(t, p, "handover: serving")
|
||||
stopped := logNs(t, old, "handover: stop begin")
|
||||
_, err = p.waitLog("handover: listening on", 30*time.Second)
|
||||
require.NoError(t, err, "%s", tail(p.log(), 30))
|
||||
exitErr, ok := old.wait(30 * time.Second)
|
||||
require.True(t, ok, "the old process %s did not exit:\n%s", old.name, tail(old.log(), 30))
|
||||
require.NoError(t, exitErr, "the old process %s must exit 0:\n%s", old.name, tail(old.log(), 30))
|
||||
return p, time.Duration(served - stopped)
|
||||
}
|
||||
|
||||
func waitWritable(t *testing.T, mnt string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
probe := filepath.Join(mnt, ".probe")
|
||||
for {
|
||||
err := withinTimeout(10*time.Second, func() error {
|
||||
if err := os.WriteFile(probe, []byte("probe"), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := os.ReadFile(probe)
|
||||
if err == nil && string(b) != "probe" {
|
||||
err = fmt.Errorf("read back %q", b)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
os.Remove(probe)
|
||||
return
|
||||
}
|
||||
require.True(t, time.Now().Before(deadline), "mount not writable: %v", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandoverEndToEnd(t *testing.T) {
|
||||
c := startCluster(t)
|
||||
m := newMountSetup(c)
|
||||
|
||||
a := c.start(m.name(), m.env, m.args()...)
|
||||
require.NoError(t, waitMounted(a, m.mnt, 60*time.Second))
|
||||
_, err := a.waitLog("handover: listening on", 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
waitWritable(t, m.mnt)
|
||||
|
||||
before, ok := mountAt(m.mnt)
|
||||
require.True(t, ok)
|
||||
var st0 syscall.Stat_t
|
||||
require.NoError(t, syscall.Stat(m.mnt, &st0))
|
||||
|
||||
w := &workloads{t: t, mnt: m.mnt, stop: make(chan struct{})}
|
||||
w.setup()
|
||||
w.start()
|
||||
time.Sleep(time.Second)
|
||||
|
||||
b, pause1 := m.takeover(t, a)
|
||||
t.Logf("handover 1: pause %v (stop begin in %s to serving in %s)", pause1, a.name, b.name)
|
||||
w.afterHandover(1)
|
||||
time.Sleep(time.Second)
|
||||
|
||||
cp, pause2 := m.takeover(t, b)
|
||||
t.Logf("handover 2: pause %v (stop begin in %s to serving in %s)", pause2, b.name, cp.name)
|
||||
w.afterHandover(2)
|
||||
time.Sleep(time.Second)
|
||||
|
||||
w.finish()
|
||||
t.Logf("longest append gap %v, longest stat of the mount %v, appended %d lines, read %d MiB in %d passes, %d walks",
|
||||
time.Duration(w.appendGap.Load()), time.Duration(w.probeMax.Load()),
|
||||
w.appended.Load(), w.readerBytes.Load()>>20, w.readerPass.Load(), w.walkPasses.Load())
|
||||
|
||||
// The mount was never unmounted.
|
||||
after, ok := mountAt(m.mnt)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, before.id, after.id, "mount id in /proc/self/mountinfo")
|
||||
var st1 syscall.Stat_t
|
||||
require.NoError(t, syscall.Stat(m.mnt, &st1))
|
||||
require.Equal(t, st0.Dev, st1.Dev, "st_dev of the mount")
|
||||
|
||||
// Only the live process keeps a cache directory: <id>.t<pid>.
|
||||
entries, err := os.ReadDir(m.cache)
|
||||
require.NoError(t, err)
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
require.Len(t, names, 1, "cache directories left: %v", names)
|
||||
require.True(t, strings.Contains(names[0], ".t"+strconv.Itoa(cp.cmd.Process.Pid)+"-"), "cache directory %s of process %d", names[0], cp.cmd.Process.Pid)
|
||||
|
||||
// The new process's subscription replaced the old one's at once.
|
||||
for _, p := range []*weedProc{b, cp} {
|
||||
require.NotContains(t, p.log(), "duplicated local subscription", "%s had to retry its metadata subscription", p.name)
|
||||
}
|
||||
|
||||
// The sockets belong to the live process.
|
||||
for _, sock := range []string{m.handoverSock, m.localSock} {
|
||||
fi, err := os.Stat(sock)
|
||||
require.NoError(t, err, "%s was unlinked by an exiting process", sock)
|
||||
require.NotZero(t, fi.Mode()&os.ModeSocket)
|
||||
}
|
||||
|
||||
// A handover that is refused leaves the mount working and the old process
|
||||
// serving: a SETLKW is blocked in it, which is refused before anything
|
||||
// pauses.
|
||||
lockFile := filepath.Join(m.mnt, "refuse.lock")
|
||||
require.NoError(t, os.WriteFile(lockFile, []byte("x"), 0o644))
|
||||
p1 := startHelper(t, m.mnt, "holdposix", lockFile)
|
||||
line, err := p1.line(20 * time.Second)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "locked", line)
|
||||
p2 := startHelper(t, m.mnt, "setlkw", lockFile)
|
||||
waitBlockedInFuse(t, p2.cmd.Process.Pid)
|
||||
|
||||
stopsBeforeRefusal := strings.Count(cp.log(), "handover: stop begin")
|
||||
d := c.start(m.name(), m.env, m.args()...)
|
||||
exitErr, ok := d.wait(60 * time.Second)
|
||||
require.True(t, ok, "the refused takeover did not exit:\n%s", tail(d.log(), 30))
|
||||
var ee *exec.ExitError
|
||||
require.ErrorAs(t, exitErr, &ee, "a refused takeover must exit non-zero")
|
||||
require.NotZero(t, ee.ExitCode())
|
||||
require.Contains(t, d.log(), "refused the handover")
|
||||
require.Contains(t, d.log(), "lock requests are blocked")
|
||||
require.Contains(t, d.log(), "keeps serving it")
|
||||
require.Equal(t, stopsBeforeRefusal, strings.Count(cp.log(), "handover: stop begin"), "the running mount paused although a lock request was blocked in it")
|
||||
t.Logf("refused takeover exits %d: %s", ee.ExitCode(), lastMatching(d.log(), "refused the handover"))
|
||||
|
||||
exited, _ := cp.exited()
|
||||
require.False(t, exited, "the old process must keep serving after a refusal")
|
||||
require.Contains(t, cp.log(), "this mount keeps serving")
|
||||
again, ok := mountAt(m.mnt)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, before.id, again.id)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(m.mnt, "after-refusal.txt"), []byte("still here"), 0o644))
|
||||
got, err := os.ReadFile(filepath.Join(m.mnt, "after-refusal.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "still here", string(got))
|
||||
|
||||
// The blocked SETLKW completes when the lock is released.
|
||||
p1.stdin.Close()
|
||||
line, err = p2.line(20 * time.Second)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "locked", line, "the blocked SETLKW after the refusal")
|
||||
p2.stdin.Close()
|
||||
p1.cmd.Wait()
|
||||
p2.cmd.Wait()
|
||||
|
||||
// With nothing blocked, a handover goes through after the refusal.
|
||||
e, pause3 := m.takeover(t, cp)
|
||||
t.Logf("handover 3, after a refusal: pause %v", pause3)
|
||||
got, err = os.ReadFile(filepath.Join(m.mnt, "after-refusal.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "still here", string(got))
|
||||
|
||||
// A new mount with other options is refused before the running one
|
||||
// pauses, and exits non-zero; the running mount serves on.
|
||||
stopsBefore := strings.Count(e.log(), "handover: stop begin")
|
||||
f := c.start(m.name(), m.env, m.args("-writebackCache")...)
|
||||
exitErr, ok = f.wait(60 * time.Second)
|
||||
require.True(t, ok, "the takeover with other options did not exit:\n%s", tail(f.log(), 30))
|
||||
require.ErrorAs(t, exitErr, &ee, "a refused takeover must exit non-zero")
|
||||
require.Contains(t, f.log(), "options differ")
|
||||
require.Equal(t, stopsBefore, strings.Count(e.log(), "handover: stop begin"), "the running mount paused for a successor with other options")
|
||||
exited, _ = e.exited()
|
||||
require.False(t, exited, "the running mount must keep serving")
|
||||
t.Logf("takeover with other options: %s", lastMatching(f.log(), "options differ"))
|
||||
|
||||
// A clean stop of the live process unmounts.
|
||||
terminate(e)
|
||||
// weed unmounts through "fusermount", which a host with only fusermount3
|
||||
// does not have, and the test's own mmap keeps the mount busy: finish it
|
||||
// lazily if weed could not.
|
||||
if _, ok := mountAt(m.mnt); ok {
|
||||
t.Logf("the mount outlived its last process (weed's own unmount: %s)", lastMatching(e.log(), "failed to unmount"))
|
||||
unmountLazily(m.mnt)
|
||||
}
|
||||
require.Eventually(t, func() bool { _, ok := mountAt(m.mnt); return !ok }, 20*time.Second, 100*time.Millisecond, "mount still present after the last process stopped")
|
||||
}
|
||||
|
||||
func lastMatching(log, substr string) string {
|
||||
last := ""
|
||||
for _, l := range strings.Split(log, "\n") {
|
||||
if strings.Contains(l, substr) {
|
||||
last = l
|
||||
}
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
// waitBlockedInFuse waits until a thread of the process sleeps in a FUSE
|
||||
// request, so that the lock request it makes has reached the mount, then a
|
||||
// little longer for the mount to have read it. Without a readable wchan it
|
||||
// waits a second, as a fallback.
|
||||
func waitBlockedInFuse(t *testing.T, pid int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
threads, _ := filepath.Glob(fmt.Sprintf("/proc/%d/task/*/wchan", pid))
|
||||
for _, path := range threads {
|
||||
if b, err := os.ReadFile(path); err == nil && (strings.Contains(string(b), "fuse") || strings.Contains(string(b), "request_wait_answer")) {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Logf("no thread of %d was seen waiting in FUSE; going on after a second", pid)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//go:build linux
|
||||
|
||||
package fuse_handover
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var stateBytesRe = regexp.MustCompile(`state_bytes=(\d+)`)
|
||||
|
||||
// TestHandoverPauseByInodes measures the pause of a handover against the
|
||||
// number of inodes the kernel holds: the inode table is the bulk of the state
|
||||
// that crosses. Creating the files takes minutes, so it only runs with
|
||||
// HANDOVER_SCALE_FILES=<number of files>.
|
||||
func TestHandoverPauseByInodes(t *testing.T) {
|
||||
files, _ := strconv.Atoi(os.Getenv("HANDOVER_SCALE_FILES"))
|
||||
if files <= 0 {
|
||||
t.Skip("set HANDOVER_SCALE_FILES=<number of files> to run")
|
||||
}
|
||||
c := startCluster(t)
|
||||
m := newMountSetup(c)
|
||||
a := c.start(m.name(), m.env, m.args()...)
|
||||
require.NoError(t, waitMounted(a, m.mnt, 60*time.Second))
|
||||
_, err := a.waitLog("handover: listening on", 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
waitWritable(t, m.mnt)
|
||||
|
||||
// Empty files in directories of 1000. The kernel keeps the inode of each
|
||||
// file it created, so the mount has one table entry per file.
|
||||
const perDir, workers = 1000, 16
|
||||
dirs := (files + perDir - 1) / perDir
|
||||
start := time.Now()
|
||||
var next, failed atomic.Int64
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < workers; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
d := int(next.Add(1)) - 1
|
||||
if d >= dirs {
|
||||
return
|
||||
}
|
||||
dir := filepath.Join(m.mnt, fmt.Sprintf("scale/d%05d", d))
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
failed.Add(1)
|
||||
return
|
||||
}
|
||||
for i := 0; i < perDir && d*perDir+i < files; i++ {
|
||||
f, err := os.Create(filepath.Join(dir, fmt.Sprintf("f%04d", i)))
|
||||
if err != nil {
|
||||
failed.Add(1)
|
||||
return
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
require.Zero(t, failed.Load(), "creating the files")
|
||||
t.Logf("created %d files in %d directories in %v", files, dirs, time.Since(start).Round(time.Millisecond))
|
||||
|
||||
b, pause := m.takeover(t, a)
|
||||
line, err := b.waitLog("handover: serving", 30*time.Second)
|
||||
require.NoError(t, err)
|
||||
stateBytes := int64(0)
|
||||
if sm := stateBytesRe.FindStringSubmatch(line); sm != nil {
|
||||
stateBytes, _ = strconv.ParseInt(sm[1], 10, 64)
|
||||
}
|
||||
t.Logf("%d files: pause %v, state %d bytes (%.1f bytes per file)", files, pause, stateBytes, float64(stateBytes)/float64(files))
|
||||
|
||||
// The new process resolves the inodes the kernel still holds: every file
|
||||
// of a few directories stats without a lookup failure.
|
||||
for _, d := range []int{0, dirs / 2, dirs - 1} {
|
||||
entries, err := os.ReadDir(filepath.Join(m.mnt, fmt.Sprintf("scale/d%05d", d)))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, entries)
|
||||
for _, e := range entries {
|
||||
_, err := e.Info()
|
||||
require.NoError(t, err, "stat %s after the handover", e.Name())
|
||||
}
|
||||
}
|
||||
|
||||
terminate(b)
|
||||
if _, ok := mountAt(m.mnt); ok {
|
||||
unmountLazily(m.mnt)
|
||||
}
|
||||
require.Eventually(t, func() bool { _, ok := mountAt(m.mnt); return !ok }, 20*time.Second, 100*time.Millisecond)
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
//go:build linux
|
||||
|
||||
package fuse_handover
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
blockSize = 1 << 20
|
||||
bigBlocks = 128 // streaming reader file: 128 MiB
|
||||
mmapBlocks = 4
|
||||
treeDirs = 12
|
||||
treeFiles = 30
|
||||
listFiles = 600
|
||||
)
|
||||
|
||||
// blockData is the content of 1 MiB block idx of a test file.
|
||||
func blockData(seed, idx int) []byte {
|
||||
r := rand.New(rand.NewPCG(uint64(seed), uint64(idx)))
|
||||
b := make([]byte, blockSize)
|
||||
for i := 0; i < len(b); i += 8 {
|
||||
v := r.Uint64()
|
||||
for j := 0; j < 8; j++ {
|
||||
b[i+j] = byte(v >> (8 * j))
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
type failures struct {
|
||||
mu sync.Mutex
|
||||
list []string
|
||||
}
|
||||
|
||||
func (f *failures) addf(format string, args ...any) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.list) < 50 {
|
||||
f.list = append(f.list, fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (f *failures) require(t *testing.T) {
|
||||
t.Helper()
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
require.Empty(t, f.list, "operations failed during the handover")
|
||||
}
|
||||
|
||||
// helper runs the test binary as a helper process, so that the test has
|
||||
// processes other than itself to hold and contend locks, and to sit in a
|
||||
// working directory inside the mount.
|
||||
type helper struct {
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
out *bufio.Reader
|
||||
}
|
||||
|
||||
func startHelper(t *testing.T, dir, mode string, args ...string) *helper {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcess$")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "FUSE_HANDOVER_HELPER="+mode, "FUSE_HANDOVER_ARGS="+strings.Join(args, "\n"))
|
||||
in, err := cmd.StdinPipe()
|
||||
require.NoError(t, err)
|
||||
out, err := cmd.StdoutPipe()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cmd.Start())
|
||||
h := &helper{cmd: cmd, stdin: in, out: bufio.NewReader(out)}
|
||||
t.Cleanup(func() { h.stdin.Close(); cmd.Process.Kill(); cmd.Wait() })
|
||||
return h
|
||||
}
|
||||
|
||||
// line reads one output line, or fails after the timeout.
|
||||
func (h *helper) line(timeout time.Duration) (string, error) {
|
||||
type res struct {
|
||||
s string
|
||||
err error
|
||||
}
|
||||
ch := make(chan res, 1)
|
||||
go func() {
|
||||
s, err := h.out.ReadString('\n')
|
||||
ch <- res{strings.TrimSpace(s), err}
|
||||
}()
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.s, r.err
|
||||
case <-time.After(timeout):
|
||||
return "", fmt.Errorf("no output within %v", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
// finish closes the helper's stdin, which ends it, and returns what it printed.
|
||||
func (h *helper) finish(timeout time.Duration) (string, error) {
|
||||
h.stdin.Close()
|
||||
s, err := h.line(timeout)
|
||||
if err != nil {
|
||||
// A helper stuck in the mount would keep Wait from returning.
|
||||
h.cmd.Process.Kill()
|
||||
}
|
||||
h.cmd.Wait()
|
||||
return s, err
|
||||
}
|
||||
|
||||
// TestHelperProcess is the helper process, not a test.
|
||||
func TestHelperProcess(t *testing.T) {
|
||||
mode := os.Getenv("FUSE_HANDOVER_HELPER")
|
||||
if mode == "" {
|
||||
t.Skip("helper process")
|
||||
}
|
||||
args := strings.Split(os.Getenv("FUSE_HANDOVER_ARGS"), "\n")
|
||||
stdinClosed := make(chan struct{})
|
||||
go func() {
|
||||
io.Copy(io.Discard, os.Stdin)
|
||||
close(stdinClosed)
|
||||
}()
|
||||
switch mode {
|
||||
case "trylocks": // args: flock file, posix file
|
||||
fmt.Println(tryLocks(args[0], args[1]))
|
||||
case "holdposix", "setlkw": // args: file
|
||||
f, err := os.OpenFile(args[0], os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
fmt.Println("error open:", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
cmd := syscall.F_SETLK
|
||||
if mode == "setlkw" {
|
||||
cmd = syscall.F_SETLKW
|
||||
}
|
||||
lk := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: 0, Start: 0, Len: 0}
|
||||
if err := syscall.FcntlFlock(f.Fd(), cmd, &lk); err != nil {
|
||||
fmt.Println("error lock:", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
fmt.Println("locked")
|
||||
<-stdinClosed
|
||||
case "cwd": // runs in a directory inside the mount
|
||||
want, _ := os.Getwd()
|
||||
var loops, errs int
|
||||
first := ""
|
||||
note := func(format string, a ...any) {
|
||||
errs++
|
||||
if first == "" {
|
||||
first = fmt.Sprintf(format, a...)
|
||||
}
|
||||
}
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-stdinClosed:
|
||||
break loop
|
||||
default:
|
||||
}
|
||||
loops++
|
||||
if wd, err := os.Getwd(); err != nil || wd != want {
|
||||
note("getwd %q %v", wd, err)
|
||||
}
|
||||
if _, err := os.Stat("."); err != nil {
|
||||
note("stat .: %v", err)
|
||||
}
|
||||
payload := []byte(fmt.Sprintf("loop %d", loops))
|
||||
if err := os.WriteFile("rel.txt", payload, 0o644); err != nil {
|
||||
note("write: %v", err)
|
||||
} else if got, err := os.ReadFile("rel.txt"); err != nil || !bytes.Equal(got, payload) {
|
||||
note("read back %q %v", got, err)
|
||||
}
|
||||
if _, err := os.ReadDir("."); err != nil {
|
||||
note("readdir: %v", err)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
fmt.Printf("errors=%d loops=%d first=%s\n", errs, loops, first)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func errName(err error) string {
|
||||
switch err {
|
||||
case nil:
|
||||
return "ok"
|
||||
case syscall.EAGAIN:
|
||||
return "EAGAIN"
|
||||
case syscall.EACCES:
|
||||
return "EACCES"
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func tryLocks(flockFile, posixFile string) string {
|
||||
f1, err := os.OpenFile(flockFile, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return "error open flock file: " + err.Error()
|
||||
}
|
||||
defer f1.Close()
|
||||
f2, err := os.OpenFile(posixFile, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return "error open posix file: " + err.Error()
|
||||
}
|
||||
defer f2.Close()
|
||||
fl := syscall.Flock(int(f1.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
lk := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: 0, Start: 0, Len: 0}
|
||||
px := syscall.FcntlFlock(f2.Fd(), syscall.F_SETLK, &lk)
|
||||
return fmt.Sprintf("flock=%s posix=%s", errName(fl), errName(px))
|
||||
}
|
||||
|
||||
// workloads is everything the scenario keeps running through the handovers.
|
||||
type workloads struct {
|
||||
t *testing.T
|
||||
mnt string
|
||||
|
||||
stop chan struct{}
|
||||
wg sync.WaitGroup
|
||||
fails failures
|
||||
|
||||
appended atomic.Int64
|
||||
appendGap atomic.Int64 // longest time between two appends, ns
|
||||
readerBytes atomic.Int64
|
||||
readerPass atomic.Int64
|
||||
walkPasses atomic.Int64
|
||||
unlinkedOps atomic.Int64
|
||||
probeMax atomic.Int64 // longest stat of the mount, ns
|
||||
|
||||
lockFlock, lockPosix *os.File
|
||||
cwd *helper
|
||||
mm []byte
|
||||
listing *os.File
|
||||
listingNames []string
|
||||
created *os.File
|
||||
renamed *os.File
|
||||
renamedName string
|
||||
unlinkedPath string
|
||||
unlinked *os.File
|
||||
flockPath, posixPath string
|
||||
}
|
||||
|
||||
func (w *workloads) p(parts ...string) string {
|
||||
return filepath.Join(append([]string{w.mnt}, parts...)...)
|
||||
}
|
||||
|
||||
func (w *workloads) setup() {
|
||||
t := w.t
|
||||
require.NoError(t, os.MkdirAll(w.p("cwd"), 0o755))
|
||||
require.NoError(t, os.MkdirAll(w.p("locks"), 0o755))
|
||||
|
||||
// The streaming reader's file, and the mmap file, written and dropped from
|
||||
// the page cache so that the reads after the handover reach the mount.
|
||||
writeBlocks := func(path string, seed, blocks int) {
|
||||
f, err := os.Create(path)
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < blocks; i++ {
|
||||
_, err := f.Write(blockData(seed, i))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NoError(t, f.Sync())
|
||||
require.NoError(t, unix.Fadvise(int(f.Fd()), 0, 0, unix.FADV_DONTNEED))
|
||||
require.NoError(t, f.Close())
|
||||
}
|
||||
writeBlocks(w.p("big.bin"), 1, bigBlocks)
|
||||
writeBlocks(w.p("mm.bin"), 2, mmapBlocks)
|
||||
|
||||
for d := 0; d < treeDirs; d++ {
|
||||
dir := w.p("tree", fmt.Sprintf("d%02d", d))
|
||||
require.NoError(t, os.MkdirAll(dir, 0o755))
|
||||
for i := 0; i < treeFiles; i++ {
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, fmt.Sprintf("f%03d", i)), []byte("x"), 0o644))
|
||||
}
|
||||
}
|
||||
require.NoError(t, os.MkdirAll(w.p("listing"), 0o755))
|
||||
for i := 0; i < listFiles; i++ {
|
||||
name := fmt.Sprintf("an-entry-with-a-rather-long-name-%04d", i)
|
||||
w.listingNames = append(w.listingNames, name)
|
||||
require.NoError(t, os.WriteFile(w.p("listing", name), nil, 0o644))
|
||||
}
|
||||
w.flockPath, w.posixPath = w.p("locks", "flock.f"), w.p("locks", "posix.f")
|
||||
require.NoError(t, os.WriteFile(w.flockPath, []byte("f"), 0o644))
|
||||
require.NoError(t, os.WriteFile(w.posixPath, []byte("p"), 0o644))
|
||||
}
|
||||
|
||||
func (w *workloads) start() {
|
||||
t := w.t
|
||||
|
||||
// A held flock and a held POSIX lock. The test process owns them; another
|
||||
// process is told it cannot have them.
|
||||
var err error
|
||||
w.lockFlock, err = os.OpenFile(w.flockPath, os.O_RDWR, 0)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.lockFlock.Close() })
|
||||
require.NoError(t, syscall.Flock(int(w.lockFlock.Fd()), syscall.LOCK_EX))
|
||||
w.lockPosix, err = os.OpenFile(w.posixPath, os.O_RDWR, 0)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.lockPosix.Close() })
|
||||
lk := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: 0, Start: 0, Len: 0}
|
||||
require.NoError(t, syscall.FcntlFlock(w.lockPosix.Fd(), syscall.F_SETLK, &lk))
|
||||
w.requireLocksHeld("before the first handover")
|
||||
|
||||
// A process whose working directory is inside the mount.
|
||||
w.cwd = startHelper(t, w.p("cwd"), "cwd")
|
||||
|
||||
// An mmap that is read only after the handover.
|
||||
mf, err := os.Open(w.p("mm.bin"))
|
||||
require.NoError(t, err)
|
||||
w.mm, err = syscall.Mmap(int(mf.Fd()), 0, mmapBlocks*blockSize, syscall.PROT_READ, syscall.MAP_SHARED)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { syscall.Munmap(w.mm); mf.Close() })
|
||||
|
||||
// A directory listing in progress.
|
||||
w.listing, err = os.Open(w.p("listing"))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.listing.Close() })
|
||||
first, err := w.listing.Readdirnames(100)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, first, 100)
|
||||
w.listingNames = nil // what was read so far is kept in the slice below
|
||||
w.listingNames = append(w.listingNames, first...)
|
||||
|
||||
// A file created and written, not yet closed.
|
||||
w.created, err = os.Create(w.p("created-open.txt"))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.created.Close() })
|
||||
_, err = w.created.WriteString("part1-")
|
||||
require.NoError(t, err)
|
||||
|
||||
// A file renamed while open, and written on.
|
||||
w.renamedName = w.p("rename-a.txt")
|
||||
w.renamed, err = os.Create(w.renamedName)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.renamed.Close() })
|
||||
_, err = w.renamed.WriteString("one-")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Rename(w.renamedName, w.p("rename-b.txt")))
|
||||
w.renamedName = w.p("rename-b.txt")
|
||||
|
||||
// An unlinked temp file, written and read back.
|
||||
w.unlinkedPath = w.p("unlinked.tmp")
|
||||
w.unlinked, err = os.OpenFile(w.unlinkedPath, os.O_RDWR|os.O_CREATE, 0o644)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { w.unlinked.Close() })
|
||||
require.NoError(t, os.Remove(w.unlinkedPath))
|
||||
|
||||
w.goRun(w.appender)
|
||||
w.goRun(w.streamReader)
|
||||
w.goRun(w.unlinkedWriter)
|
||||
w.goRun(w.walker)
|
||||
w.goRun(w.prober)
|
||||
}
|
||||
|
||||
func (w *workloads) goRun(f func()) {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
f()
|
||||
}()
|
||||
}
|
||||
|
||||
func (w *workloads) stopped() bool {
|
||||
select {
|
||||
case <-w.stop:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (w *workloads) appender() {
|
||||
f, err := os.OpenFile(w.p("append.log"), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
w.fails.addf("appender: open: %v", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
last := time.Now()
|
||||
for i := 0; !w.stopped(); i++ {
|
||||
if _, err := f.Write([]byte(fmt.Sprintf("%08d\n", i))); err != nil {
|
||||
w.fails.addf("appender: write %d: %v", i, err)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if gap := int64(now.Sub(last)); gap > w.appendGap.Load() {
|
||||
w.appendGap.Store(gap)
|
||||
}
|
||||
last = now
|
||||
w.appended.Add(1)
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *workloads) streamReader() {
|
||||
f, err := os.Open(w.p("big.bin"))
|
||||
if err != nil {
|
||||
w.fails.addf("reader: open: %v", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
buf := make([]byte, blockSize)
|
||||
for !w.stopped() {
|
||||
i := 0
|
||||
for ; i < bigBlocks && !w.stopped(); i++ {
|
||||
if _, err := io.ReadFull(f, buf); err != nil {
|
||||
w.fails.addf("reader: block %d: %v", i, err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(buf, blockData(1, i)) {
|
||||
w.fails.addf("reader: block %d has the wrong content", i)
|
||||
return
|
||||
}
|
||||
w.readerBytes.Add(blockSize)
|
||||
time.Sleep(15 * time.Millisecond)
|
||||
}
|
||||
if i < bigBlocks {
|
||||
// Stopped in the middle: not a pass.
|
||||
break
|
||||
}
|
||||
w.readerPass.Add(1)
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
w.fails.addf("reader: seek: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func unlinkedBlock(i int) []byte {
|
||||
b := make([]byte, 4096)
|
||||
for j := range b {
|
||||
b[j] = byte(i*7 + j)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func (w *workloads) unlinkedWriter() {
|
||||
for i := 0; !w.stopped(); i++ {
|
||||
if _, err := w.unlinked.WriteAt(unlinkedBlock(i), int64(i)*4096); err != nil {
|
||||
w.fails.addf("unlinked: write %d: %v", i, err)
|
||||
return
|
||||
}
|
||||
j := i / 2
|
||||
got := make([]byte, 4096)
|
||||
if _, err := w.unlinked.ReadAt(got, int64(j)*4096); err != nil || !bytes.Equal(got, unlinkedBlock(j)) {
|
||||
w.fails.addf("unlinked: read back %d: %v", j, err)
|
||||
return
|
||||
}
|
||||
w.unlinkedOps.Add(1)
|
||||
time.Sleep(8 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *workloads) walker() {
|
||||
for !w.stopped() {
|
||||
files := 0
|
||||
err := filepath.WalkDir(w.p("tree"), func(path string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !d.IsDir() {
|
||||
files++
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
w.fails.addf("walker: %v", err)
|
||||
return
|
||||
}
|
||||
if files != treeDirs*treeFiles {
|
||||
w.fails.addf("walker: %d files, want %d", files, treeDirs*treeFiles)
|
||||
return
|
||||
}
|
||||
w.walkPasses.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// prober measures what an application sees of the pause: the longest stat.
|
||||
func (w *workloads) prober() {
|
||||
for !w.stopped() {
|
||||
t0 := time.Now()
|
||||
if _, err := os.Stat(w.mnt); err != nil {
|
||||
w.fails.addf("prober: %v", err)
|
||||
return
|
||||
}
|
||||
if d := int64(time.Since(t0)); d > w.probeMax.Load() {
|
||||
w.probeMax.Store(d)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *workloads) requireLocksHeld(when string) {
|
||||
h := startHelper(w.t, w.mnt, "trylocks", w.flockPath, w.posixPath)
|
||||
got, err := h.line(20 * time.Second)
|
||||
require.NoError(w.t, err)
|
||||
require.Equal(w.t, "flock=EAGAIN posix=EAGAIN", strings.Replace(got, "posix=EACCES", "posix=EAGAIN", 1), "locks %s", when)
|
||||
}
|
||||
|
||||
// afterHandover checks what is checked after each handover, with everything
|
||||
// still running.
|
||||
func (w *workloads) afterHandover(n int) {
|
||||
t := w.t
|
||||
w.requireLocksHeld(fmt.Sprintf("after handover %d", n))
|
||||
switch n {
|
||||
case 1:
|
||||
// Pages never touched before: they come from the new process.
|
||||
for i := 0; i < mmapBlocks; i++ {
|
||||
require.True(t, bytes.Equal(w.mm[i*blockSize:(i+1)*blockSize], blockData(2, i)), "mmap block %d after the handover", i)
|
||||
}
|
||||
// Write on to the open, renamed file, then rename it again.
|
||||
_, err := w.renamed.WriteString("two-")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Rename(w.renamedName, w.p("rename-c.txt")))
|
||||
w.renamedName = w.p("rename-c.txt")
|
||||
case 2:
|
||||
_, err := w.renamed.WriteString("three")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
// The mount is the same one and answers.
|
||||
require.NoError(t, os.WriteFile(w.p(fmt.Sprintf("after-%d.txt", n)), []byte("after"), 0o644))
|
||||
}
|
||||
|
||||
// finish stops the workloads and checks what each of them saw.
|
||||
func (w *workloads) finish() {
|
||||
t := w.t
|
||||
close(w.stop)
|
||||
w.wg.Wait()
|
||||
w.fails.require(t)
|
||||
require.Greater(t, w.appended.Load(), int64(100), "the appender ran")
|
||||
require.GreaterOrEqual(t, w.readerPass.Load(), int64(1), "the reader read the file through at least once")
|
||||
require.GreaterOrEqual(t, w.walkPasses.Load(), int64(3), "the walker finished some passes")
|
||||
require.Greater(t, w.unlinkedOps.Load(), int64(50))
|
||||
|
||||
// The appended file is complete and in order.
|
||||
data, err := os.ReadFile(w.p("append.log"))
|
||||
require.NoError(t, err)
|
||||
lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
|
||||
require.Len(t, lines, int(w.appended.Load()), "appended lines")
|
||||
for i, l := range lines {
|
||||
if l != fmt.Sprintf("%08d", i) {
|
||||
require.Failf(t, "append.log", "line %d is %q", i, l)
|
||||
}
|
||||
}
|
||||
|
||||
// The unlinked file holds everything written to it.
|
||||
n := int(w.unlinkedOps.Load())
|
||||
for i := 0; i < n; i++ {
|
||||
got := make([]byte, 4096)
|
||||
_, err := w.unlinked.ReadAt(got, int64(i)*4096)
|
||||
require.NoError(t, err)
|
||||
require.True(t, bytes.Equal(got, unlinkedBlock(i)), "unlinked block %d", i)
|
||||
}
|
||||
require.NoError(t, w.unlinked.Close())
|
||||
|
||||
// The listing in progress continues with no entry skipped or repeated.
|
||||
rest, err := w.listing.Readdirnames(-1)
|
||||
require.NoError(t, err)
|
||||
seen := append(append([]string(nil), w.listingNames...), rest...)
|
||||
sort.Strings(seen)
|
||||
want := make([]string, listFiles)
|
||||
for i := range want {
|
||||
want[i] = fmt.Sprintf("an-entry-with-a-rather-long-name-%04d", i)
|
||||
}
|
||||
require.Equal(t, want, seen, "directory listing across the handovers")
|
||||
w.listing.Close()
|
||||
|
||||
// A file created before and closed after.
|
||||
_, err = w.created.WriteString("part2")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, w.created.Close())
|
||||
got, err := os.ReadFile(w.p("created-open.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "part1-part2", string(got))
|
||||
|
||||
// The renamed open file.
|
||||
require.NoError(t, w.renamed.Close())
|
||||
got, err = os.ReadFile(w.p("rename-c.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "one-two-three", string(got))
|
||||
for _, old := range []string{"rename-a.txt", "rename-b.txt"} {
|
||||
_, err := os.Stat(w.p(old))
|
||||
require.True(t, os.IsNotExist(err), "%s still exists: %v", old, err)
|
||||
}
|
||||
|
||||
// The working directory inside the mount.
|
||||
out, err := w.cwd.finish(20 * time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, strings.HasPrefix(out, "errors=0 "), "cwd process: %s", out)
|
||||
|
||||
// The locks are still held, and released when their owner lets go.
|
||||
w.requireLocksHeld("at the end")
|
||||
require.NoError(t, syscall.Flock(int(w.lockFlock.Fd()), syscall.LOCK_UN))
|
||||
lk := syscall.Flock_t{Type: syscall.F_UNLCK, Whence: 0, Start: 0, Len: 0}
|
||||
require.NoError(t, syscall.FcntlFlock(w.lockPosix.Fd(), syscall.F_SETLK, &lk))
|
||||
h := startHelper(t, w.mnt, "trylocks", w.flockPath, w.posixPath)
|
||||
res, err := h.line(20 * time.Second)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "flock=ok posix=ok", res, "locks after the owner released them")
|
||||
w.lockFlock.Close()
|
||||
w.lockPosix.Close()
|
||||
}
|
||||
@@ -143,7 +143,7 @@ func init() {
|
||||
mountOptions.debug = cmdMount.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
|
||||
mountOptions.debugPort = cmdMount.Flag.Int("debug.port", 6061, "http port for debugging")
|
||||
mountOptions.debugFuse = cmdMount.Flag.Bool("debug.fuse", false, "log raw FUSE protocol requests and responses")
|
||||
mountOptions.localSocket = cmdMount.Flag.String("localSocket", "", "default to /tmp/seaweedfs-mount-<mount_dir_hash>.sock")
|
||||
mountOptions.localSocket = cmdMount.Flag.String("localSocket", "", "default to /tmp/seaweedfs-mount-<mount_dir_hash>.sock. On Linux the mount also listens next to it, on <localSocket without .sock>.handover.sock, so that a new weed mount on the same directory takes the live mount over instead of replacing it")
|
||||
mountOptions.disableXAttr = cmdMount.Flag.Bool("disableXAttr", false, "disable xattr")
|
||||
mountOptions.windowsUid = cmdMount.Flag.Int("windows.uid", 0, "windows only: uid recorded on entries this mount creates, which other clients read")
|
||||
mountOptions.windowsGid = cmdMount.Flag.Int("windows.gid", 0, "windows only: gid recorded on entries this mount creates, which other clients read")
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"path"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -189,6 +190,60 @@ func mountFilerTokenSource(option *MountOptions) security.FilerTokenSource {
|
||||
return security.FilerTokenFile(util.ResolvePath(*option.filerTokenFile))
|
||||
}
|
||||
|
||||
// hasExtraMountOption reports whether the -o options name the mount option.
|
||||
func hasExtraMountOption(option *MountOptions, name string) bool {
|
||||
for _, opt := range option.extraOptions {
|
||||
for _, token := range strings.Split(opt, ",") {
|
||||
if strings.TrimSpace(token) == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// mountFlagOptions are the generic mount options, by the flag of the kernel's
|
||||
// mount each one sets or clears. relatime is left out: the kernel uses it
|
||||
// unless noatime or strictatime is set, so the option changes nothing.
|
||||
var mountFlagOptions = map[string]struct {
|
||||
flag string
|
||||
set bool
|
||||
}{
|
||||
"ro": {"ro", true}, "rw": {"ro", false},
|
||||
"nosuid": {"nosuid", true}, "suid": {"nosuid", false},
|
||||
"nodev": {"nodev", true}, "dev": {"nodev", false},
|
||||
"noexec": {"noexec", true}, "exec": {"noexec", false},
|
||||
"sync": {"sync", true}, "async": {"sync", false},
|
||||
"dirsync": {"dirsync", true},
|
||||
"noatime": {"noatime", true}, "atime": {"noatime", false},
|
||||
"nodiratime": {"nodiratime", true}, "diratime": {"nodiratime", false},
|
||||
"strictatime": {"strictatime", true}, "nostrictatime": {"strictatime", false},
|
||||
"lazytime": {"lazytime", true}, "nolazytime": {"lazytime", false},
|
||||
"nosymfollow": {"nosymfollow", true}, "symfollow": {"nosymfollow", false},
|
||||
}
|
||||
|
||||
// kernelMountFlags returns the generic flags, sorted, that the kernel's mount
|
||||
// gets from the options go-fuse mounts with. fusermount3 and go-fuse's direct
|
||||
// mount both start from nosuid and nodev and apply the options in order, so a
|
||||
// later option wins: -readOnly adds "ro" before the -o options, and with
|
||||
// -o rw the mount is read-write.
|
||||
func kernelMountFlags(options []string) []string {
|
||||
set := map[string]bool{"nosuid": true, "nodev": true}
|
||||
for _, option := range options {
|
||||
if o, ok := mountFlagOptions[option]; ok {
|
||||
set[o.flag] = o.set
|
||||
}
|
||||
}
|
||||
flags := make([]string, 0, len(set))
|
||||
for flag, on := range set {
|
||||
if on {
|
||||
flags = append(flags, flag)
|
||||
}
|
||||
}
|
||||
sort.Strings(flags)
|
||||
return flags
|
||||
}
|
||||
|
||||
// checkFilerTokenFile refuses options a filer token cannot serve. A filer
|
||||
// refuses MountRegister, MountList and distributed locks to a scoped token,
|
||||
// so peer chunk sharing and -dlm would fail at run time instead of at start.
|
||||
@@ -224,6 +279,8 @@ type fileSystemParams struct {
|
||||
cacheDirForRead string
|
||||
cacheDirForWrite string
|
||||
cacheMinFree *util.MinFreeSpace // the parsed -cacheMinFreeSpace
|
||||
takeover bool // taking a live mount over: cache directories of its own
|
||||
kernelMountFlags []string // the generic flags of the kernel's mount (kernelMountFlags)
|
||||
|
||||
// eagerFilerCreate persists a created file's entry at create time rather
|
||||
// than at flush. A platform sets it when it cannot run the flush before
|
||||
@@ -258,6 +315,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
|
||||
CacheDirForRead: p.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheMinFreeSpace: p.cacheMinFree,
|
||||
Takeover: p.takeover,
|
||||
CacheDirForWrite: p.cacheDirForWrite,
|
||||
WriteBufferSizeMB: *option.writeBufferSizeMB,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
@@ -276,6 +334,9 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
|
||||
UidGidMapper: p.uidGidMapper,
|
||||
IncludeSystemEntries: *option.includeSystemEntries,
|
||||
DefaultPermissions: *option.defaultPermissions,
|
||||
KernelMountFlags: p.kernelMountFlags,
|
||||
KernelAllowOther: *option.allowOthers || hasExtraMountOption(option, "allow_other"),
|
||||
KernelDefaultPermissions: *option.defaultPermissions || hasExtraMountOption(option, "default_permissions"),
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
|
||||
@@ -3,3 +3,8 @@ package command
|
||||
func checkMountPointAvailable(dir string, skipAutofs bool) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// liveMount is only asked where a mount can be taken over, on Linux.
|
||||
func liveMount(dir string, skipAutofs bool) bool {
|
||||
return false
|
||||
}
|
||||
@@ -3,3 +3,8 @@ package command
|
||||
func checkMountPointAvailable(dir string, skipAutofs bool) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// liveMount is only asked where a mount can be taken over, on Linux.
|
||||
func liveMount(dir string, skipAutofs bool) bool {
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//go:build linux || darwin || freebsd
|
||||
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount"
|
||||
)
|
||||
|
||||
// handoverSocketPath is where a mount listens for a successor: next to its
|
||||
// local gRPC socket, /tmp/seaweedfs-mount-<hash>.handover.sock by default. A
|
||||
// deployment that keeps the local socket where the next mount process can
|
||||
// reach it gets the same for this one.
|
||||
func handoverSocketPath(localSocket string) string {
|
||||
return strings.TrimSuffix(localSocket, ".sock") + ".handover.sock"
|
||||
}
|
||||
|
||||
// handoverSupported tells whether this mount can be handed over, or take a
|
||||
// mount over: on Linux, and neither with -peer.enable, whose listen port has a
|
||||
// single owner, nor with -filer.tokenFile, as read tokens and chunk proofs do
|
||||
// not cross. Such a mount does not listen, so a new mount on its directory
|
||||
// replaces it as before.
|
||||
func handoverSupported(option *MountOptions) bool {
|
||||
if runtime.GOOS != "linux" {
|
||||
return false
|
||||
}
|
||||
if option.peerEnabled != nil && *option.peerEnabled {
|
||||
return false
|
||||
}
|
||||
return option.filerTokenFile == nil || *option.filerTokenFile == ""
|
||||
}
|
||||
|
||||
// handoverGoTimeout is how long a taking-over process waits for go after it
|
||||
// said ready; the running mount answers at once.
|
||||
const handoverGoTimeout = 60 * time.Second
|
||||
|
||||
// listenMountSocket binds the local gRPC socket. With handover enabled the
|
||||
// listener does not unlink the socket file when it is closed: after a handover
|
||||
// the successor binds the same path, and only the cleanup func, which the
|
||||
// caller skips once it handed over, removes it.
|
||||
func listenMountSocket(path string, handover bool) (net.Listener, func(), error) {
|
||||
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||
return nil, nil, fmt.Errorf("remove %s: %w", path, err)
|
||||
}
|
||||
listener, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("listen on %s: %w", path, err)
|
||||
}
|
||||
if handover {
|
||||
listener.(*net.UnixListener).SetUnlinkOnClose(false)
|
||||
}
|
||||
return listener, mountSocketCleanup(path), nil
|
||||
}
|
||||
|
||||
// takeOverMount takes the mount over from the running process: it receives
|
||||
// the FUSE connection and the state, builds the server, answers ready and
|
||||
// waits for go. Until go any failure ends the process and leaves the running
|
||||
// mount as it was; the caller binds its sockets after this returns. The
|
||||
// returned server already reads requests.
|
||||
func takeOverMount(wfs *mount.WFS, dir, handoverDir, socket string, opts *fuse.MountOptions) *fuse.Server {
|
||||
fail := func(format string, args ...any) {
|
||||
wfs.ClearCacheDir()
|
||||
reason := fmt.Sprintf(format, args...)
|
||||
if !mount.HandoverAnswers(socket) {
|
||||
// It answered the probe a moment ago: it has gone since.
|
||||
glog.Exitf("take over %s failed: %s. The weed mount that served it no longer answers; start this mount again to mount it anew", dir, reason)
|
||||
}
|
||||
glog.Exitf("take over %s failed, the running weed mount keeps serving it: %s. To mount it anew instead, stop that weed mount or unmount %s first", dir, reason, dir)
|
||||
}
|
||||
// What can fail in starting the background tasks is done before the
|
||||
// running mount pauses: after go there is no mount to give back.
|
||||
if err := wfs.PrepareBackgroundTasks(); err != nil {
|
||||
fail("prepare the background tasks: %v", err)
|
||||
}
|
||||
tk, err := wfs.BeginTakeover(mount.TakeoverOptions{SocketPath: socket, MountDir: handoverDir})
|
||||
if err != nil {
|
||||
fail("%v", err)
|
||||
}
|
||||
server, err := fuse.NewServerFromDev(wfs, tk.Dev(), dir, opts)
|
||||
if err != nil {
|
||||
tk.Abort("build the FUSE server: " + err.Error())
|
||||
fail("build the FUSE server: %v", err)
|
||||
}
|
||||
if err := tk.Ready(); err != nil {
|
||||
tk.Close()
|
||||
fail("answer ready: %v", err)
|
||||
}
|
||||
if err := tk.WaitGo(handoverGoTimeout); err != nil {
|
||||
tk.Close()
|
||||
fail("%v", err)
|
||||
}
|
||||
// From here the mount is this process's.
|
||||
if err := server.Start(); err != nil {
|
||||
glog.Exitf("take over %s: the running mount is gone and the FUSE server cannot start: %v", dir, err)
|
||||
}
|
||||
glog.V(0).Infof("handover: serving unix_ns=%d state_bytes=%d", time.Now().UnixNano(), tk.StateBytes)
|
||||
tk.Close()
|
||||
return server
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build linux
|
||||
|
||||
package command
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The kernel escapes some characters of the paths in /proc/self/mountinfo; a
|
||||
// mount directory with a space must still be found there.
|
||||
func TestUnescapeMountInfoPath(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
`/srv/team\040share`: "/srv/team share",
|
||||
`/a\011b\012c\134d`: "/a\tb\nc\\d",
|
||||
"/plain": "/plain",
|
||||
`/short\04`: `/short\04`,
|
||||
`/not\09octal`: `/not\09octal`,
|
||||
} {
|
||||
if got := unescapeMountInfoPath(in); got != want {
|
||||
t.Errorf("unescapeMountInfoPath(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A kernel mount option counts whether it comes from its flag or from -o.
|
||||
func TestHasExtraMountOption(t *testing.T) {
|
||||
option := &MountOptions{extraOptions: []string{"noatime,allow_other", " ro "}}
|
||||
for name, want := range map[string]bool{"allow_other": true, "ro": true, "default_permissions": false, "noatime": true} {
|
||||
if got := hasExtraMountOption(option, name); got != want {
|
||||
t.Errorf("hasExtraMountOption(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mount flags are those fusermount3 and go-fuse's direct mount give the
|
||||
// kernel: from nosuid and nodev, the options in order. -readOnly puts "ro"
|
||||
// before the -o options, so -readOnly with -o rw mounts read-write.
|
||||
func TestKernelMountFlags(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
options []string
|
||||
want string
|
||||
}{
|
||||
{nil, "nodev,nosuid"},
|
||||
{[]string{"ro"}, "nodev,nosuid,ro"},
|
||||
{[]string{"ro", "rw"}, "nodev,nosuid"},
|
||||
{[]string{"rw", "ro"}, "nodev,nosuid,ro"},
|
||||
{[]string{"noexec"}, "nodev,noexec,nosuid"},
|
||||
{[]string{"noexec", "exec"}, "nodev,nosuid"},
|
||||
{[]string{"suid", "dev"}, ""},
|
||||
{[]string{"default_permissions", "allow_other", "noatime", "fsname=a:/b"}, "noatime,nodev,nosuid"},
|
||||
{[]string{"relatime"}, "nodev,nosuid"},
|
||||
} {
|
||||
if got := strings.Join(kernelMountFlags(c.options), ","); got != c.want {
|
||||
t.Errorf("kernelMountFlags(%q) = %q, want %q", c.options, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func mounted(mountPoint string, skipAutofs bool) (bool, error) {
|
||||
|
||||
// Search the table for the mountPoint
|
||||
for _, e := range entries {
|
||||
if e.Mountpoint == mountPoint {
|
||||
if unescapeMountInfoPath(e.Mountpoint) == mountPoint {
|
||||
// Check if the mountpoint is autofs
|
||||
if skipAutofs && e.Fstype == "autofs" {
|
||||
continue
|
||||
@@ -156,3 +156,32 @@ func checkMountPointAvailable(dir string, skipAutofs bool) bool {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// unescapeMountInfoPath undoes the octal escapes that the kernel writes into
|
||||
// the paths of /proc/self/mountinfo: \040 for a space, \011, \012 and \134.
|
||||
func unescapeMountInfoPath(s string) string {
|
||||
if !strings.Contains(s, `\`) {
|
||||
return s
|
||||
}
|
||||
isOctal := func(c byte) bool { return '0' <= c && c <= '7' }
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\\' && i+3 < len(s) && isOctal(s[i+1]) && isOctal(s[i+2]) && isOctal(s[i+3]) {
|
||||
b.WriteByte((s[i+1]-'0')<<6 | (s[i+2]-'0')<<3 | (s[i+3] - '0'))
|
||||
i += 3
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// liveMount reports whether something is mounted on dir, by the mount table.
|
||||
func liveMount(dir string, skipAutofs bool) bool {
|
||||
mountPoint := dir
|
||||
if mountPoint != "/" && strings.HasSuffix(mountPoint, "/") {
|
||||
mountPoint = mountPoint[0 : len(mountPoint)-1]
|
||||
}
|
||||
isMounted, err := mounted(mountPoint, skipAutofs)
|
||||
return err == nil && isMounted
|
||||
}
|
||||
+123
-23
@@ -8,9 +8,11 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
||||
@@ -92,11 +94,6 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.V(1).Infof("pre-mount cleanup unmount %s: %v", dir, err)
|
||||
}
|
||||
|
||||
// start on local unix socket
|
||||
if *option.localSocket == "" {
|
||||
mountDirHash := util.HashToInt32([]byte(dir))
|
||||
if mountDirHash < 0 {
|
||||
@@ -104,16 +101,80 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
*option.localSocket = fmt.Sprintf("/tmp/seaweedfs-mount-%d.sock", mountDirHash)
|
||||
}
|
||||
if err := os.Remove(*option.localSocket); err != nil && !os.IsNotExist(err) {
|
||||
glog.Fatalf("Failed to remove %s, error: %s", *option.localSocket, err.Error())
|
||||
|
||||
// A mount on a directory that is mounted already, whose weed mount answers
|
||||
// on the handover socket, takes that mount over instead of replacing it:
|
||||
// open files, locks and working directories inside it carry on. When no
|
||||
// process answers (none, a crashed one, an older weed), the mount proceeds
|
||||
// as it always did.
|
||||
skipAutofs := option.hasAutofs != nil && *option.hasAutofs
|
||||
handoverSocket := ""
|
||||
if handoverSupported(option) {
|
||||
handoverSocket = handoverSocketPath(*option.localSocket)
|
||||
}
|
||||
montSocketListener, err := net.Listen("unix", *option.localSocket)
|
||||
if err != nil {
|
||||
glog.Fatalf("Failed to listen on %s: %v", *option.localSocket, err)
|
||||
// The mount table and the hello name the directory by its absolute path;
|
||||
// the local socket keeps the name it always had.
|
||||
handoverDir := dir
|
||||
if abs, err := filepath.Abs(dir); err == nil {
|
||||
handoverDir = abs
|
||||
}
|
||||
removeMountSocket := mountSocketCleanup(*option.localSocket)
|
||||
takeover := handoverSocket != "" && liveMount(handoverDir, skipAutofs) && mount.HandoverAnswers(handoverSocket)
|
||||
if takeover {
|
||||
glog.V(0).Infof("%s is mounted and its weed mount answers on %s: taking the mount over", dir, handoverSocket)
|
||||
}
|
||||
|
||||
// A takeover works on the live mount: it never unmounts, whatever happens.
|
||||
if !takeover {
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.V(1).Infof("pre-mount cleanup unmount %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Once this process has told its successor to go, what it leaves behind is
|
||||
// the successor's: the sockets it re-binds, and the mount itself.
|
||||
var handoverSvc atomic.Pointer[mount.HandoverService]
|
||||
handedOver := func() bool {
|
||||
svc := handoverSvc.Load()
|
||||
return svc != nil && svc.Committed()
|
||||
}
|
||||
unlessHandedOver := func(f func()) func() {
|
||||
return func() {
|
||||
if !handedOver() {
|
||||
f()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// start on local unix socket. In a takeover the running process still owns
|
||||
// it and the handover socket: they are bound after it said go.
|
||||
var montSocketListener net.Listener
|
||||
var removeLocalSocket func()
|
||||
if !takeover {
|
||||
listener, cleanup, err := listenMountSocket(*option.localSocket, handoverSocket != "")
|
||||
if err != nil {
|
||||
glog.Fatalf("local socket: %v", err)
|
||||
}
|
||||
montSocketListener = listener
|
||||
removeLocalSocket = cleanup
|
||||
}
|
||||
removeMountSocket := unlessHandedOver(func() {
|
||||
if removeLocalSocket != nil {
|
||||
removeLocalSocket()
|
||||
}
|
||||
})
|
||||
defer removeMountSocket()
|
||||
grace.OnInterrupt(removeMountSocket)
|
||||
var handoverListener *net.UnixListener
|
||||
if handoverSocket != "" && !takeover {
|
||||
if listener, err := mount.ListenHandover(handoverSocket, false); err != nil {
|
||||
glog.Warningf("handover socket: %v; a new weed mount on %s will replace this mount instead of taking it over", err, dir)
|
||||
} else {
|
||||
handoverListener = listener
|
||||
removeHandoverSocket := unlessHandedOver(mountSocketCleanup(handoverSocket))
|
||||
defer removeHandoverSocket()
|
||||
grace.OnInterrupt(removeHandoverSocket)
|
||||
}
|
||||
}
|
||||
|
||||
// detect mount folder mode
|
||||
if *option.dirAutoCreate {
|
||||
@@ -157,8 +218,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
|
||||
// Ensure target mount point availability
|
||||
skipAutofs := option.hasAutofs != nil && *option.hasAutofs
|
||||
if isValid := checkMountPointAvailable(dir, skipAutofs); !isValid {
|
||||
if isValid := takeover || checkMountPointAvailable(dir, skipAutofs); !isValid {
|
||||
removeMountSocket()
|
||||
glog.Fatalf("Target mount point is not available: %s, please check!", dir)
|
||||
return true
|
||||
@@ -206,6 +266,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
IDMappedMount: *option.idmap,
|
||||
//SyncRead: false, // set to false to enable the FUSE_CAP_ASYNC_READ capability
|
||||
EnableAcl: true,
|
||||
// A mount that may be handed over reads its device in a way the
|
||||
// server can be stopped in.
|
||||
Stoppable: handoverSocket != "",
|
||||
}
|
||||
if *option.defaultPermissions {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "default_permissions")
|
||||
@@ -274,27 +337,53 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
cacheDirForRead: cacheDirForRead,
|
||||
cacheDirForWrite: cacheDirForWrite,
|
||||
cacheMinFree: cacheMinFree,
|
||||
takeover: takeover,
|
||||
kernelMountFlags: kernelMountFlags(fuseMountOptions.Options),
|
||||
})
|
||||
|
||||
if !createMountRoot(seaweedFileSystem, mountRoot, bucketRootPath, filerAddresses) {
|
||||
// A takeover finds the mount root there: the running mount serves it, and
|
||||
// refuses a successor of another root before anything is created.
|
||||
if !takeover && !createMountRoot(seaweedFileSystem, mountRoot, bucketRootPath, filerAddresses) {
|
||||
return false
|
||||
}
|
||||
|
||||
server, err := fuse.NewServer(seaweedFileSystem, dir, fuseMountOptions)
|
||||
if err != nil {
|
||||
// A failed mount is an environment problem (no /dev/fuse, fusermount not
|
||||
// setuid, stale mount point); the goroutine dump Fatalf adds buries it.
|
||||
removeMountSocket()
|
||||
glog.Exitf("Mount fail: %v", err)
|
||||
var server *fuse.Server
|
||||
if takeover {
|
||||
server = takeOverMount(seaweedFileSystem, dir, handoverDir, handoverSocket, fuseMountOptions)
|
||||
// This process serves the mount now, and the old one is gone. A
|
||||
// socket that cannot be bound costs what is reached through it
|
||||
// (quota updates, the next handover); exiting would cost the mount.
|
||||
if listener, cleanup, err := listenMountSocket(*option.localSocket, true); err != nil {
|
||||
glog.Errorf("take over %s: local socket, mount.configure will not reach this mount: %v", dir, err)
|
||||
} else {
|
||||
montSocketListener = listener
|
||||
removeLocalSocket = cleanup
|
||||
}
|
||||
if ln, err := mount.ListenHandover(handoverSocket, true); err != nil {
|
||||
glog.Errorf("take over %s: handover socket, this mount cannot be handed over again: %v", dir, err)
|
||||
} else {
|
||||
handoverListener = ln
|
||||
removeHandoverSocket := unlessHandedOver(mountSocketCleanup(handoverSocket))
|
||||
defer removeHandoverSocket()
|
||||
grace.OnInterrupt(removeHandoverSocket)
|
||||
}
|
||||
} else {
|
||||
server, err = fuse.NewServer(seaweedFileSystem, dir, fuseMountOptions)
|
||||
if err != nil {
|
||||
// A failed mount is an environment problem (no /dev/fuse, fusermount not
|
||||
// setuid, stale mount point); the goroutine dump Fatalf adds buries it.
|
||||
removeMountSocket()
|
||||
glog.Exitf("Mount fail: %v", err)
|
||||
}
|
||||
}
|
||||
if *option.idmap && server.KernelSettings().Flags64()&fuse.CAP_ALLOW_IDMAP == 0 {
|
||||
glog.Warningf("-idmap: this kernel does not support ID-mapped FUSE mounts (Linux 6.12 or later), so ID-mapped bind mounts of %s will fail", dir)
|
||||
}
|
||||
grace.OnInterrupt(func() {
|
||||
grace.OnInterrupt(unlessHandedOver(func() {
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.Errorf("failed to unmount %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
if mountOptions.fuseCommandPid != 0 {
|
||||
// send a signal to the parent process to notify that the mount is ready
|
||||
@@ -305,7 +394,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
}
|
||||
|
||||
serveMountGrpc(seaweedFileSystem, montSocketListener)
|
||||
if montSocketListener != nil {
|
||||
serveMountGrpc(seaweedFileSystem, montSocketListener)
|
||||
}
|
||||
|
||||
err = seaweedFileSystem.StartBackgroundTasks()
|
||||
if err != nil {
|
||||
@@ -316,6 +407,15 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
glog.V(0).Infof("mounted %s%s to %v", *option.filer, mountRoot, dir)
|
||||
glog.V(0).Infof("This is SeaweedFS version %s %s %s", version.Version(), runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
if handoverListener != nil {
|
||||
service := seaweedFileSystem.NewHandoverService(server, handoverListener, mount.HandoverOptions{
|
||||
MountDir: handoverDir,
|
||||
})
|
||||
handoverSvc.Store(service)
|
||||
go service.Serve()
|
||||
glog.V(0).Infof("handover: listening on %s", handoverSocket)
|
||||
}
|
||||
|
||||
server.Serve()
|
||||
|
||||
// Wait for any pending background flushes (writebackCache async mode)
|
||||
|
||||
+38
-24
@@ -18,7 +18,40 @@ func (wfs *WFS) subscribeFilerConfEvents() (*meta_cache.MetadataFollower, error)
|
||||
confName := filer.FilerConfName
|
||||
confFullName := filepath.Join(filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
|
||||
|
||||
// read current conf
|
||||
if err := wfs.loadFilerConf(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if !isFilerConfUpdateEvent(resp, confDir, confName) {
|
||||
return nil
|
||||
}
|
||||
|
||||
content := resp.EventNotification.NewEntry.Content
|
||||
fc := filer.NewFilerConf()
|
||||
if len(content) > 0 {
|
||||
if err := fc.LoadFromBytes(content); err != nil {
|
||||
return fmt.Errorf("parse %s: %v", confFullName, err)
|
||||
}
|
||||
}
|
||||
|
||||
wfs.FilerConf = fc
|
||||
|
||||
return nil
|
||||
}
|
||||
return &meta_cache.MetadataFollower{
|
||||
PathPrefixToWatch: confFullName,
|
||||
ProcessEventFn: processEventFn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadFilerConf reads the filer configuration as it is now. A filer without
|
||||
// one leaves the mount without one.
|
||||
func (wfs *WFS) loadFilerConf() error {
|
||||
confDir := filer.DirectoryEtcSeaweedFS
|
||||
confName := filer.FilerConfName
|
||||
confFullName := filepath.Join(filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
|
||||
|
||||
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
||||
content, err := filer.ReadInsideFiler(ctx, client, confDir, confName)
|
||||
if err != nil {
|
||||
@@ -39,32 +72,13 @@ func (wfs *WFS) subscribeFilerConfEvents() (*meta_cache.MetadataFollower, error)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
glog.V(0).Infof("fuse filer conf %s not found", confFullName)
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if !isFilerConfUpdateEvent(resp, confDir, confName) {
|
||||
// One read earlier, before a takeover, may have found one.
|
||||
wfs.FilerConf = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
content := resp.EventNotification.NewEntry.Content
|
||||
fc := filer.NewFilerConf()
|
||||
if len(content) > 0 {
|
||||
if err = fc.LoadFromBytes(content); err != nil {
|
||||
return fmt.Errorf("parse %s: %v", confFullName, err)
|
||||
}
|
||||
}
|
||||
|
||||
wfs.FilerConf = fc
|
||||
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
return &meta_cache.MetadataFollower{
|
||||
PathPrefixToWatch: confFullName,
|
||||
ProcessEventFn: processEventFn,
|
||||
}, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func isFilerConfUpdateEvent(resp *filer_pb.SubscribeMetadataResponse, confDir, confName string) bool {
|
||||
|
||||
@@ -0,0 +1,871 @@
|
||||
//go:build !windows
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// The handover protocol: how a new weed mount process on the directory of a
|
||||
// running one takes its live FUSE mount over without unmounting it. The state
|
||||
// it moves is described in handover_state.go; this file is the conversation.
|
||||
//
|
||||
// Transport: a unix stream socket next to the local gRPC socket, mode 0600,
|
||||
// the peer's uid checked with SO_PEERCRED on both ends (ours or root). One
|
||||
// handover at a time. A connection closed before its hello is a probe
|
||||
// (HandoverAnswers), not an error.
|
||||
//
|
||||
// new -> old hello control frame: version, mount dir, filer path and
|
||||
// the options the two mounts must share, so that a
|
||||
// mismatch is refused before anything pauses
|
||||
// old -> new header 16 bytes, written with one sendmsg that carries
|
||||
// the FUSE fd (SCM_RIGHTS) when it is an offer
|
||||
// old -> new payload header.length bytes: the INIT negotiation of
|
||||
// the connection (an offer) or the reason (refused)
|
||||
// old -> new state control frame "state", then the handover state
|
||||
// stream (or, if the export refuses before it wrote
|
||||
// anything, a control frame "abort" with the reason)
|
||||
// new -> old ready control frame, after the state is imported and the
|
||||
// server is built; or "abort" with the reason
|
||||
// old -> new go control frame; from here the new process owns the
|
||||
// mount, the local gRPC socket and the handover
|
||||
// socket, and the old one only exits
|
||||
//
|
||||
// A control frame is a uint32 length (big endian) and a JSON object. The
|
||||
// header is fixed-size and the only message that carries an fd, so that the
|
||||
// receiver can read it with one recvmsg straight from the connection (an fd is
|
||||
// lost through a buffered read); everything after it is read through one
|
||||
// bufio.Reader, which also reads the go frame right behind the state stream.
|
||||
//
|
||||
// Until go is written the old process can roll back and keep serving, and the
|
||||
// new one only has a copy of the fd to close. After go there is no way back.
|
||||
|
||||
const (
|
||||
handoverProtocolVersion = 1
|
||||
|
||||
handoverHeaderMagic = "SWHO"
|
||||
handoverHeaderSize = 16
|
||||
headerOffer = 1
|
||||
headerRefused = 2
|
||||
|
||||
maxControlFrame = 1 << 20
|
||||
|
||||
ctlHello = "hello"
|
||||
ctlState = "state"
|
||||
ctlReady = "ready"
|
||||
ctlGo = "go"
|
||||
ctlAbort = "abort"
|
||||
)
|
||||
|
||||
// controlMsg is a control frame.
|
||||
type controlMsg struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version,omitempty"`
|
||||
MountDir string `json:"mountDir,omitempty"`
|
||||
MountRoot string `json:"mountRoot,omitempty"`
|
||||
Options *handoverMountOptions `json:"options,omitempty"`
|
||||
Pid int `json:"pid,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// handoverMountOptions are the options a successor must share with the mount
|
||||
// it takes over: the exported state only fits a mount that caches, locks and
|
||||
// registers nfs file handles the same way. The hello carries them so that the
|
||||
// running mount refuses a mismatch before it pauses; the import checks the
|
||||
// identity in the state again.
|
||||
type handoverMountOptions struct {
|
||||
Writeback bool `json:"writeback"`
|
||||
RoutedLocks bool `json:"routedLocks"`
|
||||
NfsExport bool `json:"nfsExport"`
|
||||
// The kernel's mount options, from the flags and -o, which a successor
|
||||
// cannot change. Without default_permissions the kernel leaves the
|
||||
// permission checks to the mount, and a successor that counts on the
|
||||
// kernel would make none; a successor started with other mount flags
|
||||
// (ro, noexec, nosuid, ...) or allow_other would run with the old ones
|
||||
// without knowing. MountFlags are sorted.
|
||||
DefaultPermissions bool `json:"defaultPermissions"`
|
||||
AllowOthers bool `json:"allowOthers"`
|
||||
MountFlags []string `json:"mountFlags"`
|
||||
// Filers are the filer addresses as host:port, sorted. A successor must
|
||||
// name one of them: a filer serves one filer store, so a filer in common
|
||||
// means the store that the open files, the inode table's names and the
|
||||
// chunks belong to. The lists may differ otherwise, as filers are added to
|
||||
// the cluster or taken out of it.
|
||||
Filers []string `json:"filers"`
|
||||
}
|
||||
|
||||
func (wfs *WFS) handoverMountOptions() *handoverMountOptions {
|
||||
filers := make([]string, 0, len(wfs.option.FilerAddresses))
|
||||
for _, address := range wfs.option.FilerAddresses {
|
||||
filers = append(filers, address.ToHttpAddress())
|
||||
}
|
||||
sort.Strings(filers)
|
||||
return &handoverMountOptions{
|
||||
Writeback: wfs.option.WritebackCache,
|
||||
RoutedLocks: wfs.crossMountLocks(),
|
||||
NfsExport: wfs.exportedHandles != nil,
|
||||
Filers: filers,
|
||||
|
||||
DefaultPermissions: wfs.option.KernelDefaultPermissions,
|
||||
AllowOthers: wfs.option.KernelAllowOther,
|
||||
MountFlags: wfs.option.KernelMountFlags,
|
||||
}
|
||||
}
|
||||
|
||||
// mismatch describes how the new process's options differ from these, or
|
||||
// returns "" when they match.
|
||||
func (o *handoverMountOptions) mismatch(theirs *handoverMountOptions) string {
|
||||
if theirs == nil {
|
||||
return "the new process sent no mount options"
|
||||
}
|
||||
var diffs []string
|
||||
add := func(name string, here, there bool) {
|
||||
if here != there {
|
||||
diffs = append(diffs, fmt.Sprintf("%s is %v here and %v in the new process", name, here, there))
|
||||
}
|
||||
}
|
||||
add("-writebackCache", o.Writeback, theirs.Writeback)
|
||||
add("routed locking (-dlm)", o.RoutedLocks, theirs.RoutedLocks)
|
||||
add("-nfsExport", o.NfsExport, theirs.NfsExport)
|
||||
add("default_permissions (-defaultPermissions or -o)", o.DefaultPermissions, theirs.DefaultPermissions)
|
||||
add("allow_other (-allowOthers or -o)", o.AllowOthers, theirs.AllowOthers)
|
||||
if !slices.Equal(o.MountFlags, theirs.MountFlags) {
|
||||
diffs = append(diffs, fmt.Sprintf("the mount flags (-readOnly and -o) are %s here and %s in the new process", strings.Join(o.MountFlags, ","), strings.Join(theirs.MountFlags, ",")))
|
||||
}
|
||||
if !slices.ContainsFunc(o.Filers, func(f string) bool { return slices.Contains(theirs.Filers, f) }) {
|
||||
diffs = append(diffs, fmt.Sprintf("the filers are %s here and %s in the new process, none in common", strings.Join(o.Filers, ","), strings.Join(theirs.Filers, ",")))
|
||||
}
|
||||
return strings.Join(diffs, "; ")
|
||||
}
|
||||
|
||||
func writeControl(w io.Writer, m *controlMsg) error {
|
||||
body, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The peer refuses a larger frame.
|
||||
if len(body) > maxControlFrame {
|
||||
return fmt.Errorf("handover: control frame of %d bytes", len(body))
|
||||
}
|
||||
buf := make([]byte, 4, 4+len(body))
|
||||
binary.BigEndian.PutUint32(buf, uint32(len(body)))
|
||||
_, err = w.Write(append(buf, body...))
|
||||
return err
|
||||
}
|
||||
|
||||
func readControl(r io.Reader) (*controlMsg, error) {
|
||||
var prefix [4]byte
|
||||
if _, err := io.ReadFull(r, prefix[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := binary.BigEndian.Uint32(prefix[:])
|
||||
if n == 0 || n > maxControlFrame {
|
||||
return nil, fmt.Errorf("handover: control frame of %d bytes", n)
|
||||
}
|
||||
body := make([]byte, n)
|
||||
if _, err := io.ReadFull(r, body); err != nil {
|
||||
return nil, unexpectedEOF(err)
|
||||
}
|
||||
m := &controlMsg{}
|
||||
if err := json.Unmarshal(body, m); err != nil {
|
||||
return nil, fmt.Errorf("handover: control frame: %w", err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func encodeHeader(kind uint16, length uint32) []byte {
|
||||
h := make([]byte, handoverHeaderSize)
|
||||
copy(h, handoverHeaderMagic)
|
||||
binary.BigEndian.PutUint16(h[4:], handoverProtocolVersion)
|
||||
binary.BigEndian.PutUint16(h[6:], kind)
|
||||
binary.BigEndian.PutUint32(h[8:], length)
|
||||
return h
|
||||
}
|
||||
|
||||
// HandoverRefusedError is the answer of an old process that did not hand over.
|
||||
type HandoverRefusedError struct{ Reason string }
|
||||
|
||||
func (e *HandoverRefusedError) Error() string {
|
||||
return "the running mount refused the handover: " + e.Reason
|
||||
}
|
||||
|
||||
// HandoverServer is what the old side needs of the FUSE server; *fuse.Server
|
||||
// is one.
|
||||
type HandoverServer interface {
|
||||
Stop(ctx context.Context) error
|
||||
Start() error
|
||||
Dev() (*fuse.Dev, error)
|
||||
Shutdown(ctx context.Context) error
|
||||
}
|
||||
|
||||
var _ HandoverServer = (*fuse.Server)(nil)
|
||||
|
||||
// ---------------------------------------------------------------- old side
|
||||
|
||||
// HandoverOptions configures the old side. Zero durations take the defaults.
|
||||
type HandoverOptions struct {
|
||||
// MountDir is the mount directory a new process must name.
|
||||
MountDir string
|
||||
// PreFlushTimeout bounds the flush done while still serving (default 120 s).
|
||||
PreFlushTimeout time.Duration
|
||||
// StopTimeout bounds quiescing the background writers and the drain of
|
||||
// requests in flight, Server.Stop (default 10 s).
|
||||
StopTimeout time.Duration
|
||||
// FlushTimeout bounds the second flush, inside the pause (default 30 s).
|
||||
FlushTimeout time.Duration
|
||||
// ReadyTimeout is how long the new process has to import and answer
|
||||
// ready (default 60 s).
|
||||
ReadyTimeout time.Duration
|
||||
// AllowPeerUID decides on the uid of the peer; the default allows our own
|
||||
// uid and root.
|
||||
AllowPeerUID func(uid uint32) bool
|
||||
}
|
||||
|
||||
func (o *HandoverOptions) withDefaults() {
|
||||
if o.PreFlushTimeout <= 0 {
|
||||
o.PreFlushTimeout = 120 * time.Second
|
||||
}
|
||||
if o.StopTimeout <= 0 {
|
||||
o.StopTimeout = 10 * time.Second
|
||||
}
|
||||
if o.FlushTimeout <= 0 {
|
||||
o.FlushTimeout = 30 * time.Second
|
||||
}
|
||||
if o.ReadyTimeout <= 0 {
|
||||
o.ReadyTimeout = 60 * time.Second
|
||||
}
|
||||
if o.AllowPeerUID == nil {
|
||||
o.AllowPeerUID = func(uid uint32) bool { return uid == uint32(os.Getuid()) || uid == 0 }
|
||||
}
|
||||
}
|
||||
|
||||
// HandoverService is the old side: it answers a new process on the handover
|
||||
// socket.
|
||||
type HandoverService struct {
|
||||
wfs *WFS
|
||||
srv HandoverServer
|
||||
ln net.Listener
|
||||
opts HandoverOptions
|
||||
|
||||
// flush is FlushForHandover; a seam for tests.
|
||||
flush func(ctx context.Context) error
|
||||
// sendGo writes the go frame; a seam for tests.
|
||||
sendGo func(conn net.Conn) error
|
||||
|
||||
busy atomic.Bool
|
||||
committed atomic.Bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewHandoverService serves handovers on ln for the mount served by srv. Call
|
||||
// Serve to start accepting.
|
||||
func (wfs *WFS) NewHandoverService(srv HandoverServer, ln net.Listener, opts HandoverOptions) *HandoverService {
|
||||
opts.withDefaults()
|
||||
return &HandoverService{wfs: wfs, srv: srv, ln: ln, opts: opts, flush: wfs.FlushForHandover, sendGo: func(c net.Conn) error { return writeControl(c, &controlMsg{Type: ctlGo}) }, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Committed reports that this process has told a successor to go. From then
|
||||
// on its exit must leave everything outside the process alone: no unmount, and
|
||||
// the local gRPC socket and the handover socket are the successor's to bind.
|
||||
func (h *HandoverService) Committed() bool { return h.committed.Load() }
|
||||
|
||||
// Done is closed after a handover went through.
|
||||
func (h *HandoverService) Done() <-chan struct{} { return h.done }
|
||||
|
||||
// Close stops accepting.
|
||||
func (h *HandoverService) Close() { h.ln.Close() }
|
||||
|
||||
// Serve accepts connections until the listener is closed.
|
||||
func (h *HandoverService) Serve() {
|
||||
for {
|
||||
conn, err := h.ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uc, ok := conn.(*net.UnixConn)
|
||||
if !ok {
|
||||
conn.Close()
|
||||
continue
|
||||
}
|
||||
go h.handleConn(uc)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HandoverService) handleConn(conn *net.UnixConn) {
|
||||
defer conn.Close()
|
||||
refuse := func(err error) {
|
||||
glog.Errorf("handover refused, this mount keeps serving: %v", err)
|
||||
refuseOffer(conn, err.Error())
|
||||
}
|
||||
uid, err := peerUID(conn)
|
||||
if err != nil {
|
||||
refuse(fmt.Errorf("cannot identify the peer: %w", err))
|
||||
return
|
||||
}
|
||||
if !h.opts.AllowPeerUID(uid) {
|
||||
refuse(fmt.Errorf("peer uid %d is not allowed", uid))
|
||||
return
|
||||
}
|
||||
br := bufio.NewReader(conn)
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
hello, err := readControl(br)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Closed without a word: a new mount probing for this one.
|
||||
glog.V(1).Infof("handover: probed by uid %d", uid)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
refuse(fmt.Errorf("read hello: %w", err))
|
||||
return
|
||||
}
|
||||
if h.committed.Load() {
|
||||
refuseOffer(conn, "this mount was already handed over")
|
||||
return
|
||||
}
|
||||
if !h.busy.CompareAndSwap(false, true) {
|
||||
refuseOffer(conn, "another handover is in progress")
|
||||
return
|
||||
}
|
||||
defer h.busy.Store(false)
|
||||
if err := h.run(conn, br, hello, uid); err != nil {
|
||||
glog.Errorf("handover refused or rolled back, this mount keeps serving: %v", err)
|
||||
return
|
||||
}
|
||||
close(h.done)
|
||||
// The listener is the successor's from here on; do not leave a second
|
||||
// accepting socket behind.
|
||||
h.ln.Close()
|
||||
}
|
||||
|
||||
func refuseOffer(conn net.Conn, reason string) {
|
||||
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(append(encodeHeader(headerRefused, uint32(len(reason))), reason...))
|
||||
}
|
||||
|
||||
// run is one handover, from the hello to the shutdown. It returns an error
|
||||
// only when it rolled back (or never started); the process then serves on.
|
||||
func (h *HandoverService) run(conn *net.UnixConn, br *bufio.Reader, hello *controlMsg, uid uint32) (err error) {
|
||||
var (
|
||||
offered, stateStarted, exported bool
|
||||
quiesced, stopped, paused, gone bool
|
||||
)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
glog.Errorf("panic during handover (go sent: %v): %v\n%s", gone, r, debug.Stack())
|
||||
if gone {
|
||||
// The successor serves; there is nothing to roll back.
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
err = fmt.Errorf("panic during handover: %v", r)
|
||||
}
|
||||
if err == nil || gone {
|
||||
return
|
||||
}
|
||||
// The server first: every request to the mount waits until it
|
||||
// reads again, and a subscription that did not end in time may be
|
||||
// waiting for one of them.
|
||||
if stopped {
|
||||
if serr := h.srv.Start(); serr != nil {
|
||||
glog.Errorf("handover rollback: resume FUSE server: %v", serr)
|
||||
}
|
||||
}
|
||||
if quiesced {
|
||||
h.wfs.ResumeBackground()
|
||||
}
|
||||
if exported {
|
||||
// The export stopped the nfs export writer for its successor.
|
||||
h.wfs.exportedHandles.resume()
|
||||
}
|
||||
if paused {
|
||||
h.wfs.resumeMetadataFollowLater()
|
||||
}
|
||||
// Tell the peer why, where the protocol has room for it.
|
||||
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
switch {
|
||||
case !offered:
|
||||
refuseOffer(conn, err.Error())
|
||||
case !stateStarted:
|
||||
writeControl(conn, &controlMsg{Type: ctlAbort, Reason: err.Error()})
|
||||
}
|
||||
}()
|
||||
|
||||
if hello.Type != ctlHello || hello.Version != handoverProtocolVersion {
|
||||
return fmt.Errorf("unsupported hello (type %q, protocol %d, this mount speaks %d)", hello.Type, hello.Version, handoverProtocolVersion)
|
||||
}
|
||||
if hello.MountDir != h.opts.MountDir {
|
||||
return fmt.Errorf("this process serves %s, not %s", h.opts.MountDir, hello.MountDir)
|
||||
}
|
||||
if hello.MountRoot != h.wfs.option.FilerMountRootPath {
|
||||
return fmt.Errorf("this process serves filer path %s, not %s", h.wfs.option.FilerMountRootPath, hello.MountRoot)
|
||||
}
|
||||
if diff := h.wfs.handoverMountOptions().mismatch(hello.Options); diff != "" {
|
||||
return fmt.Errorf("the new process's options differ: %s", diff)
|
||||
}
|
||||
if h.wfs.option.PeerEnabled {
|
||||
return errors.New("peer chunk sharing is enabled, its listen port has a single owner")
|
||||
}
|
||||
glog.V(0).Infof("handover: peer pid %d uid %d asks for %s", hello.Pid, uid, hello.MountDir)
|
||||
|
||||
// A blocked lock request would hold the drain below until its deadline,
|
||||
// with every other request to the mount waiting meanwhile: refuse now,
|
||||
// before anything pauses. One that blocks after this check is still
|
||||
// caught by the drain and the export.
|
||||
if n := h.wfs.blockedLockRequests(); n > 0 {
|
||||
return fmt.Errorf("%d lock requests are blocked in this mount", n)
|
||||
}
|
||||
if h.wfs.metaFollowResuming.Load() {
|
||||
return errMetadataFollowResuming
|
||||
}
|
||||
|
||||
// 1. Flush while still serving, so the bulk of the uploads is not in the pause.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), h.opts.PreFlushTimeout)
|
||||
ferr := h.flush(ctx)
|
||||
cancel()
|
||||
if ferr != nil {
|
||||
return fmt.Errorf("flush before handover: %w", ferr)
|
||||
}
|
||||
|
||||
// 2. Quiesce the writers that flush on their own. The -dlm keepalive is not one.
|
||||
ctx, cancel = context.WithTimeout(context.Background(), h.opts.StopTimeout)
|
||||
quiesced = true
|
||||
qerr := h.wfs.QuiesceBackground(ctx)
|
||||
cancel()
|
||||
if qerr != nil {
|
||||
return fmt.Errorf("quiesce background writers: %w", qerr)
|
||||
}
|
||||
|
||||
// 3. Stop reading requests and wait for those in flight.
|
||||
stopStart := time.Now()
|
||||
glog.V(0).Infof("handover: stop begin unix_ns=%d", stopStart.UnixNano())
|
||||
ctx, cancel = context.WithTimeout(context.Background(), h.opts.StopTimeout)
|
||||
stopped = true
|
||||
serr := h.srv.Stop(ctx)
|
||||
cancel()
|
||||
if serr != nil {
|
||||
return fmt.Errorf("drain requests in flight within %v: %w", h.opts.StopTimeout, serr)
|
||||
}
|
||||
|
||||
// 4. What became dirty after the first flush.
|
||||
ctx, cancel = context.WithTimeout(context.Background(), h.opts.FlushTimeout)
|
||||
ferr = h.flush(ctx)
|
||||
cancel()
|
||||
if ferr != nil {
|
||||
return fmt.Errorf("final flush: %w", ferr)
|
||||
}
|
||||
|
||||
// 5. The subscription: its position is part of the state.
|
||||
paused = true
|
||||
if perr := h.wfs.PauseMetadataFollow(); perr != nil {
|
||||
return perr
|
||||
}
|
||||
|
||||
// 6. Offer: header with the fd, the negotiation, then the state.
|
||||
dev, derr := h.srv.Dev()
|
||||
if derr != nil {
|
||||
return fmt.Errorf("get the FUSE connection: %w", derr)
|
||||
}
|
||||
defer dev.Close()
|
||||
neg, nerr := dev.MarshalBinary()
|
||||
if nerr != nil {
|
||||
return fmt.Errorf("marshal the FUSE negotiation: %w", nerr)
|
||||
}
|
||||
conn.SetWriteDeadline(time.Now().Add(h.opts.ReadyTimeout))
|
||||
if _, _, werr := conn.WriteMsgUnix(encodeHeader(headerOffer, uint32(len(neg))), syscall.UnixRights(dev.Fd()), nil); werr != nil {
|
||||
return fmt.Errorf("send the offer: %w", werr)
|
||||
}
|
||||
offered = true
|
||||
if _, werr := conn.Write(neg); werr != nil {
|
||||
return fmt.Errorf("send the negotiation: %w", werr)
|
||||
}
|
||||
sw := &stateWriter{conn: conn}
|
||||
eerr := h.wfs.ExportHandoverState(sw)
|
||||
stateStarted = sw.started
|
||||
if eerr != nil {
|
||||
return fmt.Errorf("export state: %w", eerr)
|
||||
}
|
||||
exported = true
|
||||
conn.SetWriteDeadline(time.Time{})
|
||||
glog.V(0).Infof("handover: state sent bytes=%d", sw.n)
|
||||
|
||||
// 7. Ready.
|
||||
conn.SetReadDeadline(time.Now().Add(h.opts.ReadyTimeout))
|
||||
reply, rerr := readControl(br)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
if rerr != nil {
|
||||
return fmt.Errorf("wait for the new process to be ready: %w", rerr)
|
||||
}
|
||||
if reply.Type != ctlReady {
|
||||
return fmt.Errorf("the new process did not become ready: %s %s", reply.Type, reply.Reason)
|
||||
}
|
||||
h.committed.Store(true)
|
||||
|
||||
// 8. Go.
|
||||
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
if werr := h.sendGo(conn); werr != nil {
|
||||
h.committed.Store(false)
|
||||
return fmt.Errorf("send go: %w", werr)
|
||||
}
|
||||
gone = true
|
||||
glog.V(0).Infof("handover: go sent unix_ns=%d pause_so_far_ms=%d", time.Now().UnixNano(), time.Since(stopStart).Milliseconds())
|
||||
|
||||
// 9. Close the server without unmounting; Serve returns and the process
|
||||
// ends. A failure here cannot be rolled back: the successor serves.
|
||||
ctx, cancel = context.WithTimeout(context.Background(), h.opts.StopTimeout)
|
||||
defer cancel()
|
||||
if serr := h.srv.Shutdown(ctx); serr != nil {
|
||||
glog.Errorf("handover: shut the old FUSE server down: %v", serr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// blockedLockRequests counts the SETLKW calls waiting for a lock: in the local
|
||||
// table, or polling the filer for a routed one.
|
||||
func (wfs *WFS) blockedLockRequests() int64 {
|
||||
n := wfs.routedLockWaiters.Load()
|
||||
plt := wfs.posixLocks
|
||||
plt.mu.Lock()
|
||||
defer plt.mu.Unlock()
|
||||
for _, il := range plt.inodes {
|
||||
il.mu.Lock()
|
||||
if !il.dead {
|
||||
n += int64(len(il.waiters) + il.wakeRefs)
|
||||
}
|
||||
il.mu.Unlock()
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// stateWriter writes the "state" frame in front of the first byte of the
|
||||
// state, so that an export that refuses before it wrote anything can still say
|
||||
// so with an "abort" frame.
|
||||
type stateWriter struct {
|
||||
conn net.Conn
|
||||
started bool
|
||||
n int64
|
||||
}
|
||||
|
||||
func (w *stateWriter) Write(p []byte) (int, error) {
|
||||
if !w.started {
|
||||
w.started = true
|
||||
if err := writeControl(w.conn, &controlMsg{Type: ctlState}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
n, err := w.conn.Write(p)
|
||||
w.n += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ListenHandover listens on a unix socket at path, mode 0600. Unless replace
|
||||
// is set it refuses a socket another process still answers on; a successor
|
||||
// that was told to go passes replace, as the old process still has it open.
|
||||
// The socket file is not unlinked when the listener is closed: after a
|
||||
// handover the successor binds the same path.
|
||||
func ListenHandover(path string, replace bool) (*net.UnixListener, error) {
|
||||
if !replace && HandoverAnswers(path) {
|
||||
return nil, fmt.Errorf("handover socket %s is in use by another process", path)
|
||||
}
|
||||
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("remove stale handover socket: %w", err)
|
||||
}
|
||||
ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ln.SetUnlinkOnClose(false)
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
ln.Close()
|
||||
os.Remove(path)
|
||||
return nil, err
|
||||
}
|
||||
return ln, nil
|
||||
}
|
||||
|
||||
// HandoverAnswers reports whether a weed mount listens on the handover socket
|
||||
// at path. It connects and closes at once, which the listener takes for a
|
||||
// probe.
|
||||
func HandoverAnswers(path string) bool {
|
||||
c, err := net.DialTimeout("unix", path, time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
c.Close()
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- new side
|
||||
|
||||
// TakeoverOptions configures the new side.
|
||||
type TakeoverOptions struct {
|
||||
SocketPath string
|
||||
MountDir string
|
||||
// OfferTimeout is how long to wait for the running mount to flush and
|
||||
// offer (default 10 min); StateTimeout bounds the transfer of the state
|
||||
// (default 5 min).
|
||||
OfferTimeout time.Duration
|
||||
StateTimeout time.Duration
|
||||
// AllowPeerUID decides on the uid of the process that answers; the
|
||||
// default allows our own uid and root. Anyone else could have bound the
|
||||
// socket path, and would be handing over a connection of its own.
|
||||
AllowPeerUID func(uid uint32) bool
|
||||
}
|
||||
|
||||
// Takeover is the new side of a handover in progress.
|
||||
type Takeover struct {
|
||||
conn *net.UnixConn
|
||||
br *bufio.Reader
|
||||
dev *fuse.Dev
|
||||
count *countingReader
|
||||
// StateBytes is the size of the state that was imported.
|
||||
StateBytes int64
|
||||
}
|
||||
|
||||
type countingReader struct {
|
||||
r io.Reader
|
||||
n int64
|
||||
}
|
||||
|
||||
func (c *countingReader) Read(p []byte) (int, error) {
|
||||
n, err := c.r.Read(p)
|
||||
c.n += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// BeginTakeover connects to the running mount, receives the FUSE connection
|
||||
// and imports the state into wfs, which must be fresh (see
|
||||
// ImportHandoverState). It changes nothing outside this process. On error the
|
||||
// running mount keeps serving. On success the caller builds the server with
|
||||
// Dev, then calls Ready and WaitGo; Abort ends it before.
|
||||
func (wfs *WFS) BeginTakeover(opts TakeoverOptions) (*Takeover, error) {
|
||||
if opts.OfferTimeout <= 0 {
|
||||
opts.OfferTimeout = 10 * time.Minute
|
||||
}
|
||||
if opts.StateTimeout <= 0 {
|
||||
opts.StateTimeout = 5 * time.Minute
|
||||
}
|
||||
if opts.AllowPeerUID == nil {
|
||||
opts.AllowPeerUID = func(uid uint32) bool { return uid == uint32(os.Getuid()) || uid == 0 }
|
||||
}
|
||||
c, err := net.DialTimeout("unix", opts.SocketPath, 5*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nothing answers on the handover socket %s: %w", opts.SocketPath, err)
|
||||
}
|
||||
conn := c.(*net.UnixConn)
|
||||
t := &Takeover{conn: conn}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
t.Close()
|
||||
}
|
||||
}()
|
||||
uid, err := peerUID(conn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot identify the process on the handover socket: %w", err)
|
||||
}
|
||||
if !opts.AllowPeerUID(uid) {
|
||||
return nil, fmt.Errorf("the process on the handover socket %s runs as uid %d, neither this process's uid nor root", opts.SocketPath, uid)
|
||||
}
|
||||
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
// A running mount that refuses at once (busy, already handed over) may
|
||||
// close before the hello is written: its reason is still to be read.
|
||||
helloErr := writeControl(conn, &controlMsg{Type: ctlHello, Version: handoverProtocolVersion, MountDir: opts.MountDir, MountRoot: wfs.option.FilerMountRootPath, Options: wfs.handoverMountOptions(), Pid: os.Getpid()})
|
||||
conn.SetWriteDeadline(time.Time{})
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(opts.OfferTimeout))
|
||||
kind, length, fd, err := readHeader(conn)
|
||||
if err != nil {
|
||||
if helloErr != nil {
|
||||
return nil, fmt.Errorf("send hello: %w", helloErr)
|
||||
}
|
||||
return nil, fmt.Errorf("read the offer: %w", err)
|
||||
}
|
||||
switch kind {
|
||||
case headerRefused:
|
||||
closeFd(fd)
|
||||
reason, rerr := readPayload(conn, length)
|
||||
if rerr != nil {
|
||||
return nil, &HandoverRefusedError{Reason: "(no reason received)"}
|
||||
}
|
||||
return nil, &HandoverRefusedError{Reason: string(reason)}
|
||||
case headerOffer:
|
||||
default:
|
||||
closeFd(fd)
|
||||
return nil, fmt.Errorf("unknown offer type %d", kind)
|
||||
}
|
||||
if fd < 0 {
|
||||
return nil, errors.New("the offer carries no file descriptor")
|
||||
}
|
||||
dev := fuse.NewDev(fd, nil, nil)
|
||||
neg, err := readPayload(conn, length)
|
||||
if err == nil {
|
||||
err = dev.UnmarshalBinary(neg)
|
||||
}
|
||||
if err != nil {
|
||||
dev.Close()
|
||||
return nil, fmt.Errorf("read the FUSE negotiation: %w", err)
|
||||
}
|
||||
t.dev = dev
|
||||
|
||||
t.count = &countingReader{r: conn}
|
||||
t.br = bufio.NewReaderSize(t.count, 1<<16)
|
||||
frame, err := readControl(t.br)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wait for the state: %w", err)
|
||||
}
|
||||
if frame.Type == ctlAbort {
|
||||
return nil, &HandoverRefusedError{Reason: frame.Reason}
|
||||
}
|
||||
if frame.Type != ctlState {
|
||||
return nil, fmt.Errorf("unexpected %q frame instead of the state", frame.Type)
|
||||
}
|
||||
conn.SetReadDeadline(time.Now().Add(opts.StateTimeout))
|
||||
if err := wfs.ImportHandoverState(t.br); err != nil {
|
||||
t.sendAbort(fmt.Sprintf("import state: %v", err))
|
||||
return nil, fmt.Errorf("import the state: %w", err)
|
||||
}
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
t.StateBytes = t.count.n - int64(t.br.Buffered())
|
||||
glog.V(0).Infof("handover: state imported bytes=%d unix_ns=%d", t.StateBytes, time.Now().UnixNano())
|
||||
ok = true
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Dev takes the FUSE connection out: the caller passes it to
|
||||
// fuse.NewServerFromDev, which owns it from then on.
|
||||
func (t *Takeover) Dev() *fuse.Dev {
|
||||
d := t.dev
|
||||
t.dev = nil
|
||||
return d
|
||||
}
|
||||
|
||||
// Ready tells the old process that this one is prepared to serve.
|
||||
func (t *Takeover) Ready() error {
|
||||
t.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
return writeControl(t.conn, &controlMsg{Type: ctlReady})
|
||||
}
|
||||
|
||||
// WaitGo waits for the old process to say go. After it returns nil this
|
||||
// process owns the mount.
|
||||
func (t *Takeover) WaitGo(timeout time.Duration) error {
|
||||
t.conn.SetReadDeadline(time.Now().Add(timeout))
|
||||
m, err := readControl(t.br)
|
||||
if err != nil {
|
||||
return fmt.Errorf("wait for go: %w", err)
|
||||
}
|
||||
if m.Type != ctlGo {
|
||||
return fmt.Errorf("the running mount answered %q %s instead of go", m.Type, m.Reason)
|
||||
}
|
||||
glog.V(0).Infof("handover: go received unix_ns=%d", time.Now().UnixNano())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Takeover) sendAbort(reason string) {
|
||||
t.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
writeControl(t.conn, &controlMsg{Type: ctlAbort, Reason: reason})
|
||||
}
|
||||
|
||||
// Abort tells the old process this one gives up, and ends the conversation.
|
||||
func (t *Takeover) Abort(reason string) {
|
||||
t.sendAbort(reason)
|
||||
t.Close()
|
||||
}
|
||||
|
||||
// Close ends the conversation, and closes the connection if it was not taken.
|
||||
func (t *Takeover) Close() {
|
||||
if t.dev != nil {
|
||||
t.dev.Close()
|
||||
t.dev = nil
|
||||
}
|
||||
t.conn.Close()
|
||||
}
|
||||
|
||||
func closeFd(fd int) {
|
||||
if fd >= 0 {
|
||||
syscall.Close(fd)
|
||||
}
|
||||
}
|
||||
|
||||
// readHeader reads the fixed-size header with recvmsg directly from the
|
||||
// connection, and the fd that came with it, if any.
|
||||
func readHeader(conn *net.UnixConn) (kind uint16, length uint32, fd int, err error) {
|
||||
fd = -1
|
||||
buf := make([]byte, handoverHeaderSize)
|
||||
oob := make([]byte, syscall.CmsgSpace(4*4))
|
||||
got := 0
|
||||
for got < len(buf) {
|
||||
n, oobn, flags, _, rerr := conn.ReadMsgUnix(buf[got:], oob)
|
||||
if oobn > 0 {
|
||||
msgs, perr := syscall.ParseSocketControlMessage(oob[:oobn])
|
||||
if perr == nil {
|
||||
for i := range msgs {
|
||||
fds, ferr := syscall.ParseUnixRights(&msgs[i])
|
||||
if ferr != nil {
|
||||
continue
|
||||
}
|
||||
for _, f := range fds {
|
||||
if fd < 0 {
|
||||
fd = f
|
||||
} else {
|
||||
syscall.Close(f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if flags&syscall.MSG_CTRUNC != 0 {
|
||||
closeFd(fd)
|
||||
return 0, 0, -1, errors.New("ancillary data truncated")
|
||||
}
|
||||
got += n
|
||||
if rerr != nil {
|
||||
if got < len(buf) {
|
||||
closeFd(fd)
|
||||
return 0, 0, -1, unexpectedEOF(rerr)
|
||||
}
|
||||
// The header is complete: the fd that came with it stays open.
|
||||
break
|
||||
}
|
||||
}
|
||||
if string(buf[:4]) != handoverHeaderMagic {
|
||||
closeFd(fd)
|
||||
return 0, 0, -1, errors.New("bad handover header")
|
||||
}
|
||||
if v := binary.BigEndian.Uint16(buf[4:]); v != handoverProtocolVersion {
|
||||
closeFd(fd)
|
||||
return 0, 0, -1, fmt.Errorf("the running mount speaks handover protocol %d, this one %d", v, handoverProtocolVersion)
|
||||
}
|
||||
return binary.BigEndian.Uint16(buf[6:]), binary.BigEndian.Uint32(buf[8:]), fd, nil
|
||||
}
|
||||
|
||||
func readPayload(r io.Reader, n uint32) ([]byte, error) {
|
||||
if n > maxControlFrame {
|
||||
return nil, fmt.Errorf("payload of %d bytes", n)
|
||||
}
|
||||
b := make([]byte, n)
|
||||
if _, err := io.ReadFull(r, b); err != nil {
|
||||
return nil, unexpectedEOF(err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"net"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// peerUID is the uid of the process on the other end, from SO_PEERCRED.
|
||||
func peerUID(conn *net.UnixConn) (uint32, error) {
|
||||
rc, err := conn.SyscallConn()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var cred *syscall.Ucred
|
||||
var gerr error
|
||||
if err := rc.Control(func(fd uintptr) {
|
||||
cred, gerr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if gerr != nil {
|
||||
return 0, gerr
|
||||
}
|
||||
return cred.Uid, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !linux && !windows
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
func peerUID(conn *net.UnixConn) (uint32, error) {
|
||||
return 0, errors.New("peer credentials are only read on Linux")
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
// backgroundGate lets a handover keep the writers that start flushes on their
|
||||
// own (the periodic metadata flush, the proactive chunk flush, the idle
|
||||
// directory eviction) from beginning new work, and wait for what they run.
|
||||
// Their loops keep ticking; a tick that finds the gate closed does nothing.
|
||||
type backgroundGate struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
active int
|
||||
}
|
||||
|
||||
// beginBackgroundWork reports whether a background writer may run now. A true
|
||||
// answer must be followed by endBackgroundWork.
|
||||
func (wfs *WFS) beginBackgroundWork() bool {
|
||||
g := &wfs.background
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.closed {
|
||||
return false
|
||||
}
|
||||
g.active++
|
||||
return true
|
||||
}
|
||||
|
||||
func (wfs *WFS) endBackgroundWork() {
|
||||
g := &wfs.background
|
||||
g.mu.Lock()
|
||||
g.active--
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
// QuiesceBackground closes the gate and waits until the background writers
|
||||
// that were running have finished. On ctx expiry the gate stays closed, and
|
||||
// the caller reopens it with ResumeBackground when it gives up.
|
||||
func (wfs *WFS) QuiesceBackground(ctx context.Context) error {
|
||||
g := &wfs.background
|
||||
g.mu.Lock()
|
||||
g.closed = true
|
||||
g.mu.Unlock()
|
||||
for {
|
||||
g.mu.Lock()
|
||||
idle := g.active == 0
|
||||
g.mu.Unlock()
|
||||
if idle {
|
||||
return nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(5 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ResumeBackground reopens the gate.
|
||||
func (wfs *WFS) ResumeBackground() {
|
||||
g := &wfs.background
|
||||
g.mu.Lock()
|
||||
g.closed = false
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
// BackgroundQuiesced reports whether the gate is closed.
|
||||
func (wfs *WFS) BackgroundQuiesced() bool {
|
||||
g := &wfs.background
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.closed
|
||||
}
|
||||
|
||||
// PauseMetadataFollow ends the metadata subscription, for a handover. It fails
|
||||
// if the subscription goroutine did not end in time; the caller must not
|
||||
// export state then, as that goroutine may still change the meta cache.
|
||||
func (wfs *WFS) PauseMetadataFollow() error {
|
||||
if wfs.metaFollowResuming.Load() {
|
||||
return errMetadataFollowResuming
|
||||
}
|
||||
if !wfs.stopMetadataFollowWait() {
|
||||
return errMetadataFollowBusy
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resumeMetadataFollowLater runs ResumeMetadataFollow in the background: it
|
||||
// waits for a subscription that did not end in time, which can take as long
|
||||
// as the read that subscription is in. Until it has run PauseMetadataFollow
|
||||
// refuses, as a handover in between would export while the subscription
|
||||
// starts again.
|
||||
func (wfs *WFS) resumeMetadataFollowLater() {
|
||||
wfs.metaFollowResuming.Store(true)
|
||||
go func() {
|
||||
defer wfs.metaFollowResuming.Store(false)
|
||||
wfs.ResumeMetadataFollow()
|
||||
}()
|
||||
}
|
||||
|
||||
type handoverError string
|
||||
|
||||
func (e handoverError) Error() string { return string(e) }
|
||||
|
||||
const (
|
||||
errMetadataFollowBusy = handoverError("the metadata subscription did not stop")
|
||||
errMetadataFollowResuming = handoverError("the metadata subscription is still starting again after a handover was rolled back")
|
||||
)
|
||||
|
||||
// ResumeMetadataFollow starts the subscription again after PauseMetadataFollow,
|
||||
// from the log position of the last event it handled, with the filer.conf
|
||||
// follower it had. It does nothing if the subscription runs, or never started.
|
||||
func (wfs *WFS) ResumeMetadataFollow() {
|
||||
wfs.metaFollowMu.Lock()
|
||||
running := wfs.metaFollowCancel != nil
|
||||
follower := wfs.metaFollower
|
||||
wfs.metaFollowMu.Unlock()
|
||||
if running || wfs.metaCache == nil || follower == nil {
|
||||
return
|
||||
}
|
||||
// A subscription that did not end in time is cancelled and ends on its own.
|
||||
wfs.metaFollowWg.Wait()
|
||||
startTsNs := wfs.metaCache.SubscribedTsNs()
|
||||
start := time.Unix(0, startTsNs)
|
||||
if startTsNs <= 0 {
|
||||
glog.Warningf("handover rollback: no subscription position, following from now")
|
||||
start = time.Now()
|
||||
}
|
||||
if wfs.resumeFollowHook != nil {
|
||||
wfs.resumeFollowHook(start, follower)
|
||||
return
|
||||
}
|
||||
wfs.followMetadataUpdates(start, follower)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//go:build !windows
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
func TestHandoverBackgroundGate(t *testing.T) {
|
||||
wfs := newHandoverWFS(t)
|
||||
if !wfs.beginBackgroundWork() {
|
||||
t.Fatal("gate closed at start")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := wfs.QuiesceBackground(ctx); err == nil {
|
||||
t.Fatal("quiesced with a writer running")
|
||||
}
|
||||
if wfs.beginBackgroundWork() {
|
||||
t.Fatal("a writer began behind a closed gate")
|
||||
}
|
||||
wfs.endBackgroundWork()
|
||||
if err := wfs.QuiesceBackground(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wfs.ResumeBackground()
|
||||
if !wfs.beginBackgroundWork() {
|
||||
t.Fatal("gate still closed after resume")
|
||||
}
|
||||
wfs.endBackgroundWork()
|
||||
}
|
||||
|
||||
func TestTakeoverCacheDirectories(t *testing.T) {
|
||||
read, write := t.TempDir(), t.TempDir()
|
||||
newOption := func(takeover bool) *Option {
|
||||
return &Option{
|
||||
CacheDirForRead: read, CacheDirForWrite: write, Takeover: takeover,
|
||||
MountDirectory: "/mnt/x", FilerMountRootPath: "/",
|
||||
FilerAddresses: []pb.ServerAddress{"127.0.0.1:8888"},
|
||||
}
|
||||
}
|
||||
first := newOption(false)
|
||||
first.setupUniqueCacheDirectory()
|
||||
id := filepath.Base(first.getUniqueCacheDirForRead())
|
||||
|
||||
// A takeover in the same version computes the same id: it gets a suffix
|
||||
// of its own, with a random part, as two processes in containers can
|
||||
// both be pid 1.
|
||||
second := newOption(true)
|
||||
second.setupUniqueCacheDirectory()
|
||||
got := filepath.Base(second.getUniqueCacheDirForRead())
|
||||
if prefix := fmt.Sprintf("%s.t%d-", id, os.Getpid()); !strings.HasPrefix(got, prefix) {
|
||||
t.Fatalf("takeover read directory %s, want %s<random>", got, prefix)
|
||||
}
|
||||
if swap := filepath.Base(filepath.Dir(second.getUniqueCacheDirForWrite())); swap != got {
|
||||
t.Fatalf("takeover swap directory under %s, want %s", swap, got)
|
||||
}
|
||||
again := newOption(true)
|
||||
again.setupUniqueCacheDirectory()
|
||||
if filepath.Base(again.getUniqueCacheDirForRead()) == got {
|
||||
t.Fatalf("two takeovers by one pid got the same directory %s", got)
|
||||
}
|
||||
// The predecessor's directories are still there.
|
||||
for _, d := range []string{first.getUniqueCacheDirForRead(), first.getUniqueCacheDirForWrite()} {
|
||||
if _, err := os.Stat(d); err != nil {
|
||||
t.Fatalf("a takeover removed %s: %v", d, err)
|
||||
}
|
||||
}
|
||||
// A normal start removes the stale takeover siblings and keeps its own.
|
||||
third := newOption(false)
|
||||
third.setupUniqueCacheDirectory()
|
||||
for _, d := range []string{second.getUniqueCacheDirForRead(), filepath.Dir(second.getUniqueCacheDirForWrite())} {
|
||||
if _, err := os.Stat(d); !os.IsNotExist(err) {
|
||||
t.Fatalf("stale directory %s was not removed: %v", d, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(third.getUniqueCacheDirForRead()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ func newHandoverWFS(t *testing.T) *WFS {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
wfs.option.WritebackCache = true
|
||||
wfs.option.FilerMountRootPath = "/"
|
||||
wfs.option.KernelMountFlags = []string{"nodev", "nosuid"}
|
||||
wfs.dhMap = NewDirectoryHandleToInode()
|
||||
wfs.posixLocks = NewPosixLockTable()
|
||||
wfs.posixHint = newPosixLockHint()
|
||||
|
||||
@@ -0,0 +1,633 @@
|
||||
//go:build linux
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
// fakeFuse stands in for the FUSE server on the old side.
|
||||
type fakeFuse struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
blockStop bool
|
||||
stopErr error
|
||||
shutdownErr error
|
||||
panicOnDev bool
|
||||
}
|
||||
|
||||
func (f *fakeFuse) record(c string) {
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, c)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *fakeFuse) Calls() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return slices.Clone(f.calls)
|
||||
}
|
||||
|
||||
func (f *fakeFuse) Stop(ctx context.Context) error {
|
||||
f.record("Stop")
|
||||
if f.blockStop {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return f.stopErr
|
||||
}
|
||||
|
||||
func (f *fakeFuse) Start() error { f.record("Start"); return nil }
|
||||
|
||||
func (f *fakeFuse) Shutdown(ctx context.Context) error {
|
||||
f.record("Shutdown")
|
||||
return f.shutdownErr
|
||||
}
|
||||
|
||||
func (f *fakeFuse) Dev() (*fuse.Dev, error) {
|
||||
f.record("Dev")
|
||||
if f.panicOnDev {
|
||||
panic("boom")
|
||||
}
|
||||
fd, err := syscall.Open("/dev/null", syscall.O_RDWR|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
in := &fuse.InitIn{Major: 7, Minor: 31}
|
||||
out := &fuse.InitOut{Major: 7, Minor: 31, MaxWrite: 1 << 20}
|
||||
return fuse.NewDev(fd, in, out), nil
|
||||
}
|
||||
|
||||
const testMountDir = "/mnt/handover-test"
|
||||
|
||||
type handoverRig struct {
|
||||
t *testing.T
|
||||
src *WFS
|
||||
fake *fakeFuse
|
||||
svc *HandoverService
|
||||
path string
|
||||
paused atomic.Int32
|
||||
resumed atomic.Int32
|
||||
flushes atomic.Int32
|
||||
// flushFail makes the n-th flush fail (1-based), 0 never.
|
||||
flushFail atomic.Int32
|
||||
}
|
||||
|
||||
func newHandoverRig(t *testing.T, opts HandoverOptions) *handoverRig {
|
||||
t.Helper()
|
||||
r := &handoverRig{t: t, src: newHandoverWFS(t), fake: &fakeFuse{}}
|
||||
now := time.Now().Unix()
|
||||
it := r.src.inodeToPath
|
||||
it.Lookup("/a", now, true, false, 0, true)
|
||||
file := it.Lookup("/a/f1", now, false, false, 0, true)
|
||||
r.src.fhMap.AcquireFileHandle(r.src, file, testEntry("f1", file), 111, 5, false)
|
||||
r.src.metaCache.NoteSubscribedTsNs(98765)
|
||||
|
||||
// A running subscription, as far as pause and resume can tell.
|
||||
r.src.metaFollower = &meta_cache.MetadataFollower{}
|
||||
r.src.metaFollowCancel = func() { r.paused.Add(1) }
|
||||
r.src.resumeFollowHook = func(start time.Time, f *meta_cache.MetadataFollower) {
|
||||
r.resumed.Add(1)
|
||||
if start.UnixNano() != 98765 || f != r.src.metaFollower {
|
||||
t.Errorf("subscription resumed from %d with follower %p, want 98765 and the kept one", start.UnixNano(), f)
|
||||
}
|
||||
}
|
||||
|
||||
// A short path: a unix socket path is limited to about 100 bytes, and
|
||||
// t.TempDir carries the test name.
|
||||
sockDir, err := os.MkdirTemp("", "ho")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(sockDir) })
|
||||
r.path = filepath.Join(sockDir, "h.sock")
|
||||
ln, err := ListenHandover(r.path, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if opts.MountDir == "" {
|
||||
opts.MountDir = testMountDir
|
||||
}
|
||||
r.svc = r.src.NewHandoverService(r.fake, ln, opts)
|
||||
r.svc.flush = func(ctx context.Context) error {
|
||||
n := r.flushes.Add(1)
|
||||
if n == r.flushFail.Load() {
|
||||
return errors.New("injected flush failure")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
go r.svc.Serve()
|
||||
t.Cleanup(r.svc.Close)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *handoverRig) takeover(dir string) (*WFS, *Takeover, error) {
|
||||
dst := newHandoverWFS(r.t)
|
||||
tk, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: dir, OfferTimeout: 10 * time.Second})
|
||||
return dst, tk, err
|
||||
}
|
||||
|
||||
// waitIdle waits until the service finished the conversation it was in.
|
||||
func (r *handoverRig) waitIdle() {
|
||||
r.t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for r.svc.busy.Load() && !r.svc.Committed() {
|
||||
if time.Now().After(deadline) {
|
||||
r.t.Fatal("the handover did not end")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// requireRolledBack checks what every rollback must leave: the server
|
||||
// serving, the subscription running, the writers released, nothing committed.
|
||||
func (r *handoverRig) requireRolledBack(wantCalls ...string) {
|
||||
r.t.Helper()
|
||||
r.waitIdle()
|
||||
if got := r.fake.Calls(); !slices.Equal(got, wantCalls) {
|
||||
r.t.Fatalf("server calls %v, want %v", got, wantCalls)
|
||||
}
|
||||
if r.svc.Committed() {
|
||||
r.t.Fatal("committed after a rollback")
|
||||
}
|
||||
if r.src.BackgroundQuiesced() {
|
||||
r.t.Fatal("background writers are still quiesced")
|
||||
}
|
||||
// The subscription starts again in the background.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for r.paused.Load() != r.resumed.Load() {
|
||||
if time.Now().After(deadline) {
|
||||
r.t.Fatalf("subscription paused %d times, resumed %d", r.paused.Load(), r.resumed.Load())
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
select {
|
||||
case <-r.svc.Done():
|
||||
r.t.Fatal("done after a rollback")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func requireRefused(t *testing.T, err error, contains string) {
|
||||
t.Helper()
|
||||
var refused *HandoverRefusedError
|
||||
if !errors.As(err, &refused) {
|
||||
t.Fatalf("error %v, want a refusal", err)
|
||||
}
|
||||
if !strings.Contains(refused.Reason, contains) {
|
||||
t.Fatalf("refused with %q, want %q in it", refused.Reason, contains)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandoverSucceeds(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tk.Close()
|
||||
|
||||
// The state arrived.
|
||||
if tk.StateBytes == 0 {
|
||||
t.Error("no state bytes counted")
|
||||
}
|
||||
if got, _ := dst.inodeToPath.GetInode("/a/f1"); got == 0 {
|
||||
t.Error("the inode of /a/f1 did not cross")
|
||||
}
|
||||
if dst.handoverMetaTsNs != 98765 {
|
||||
t.Errorf("subscription position %d did not cross", dst.handoverMetaTsNs)
|
||||
}
|
||||
// The connection arrived with its negotiation.
|
||||
dev := tk.Dev()
|
||||
defer dev.Close()
|
||||
if _, out := dev.Init(); out.Major != 7 || out.MaxWrite != 1<<20 {
|
||||
t.Errorf("negotiation %+v", out)
|
||||
}
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Fstat(dev.Fd(), &st); err != nil {
|
||||
t.Errorf("the received fd is not usable: %v", err)
|
||||
}
|
||||
|
||||
// Nothing is final before ready, and nothing is closed before go.
|
||||
if slices.Contains(r.fake.Calls(), "Shutdown") || r.svc.Committed() {
|
||||
t.Fatal("old side committed before ready")
|
||||
}
|
||||
if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Dev"}) {
|
||||
t.Fatalf("calls before ready %v", got)
|
||||
}
|
||||
if err := tk.Ready(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tk.WaitGo(10 * time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-r.svc.Done():
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("old side did not finish")
|
||||
}
|
||||
if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Dev", "Shutdown"}) {
|
||||
t.Fatalf("calls %v", got)
|
||||
}
|
||||
if !r.svc.Committed() {
|
||||
t.Fatal("not marked as committed: its exit would unlink the successor's sockets")
|
||||
}
|
||||
if !r.src.BackgroundQuiesced() || r.paused.Load() != 1 || r.resumed.Load() != 0 {
|
||||
t.Fatalf("writers quiesced %v, subscription paused %d resumed %d", r.src.BackgroundQuiesced(), r.paused.Load(), r.resumed.Load())
|
||||
}
|
||||
if got := r.flushes.Load(); got != 2 {
|
||||
t.Fatalf("%d flushes, want one before and one after the stop", got)
|
||||
}
|
||||
// The listener went away with the handover: a second attempt finds nothing.
|
||||
if _, _, err := r.takeover(testMountDir); err == nil {
|
||||
t.Fatal("a handover was offered after the mount was handed over")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandoverRefusals(t *testing.T) {
|
||||
t.Run("wrong mount dir", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
_, _, err := r.takeover("/mnt/somewhere-else")
|
||||
requireRefused(t, err, "serves "+testMountDir)
|
||||
r.requireRolledBack()
|
||||
})
|
||||
t.Run("peer uid", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{AllowPeerUID: func(uint32) bool { return false }})
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "not allowed")
|
||||
r.requireRolledBack()
|
||||
})
|
||||
t.Run("running mount of another uid", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir, AllowPeerUID: func(uint32) bool { return false }})
|
||||
if err == nil || !strings.Contains(err.Error(), "runs as uid") {
|
||||
t.Fatalf("error %v", err)
|
||||
}
|
||||
r.requireRolledBack()
|
||||
})
|
||||
t.Run("blocked lock request", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.src.routedLockWaiters.Add(1)
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "1 lock requests are blocked")
|
||||
r.requireRolledBack()
|
||||
if n := r.flushes.Load(); n != 0 {
|
||||
t.Fatalf("%d flushes before the refusal, want none", n)
|
||||
}
|
||||
r.src.routedLockWaiters.Add(-1)
|
||||
|
||||
// A waiter in the local table counts as well.
|
||||
r.src.posixLocks.mu.Lock()
|
||||
r.src.posixLocks.inodes[77] = &inodeLocks{waiters: []*lockWaiter{{}}}
|
||||
r.src.posixLocks.mu.Unlock()
|
||||
_, _, err = r.takeover(testMountDir)
|
||||
requireRefused(t, err, "1 lock requests are blocked")
|
||||
r.requireRolledBack()
|
||||
})
|
||||
t.Run("peer uid default allows ours", func(t *testing.T) {
|
||||
o := HandoverOptions{}
|
||||
o.withDefaults()
|
||||
if !o.AllowPeerUID(uint32(syscall.Getuid())) || !o.AllowPeerUID(0) || o.AllowPeerUID(uint32(syscall.Getuid())+12345) {
|
||||
t.Fatal("default uid policy")
|
||||
}
|
||||
})
|
||||
t.Run("first flush fails", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.flushFail.Store(1)
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "flush before handover")
|
||||
r.requireRolledBack()
|
||||
})
|
||||
t.Run("stop times out", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{StopTimeout: 200 * time.Millisecond})
|
||||
r.fake.blockStop = true
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "drain requests")
|
||||
r.requireRolledBack("Stop", "Start")
|
||||
|
||||
// The mount keeps serving and a later handover goes through.
|
||||
r.fake.blockStop = false
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatalf("handover after a rollback: %v", err)
|
||||
}
|
||||
tk.Close()
|
||||
})
|
||||
t.Run("final flush fails", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.flushFail.Store(2)
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "final flush")
|
||||
r.requireRolledBack("Stop", "Start")
|
||||
})
|
||||
t.Run("export refuses", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.src.asyncCreates.Add(1) // a create still being sent: the state cannot be carried
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "cannot be handed over")
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
if r.paused.Load() != 1 {
|
||||
t.Fatalf("subscription paused %d times", r.paused.Load())
|
||||
}
|
||||
})
|
||||
t.Run("panic", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.fake.panicOnDev = true
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "panic")
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
})
|
||||
t.Run("peer aborts instead of ready", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk.Abort("test")
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
})
|
||||
t.Run("peer vanishes before ready", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk.Close()
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
})
|
||||
t.Run("peer never answers", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{ReadyTimeout: 300 * time.Millisecond})
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tk.Close()
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
if err := tk.WaitGo(2 * time.Second); err == nil {
|
||||
t.Fatal("go after a timeout")
|
||||
}
|
||||
})
|
||||
t.Run("go cannot be written", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.svc.sendGo = func(net.Conn) error { return errors.New("broken pipe") }
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tk.Close()
|
||||
if err := tk.Ready(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
if err := tk.WaitGo(2 * time.Second); err == nil {
|
||||
t.Fatal("go received although it was not sent")
|
||||
}
|
||||
})
|
||||
t.Run("one at a time", func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, err = r.takeover(testMountDir)
|
||||
requireRefused(t, err, "in progress")
|
||||
tk.Abort("done")
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
})
|
||||
}
|
||||
|
||||
// A frame the peer would refuse is not sent.
|
||||
func TestWriteControlRefusesOversizedFrame(t *testing.T) {
|
||||
var sent strings.Builder
|
||||
err := writeControl(&sent, &controlMsg{Type: ctlAbort, Reason: strings.Repeat("x", maxControlFrame)})
|
||||
if err == nil || sent.Len() != 0 {
|
||||
t.Fatalf("error %v with %d bytes sent, want an error and nothing sent", err, sent.Len())
|
||||
}
|
||||
}
|
||||
|
||||
// A hello that is not one is refused, and so is a peer of another protocol.
|
||||
func TestHandoverBadHello(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
c, err := net.Dial("unix", r.path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if err := writeControl(c, &controlMsg{Type: ctlHello, Version: 99, MountDir: testMountDir}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kind, length, fd, err := readHeader(c.(*net.UnixConn))
|
||||
if err != nil || kind != headerRefused || fd >= 0 {
|
||||
t.Fatalf("header %d %d fd %d err %v", kind, length, fd, err)
|
||||
}
|
||||
reason, _ := readPayload(c, length)
|
||||
if !strings.Contains(string(reason), "unsupported hello") {
|
||||
t.Fatalf("reason %q", reason)
|
||||
}
|
||||
r.requireRolledBack()
|
||||
}
|
||||
|
||||
func TestTakeoverNothingListens(t *testing.T) {
|
||||
dst := newHandoverWFS(t)
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: filepath.Join(os.TempDir(), fmt.Sprintf("none-%d.sock", os.Getpid())), MountDir: testMountDir})
|
||||
if err == nil || !strings.Contains(err.Error(), "nothing answers") {
|
||||
t.Fatalf("error %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The options the state depends on are compared in the hello: a successor
|
||||
// that differs is refused before the running mount flushes or pauses.
|
||||
func TestHandoverOptionsMismatchRefusedBeforePause(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
dst.option.WritebackCache = false // the source runs with writeback on
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir})
|
||||
requireRefused(t, err, "-writebackCache is true here and false in the new process")
|
||||
r.requireRolledBack()
|
||||
if n := r.flushes.Load(); n != 0 {
|
||||
t.Fatalf("%d flushes before the mismatch was refused, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Without default_permissions the kernel leaves the permission checks to the
|
||||
// mount: a successor that counts on the kernel would make none.
|
||||
func TestHandoverDefaultPermissionsMismatchRefusedBeforePause(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
dst.option.KernelDefaultPermissions = !r.src.option.KernelDefaultPermissions
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir})
|
||||
requireRefused(t, err, "default_permissions")
|
||||
r.requireRolledBack()
|
||||
if n := r.flushes.Load(); n != 0 {
|
||||
t.Fatalf("%d flushes before the mismatch was refused, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// The kernel's mount options are fixed in the mount: a successor started with
|
||||
// others, -readOnly or -o noexec say, would run with the old ones without
|
||||
// knowing.
|
||||
func TestHandoverKernelMountOptionsMismatchRefused(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, reason string
|
||||
set func(*WFS)
|
||||
}{
|
||||
{"ro", "the mount flags (-readOnly and -o) are nodev,nosuid here and nodev,nosuid,ro in the new process",
|
||||
func(w *WFS) { w.option.KernelMountFlags = []string{"nodev", "nosuid", "ro"} }},
|
||||
{"noexec", "are nodev,nosuid here and nodev,noexec,nosuid in the new process",
|
||||
func(w *WFS) { w.option.KernelMountFlags = []string{"nodev", "noexec", "nosuid"} }},
|
||||
{"allow_other", "allow_other (", func(w *WFS) { w.option.KernelAllowOther = true }},
|
||||
{"default_permissions", "default_permissions (", func(w *WFS) { w.option.KernelDefaultPermissions = !w.option.KernelDefaultPermissions }},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
c.set(dst)
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir})
|
||||
requireRefused(t, err, c.reason)
|
||||
r.requireRolledBack()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A successor started against other filers would send the reads and writes of
|
||||
// the open files it gets to those: refused before anything pauses.
|
||||
func TestHandoverOtherFilersRefusedBeforePause(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
dst.option.FilerAddresses = []pb.ServerAddress{"10.9.9.9:8888"}
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir})
|
||||
requireRefused(t, err, "the filers are")
|
||||
r.requireRolledBack()
|
||||
if n := r.flushes.Load(); n != 0 {
|
||||
t.Fatalf("%d flushes before the mismatch was refused, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A successor that names a filer of the running mount, however it writes the
|
||||
// address and whatever other filers it lists, serves the same filer store:
|
||||
// the handover goes through.
|
||||
func TestHandoverFilerInCommonAccepted(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
dst := newHandoverWFS(t)
|
||||
// The running mount names its filer with the gRPC port, 127.0.0.1:1.1.
|
||||
dst.option.FilerAddresses = []pb.ServerAddress{"10.9.9.9:8888", "127.0.0.1:1"}
|
||||
tk, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir, OfferTimeout: 10 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tk.Close()
|
||||
defer tk.Dev().Close()
|
||||
if err := tk.Ready(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tk.WaitGo(10 * time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-r.svc.Done():
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("old side did not finish")
|
||||
}
|
||||
if !r.svc.Committed() {
|
||||
t.Fatal("the handover did not commit")
|
||||
}
|
||||
}
|
||||
|
||||
// A subscription that does not end in time fails the handover. The rollback
|
||||
// lets the mount serve again at once, starts the subscription again only once
|
||||
// the old one has ended, and a handover in between is refused before anything
|
||||
// pauses.
|
||||
func TestHandoverRollbackDoesNotWaitForAStuckSubscription(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
r.src.metaFollowWg.Add(1) // a subscription that does not end
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
r.src.metaFollowWg.Done()
|
||||
}
|
||||
}()
|
||||
|
||||
_, _, err := r.takeover(testMountDir)
|
||||
requireRefused(t, err, "did not stop")
|
||||
r.waitIdle()
|
||||
if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Start"}) {
|
||||
t.Fatalf("server calls %v, want it stopped and started again", got)
|
||||
}
|
||||
if n := r.resumed.Load(); n != 0 {
|
||||
t.Fatalf("the subscription started again %d times before the old one ended", n)
|
||||
}
|
||||
|
||||
_, _, err = r.takeover(testMountDir)
|
||||
requireRefused(t, err, "still starting again")
|
||||
if got := r.fake.Calls(); !slices.Equal(got, []string{"Stop", "Start"}) {
|
||||
t.Fatalf("server calls %v: a refused handover paused the mount", got)
|
||||
}
|
||||
|
||||
released = true
|
||||
r.src.metaFollowWg.Done()
|
||||
r.requireRolledBack("Stop", "Start")
|
||||
}
|
||||
|
||||
// A successor that cannot import the state makes the old side roll back, the
|
||||
// nfs export writer that the export stopped included.
|
||||
func TestHandoverImportFailureRollsBack(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
kv := &fakeKv{values: map[string][]byte{}}
|
||||
r.src.exportedHandles = newExportedHandlesForTest(kv, 1, 0)
|
||||
dst := newHandoverWFS(t)
|
||||
dst.exportedHandles = newExportedHandlesForTest(kv, 2, 0)
|
||||
// A successor that holds state already refuses to import.
|
||||
dst.inodeToPath.Lookup("/already", time.Now().Unix(), false, false, 0, true)
|
||||
_, err := dst.BeginTakeover(TakeoverOptions{SocketPath: r.path, MountDir: testMountDir})
|
||||
if err == nil || !strings.Contains(err.Error(), "fresh mount") {
|
||||
t.Fatalf("error %v", err)
|
||||
}
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
h := r.src.exportedHandles
|
||||
h.mu.Lock()
|
||||
stopped := h.handedOver
|
||||
h.mu.Unlock()
|
||||
if stopped {
|
||||
t.Fatal("the nfs export writer is still stopped after the rollback")
|
||||
}
|
||||
}
|
||||
|
||||
// A new mount probes for a running one before it decides to take the mount
|
||||
// over. The probe is no handover: nothing pauses, and a handover right after
|
||||
// it is not turned away as one in progress.
|
||||
func TestHandoverProbe(t *testing.T) {
|
||||
r := newHandoverRig(t, HandoverOptions{})
|
||||
if !HandoverAnswers(r.path) {
|
||||
t.Fatal("the running mount does not answer a probe")
|
||||
}
|
||||
if HandoverAnswers(r.path + ".none") {
|
||||
t.Fatal("a socket nobody listens on answers")
|
||||
}
|
||||
_, tk, err := r.takeover(testMountDir)
|
||||
if err != nil {
|
||||
t.Fatalf("handover right after a probe: %v", err)
|
||||
}
|
||||
tk.Close()
|
||||
r.requireRolledBack("Stop", "Dev", "Start")
|
||||
if n := r.flushes.Load(); n != 2 {
|
||||
t.Fatalf("%d flushes, want the 2 of the one handover", n)
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ type MetaCache struct {
|
||||
isCachedFn func(fullpath util.FullPath) bool
|
||||
invalidateFunc func(EntryInvalidation)
|
||||
onDirectoryUpdate func(dir util.FullPath)
|
||||
subscriptionEpoch atomic.Int32 // first client epoch of the subscription, 0 for 1; see SetSubscriptionEpoch
|
||||
subscribedTsNs atomic.Int64 // log position of the last subscribed event handled; see SubscribedTsNs
|
||||
pinnedChildFn func(*filer.Entry) bool // a child a rebuild must not drop (local-only, not yet on the filer); nil disables
|
||||
dropListingFn func(dir util.FullPath) // drops a directory's cached listing; see dropListingsOf. nil disables
|
||||
@@ -1814,6 +1815,15 @@ func collectEntryInvalidations(resp *filer_pb.SubscribeMetadataResponse) []Entry
|
||||
return invalidations
|
||||
}
|
||||
|
||||
// SetSubscriptionEpoch sets the client epoch the metadata subscription starts
|
||||
// at (default 1; each reconnect adds one). The filer refuses a second
|
||||
// subscription of the same client id and epoch while it still knows the first,
|
||||
// and replaces one of a lower epoch. A mount that took another over keeps its
|
||||
// client id, so it starts above the epoch its predecessor reached.
|
||||
func (mc *MetaCache) SetSubscriptionEpoch(epoch int32) {
|
||||
mc.subscriptionEpoch.Store(epoch)
|
||||
}
|
||||
|
||||
// SubscribedTsNs is the log position of the last event the metadata
|
||||
// subscription handled, applied or skipped as the mount's own. A successor
|
||||
// process resumes the subscription from it. 0 before the first event. The
|
||||
|
||||
@@ -137,10 +137,14 @@ func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32
|
||||
// Replaying the persisted log chunks here keeps the cost off the filer's heap.
|
||||
// The caller's lookup says where to read them from, so a mount that cannot
|
||||
// reach volume servers directly still replays through its filer.
|
||||
startEpoch := mc.subscriptionEpoch.Load()
|
||||
if startEpoch <= 0 {
|
||||
startEpoch = 1
|
||||
}
|
||||
metadataFollowOption := &pb.MetadataFollowOption{
|
||||
ClientName: "mount",
|
||||
ClientId: selfSignature,
|
||||
ClientEpoch: 1,
|
||||
ClientEpoch: startEpoch,
|
||||
SelfSignature: selfSignature,
|
||||
PathPrefix: prefix,
|
||||
AdditionalPathPrefixes: prefixes,
|
||||
@@ -176,6 +180,9 @@ func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32
|
||||
return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err)
|
||||
}
|
||||
metadataFollowOption.ClientEpoch++
|
||||
// The filer holds this epoch now: a later subscription with
|
||||
// the same client id has to start above it.
|
||||
mc.subscriptionEpoch.Store(metadataFollowOption.ClientEpoch)
|
||||
err := follow()
|
||||
if credentials == nil || !errors.Is(err, pb.ErrResubscribe) {
|
||||
return err
|
||||
|
||||
+124
-9
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"path"
|
||||
@@ -39,7 +40,10 @@ import (
|
||||
)
|
||||
|
||||
type Option struct {
|
||||
filerIndex int32 // align memory for atomic read/write
|
||||
filerIndex int32 // align memory for atomic read/write
|
||||
// Takeover is set for a process that takes a live mount over from another
|
||||
// one: it gets cache directories of its own.
|
||||
Takeover bool
|
||||
FilerAddresses []pb.ServerAddress
|
||||
MountDirectory string
|
||||
GrpcDialOption grpc.DialOption
|
||||
@@ -99,6 +103,14 @@ type Option struct {
|
||||
// skips its own redundant permission checks (and the group lookups behind
|
||||
// them) on those hot paths.
|
||||
DefaultPermissions bool
|
||||
// KernelMountFlags (the generic flags: ro, nosuid, nodev, noexec, ...,
|
||||
// sorted), KernelAllowOther and KernelDefaultPermissions are the kernel's
|
||||
// mount options as the command line sets them, by flag or by -o. The
|
||||
// mount does not act on them; a handover compares them, as a successor
|
||||
// cannot change them.
|
||||
KernelMountFlags []string
|
||||
KernelAllowOther bool
|
||||
KernelDefaultPermissions bool
|
||||
|
||||
// Periodic metadata flush interval in seconds (0 to disable)
|
||||
// This protects chunks from being purged by volume.fsck for long-running writes
|
||||
@@ -258,6 +270,17 @@ type WFS struct {
|
||||
// metaFollowers counts the subscription goroutines metaFollowWg tracks,
|
||||
// for a caller that must not wait: a handover exports only at zero.
|
||||
metaFollowers atomic.Int32
|
||||
// metaFollowResuming is set while a rolled back handover waits to start
|
||||
// the subscription again (see resumeMetadataFollowLater).
|
||||
metaFollowResuming atomic.Bool
|
||||
// metaFollower is the filer.conf follower the subscription was started
|
||||
// with, kept so ResumeMetadataFollow can start it again.
|
||||
metaFollower *meta_cache.MetadataFollower
|
||||
// resumeFollowHook replaces the subscription start in tests.
|
||||
resumeFollowHook func(start time.Time, follower *meta_cache.MetadataFollower)
|
||||
// background is the gate of the writers that start flushes on their own,
|
||||
// see handover_quiesce.go.
|
||||
background backgroundGate
|
||||
|
||||
// entryChanged is notified of every applied metadata event, for a front
|
||||
// end that has to push invalidations to its own client.
|
||||
@@ -568,24 +591,69 @@ func (wfs *WFS) StartBackgroundTasks() error {
|
||||
if wfs.lockClient != nil {
|
||||
wfs.followLockRing()
|
||||
}
|
||||
|
||||
follower, err := wfs.subscribeFilerConfEvents()
|
||||
if err != nil {
|
||||
return err
|
||||
// First: a successor holds routed locks the predecessor took, whose
|
||||
// filer leases end unless they are renewed, and what follows may wait
|
||||
// on the filer.
|
||||
if wfs.crossMountLocks() {
|
||||
go wfs.loopRenewPosixLeases()
|
||||
}
|
||||
|
||||
if err := wfs.PrepareBackgroundTasks(); err != nil {
|
||||
return err
|
||||
}
|
||||
if wfs.option.Takeover {
|
||||
// The configuration was read before the predecessor paused. A change
|
||||
// that it applied since does not come again with the subscription,
|
||||
// which starts where the predecessor stopped: read it once more,
|
||||
// before the subscription starts, so that this read cannot land on
|
||||
// top of a newer event. On failure the one read before stays.
|
||||
var err error
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
if err = wfs.loadFilerConf(); err == nil {
|
||||
break
|
||||
}
|
||||
if attempt < 3 {
|
||||
time.Sleep(time.Duration(attempt) * time.Second)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
glog.Warningf("read the filer configuration again after the takeover, keeping the one read before it until its next change: %v", err)
|
||||
}
|
||||
}
|
||||
wfs.metaFollowMu.Lock()
|
||||
follower := wfs.metaFollower
|
||||
wfs.metaFollowMu.Unlock()
|
||||
wfs.followMetadataUpdates(wfs.metadataFollowStart(), follower)
|
||||
go wfs.loopCheckQuota()
|
||||
go wfs.loopFlushDirtyMetadata()
|
||||
go wfs.loopEvictIdleDirCache()
|
||||
go wfs.loopProactiveFlush()
|
||||
if wfs.crossMountLocks() {
|
||||
go wfs.loopRenewPosixLeases()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareBackgroundTasks does what can fail in StartBackgroundTasks: it reads
|
||||
// the filer configuration and builds the follower of its changes. A process
|
||||
// that takes a mount over calls it before the running mount pauses, since
|
||||
// once that mount has handed over there is nothing to give back; afterwards
|
||||
// StartBackgroundTasks finds it done.
|
||||
func (wfs *WFS) PrepareBackgroundTasks() error {
|
||||
wfs.metaFollowMu.Lock()
|
||||
prepared := wfs.metaFollower != nil
|
||||
wfs.metaFollowMu.Unlock()
|
||||
if prepared {
|
||||
return nil
|
||||
}
|
||||
follower, err := wfs.subscribeFilerConfEvents()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wfs.metaFollowMu.Lock()
|
||||
wfs.metaFollower = follower
|
||||
wfs.metaFollowMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// metadataFollowStart is where the metadata subscription starts: now, or the
|
||||
// position a predecessor process handed over. It is also recorded as the
|
||||
// subscription's position, so a mount that hands over before its first event
|
||||
@@ -595,6 +663,11 @@ func (wfs *WFS) metadataFollowStart() time.Time {
|
||||
startTime := time.Now()
|
||||
if wfs.handoverMetaTsNs > 0 {
|
||||
startTime = time.Unix(0, wfs.handoverMetaTsNs)
|
||||
// The client id is the predecessor's too (the signature crossed): its
|
||||
// subscription may not be gone from the filer yet, and the filer
|
||||
// replaces a subscription only for a higher epoch. Seconds since the
|
||||
// epoch grow with every generation and every reconnect adds only one.
|
||||
wfs.metaCache.SetSubscriptionEpoch(int32(time.Now().Unix()))
|
||||
}
|
||||
wfs.metaCache.NoteSubscribedTsNs(startTime.UnixNano())
|
||||
return startTime
|
||||
@@ -648,12 +721,18 @@ const metadataFollowStopWait = 5 * time.Second
|
||||
// goroutine, so nothing is left writing into the meta cache when it closes.
|
||||
// Safe to call more than once and before the follow ever started.
|
||||
func (wfs *WFS) stopMetadataFollow() {
|
||||
wfs.stopMetadataFollowWait()
|
||||
}
|
||||
|
||||
// stopMetadataFollowWait is stopMetadataFollow that tells whether the
|
||||
// goroutine ended within metadataFollowStopWait.
|
||||
func (wfs *WFS) stopMetadataFollowWait() bool {
|
||||
wfs.metaFollowMu.Lock()
|
||||
cancel := wfs.metaFollowCancel
|
||||
wfs.metaFollowCancel = nil
|
||||
wfs.metaFollowMu.Unlock()
|
||||
if cancel == nil {
|
||||
return
|
||||
return true
|
||||
}
|
||||
cancel()
|
||||
|
||||
@@ -664,8 +743,10 @@ func (wfs *WFS) stopMetadataFollow() {
|
||||
}()
|
||||
select {
|
||||
case <-stopped:
|
||||
return true
|
||||
case <-time.After(metadataFollowStopWait):
|
||||
glog.Warningf("metadata subscriber did not stop within %v", metadataFollowStopWait)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1509,21 +1590,55 @@ func (wfs *WFS) loopEvictIdleDirCache() {
|
||||
ticker := time.NewTicker(wfs.dirIdleEvict / 2)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
if !wfs.beginBackgroundWork() {
|
||||
continue
|
||||
}
|
||||
dirs := wfs.inodeToPath.CollectEvictableDirs(time.Now(), wfs.dirIdleEvict)
|
||||
for _, dir := range dirs {
|
||||
wfs.purgeDirectoryCache(dir)
|
||||
}
|
||||
wfs.endBackgroundWork()
|
||||
}
|
||||
}
|
||||
|
||||
func (option *Option) setupUniqueCacheDirectory() {
|
||||
cacheUniqueId := util.Md5String([]byte(option.MountDirectory + string(option.FilerAddresses[0]) + option.FilerMountRootPath + version.Version()))[0:8]
|
||||
if option.Takeover {
|
||||
// The process handing the mount over is still using the directory of
|
||||
// the same id, and a takeover within one version computes that very
|
||||
// id: this process gets its own. The pid alone does not tell two
|
||||
// processes apart that each run as pid 1 of a container sharing the
|
||||
// cache base. The chunk cache therefore starts cold after a handover;
|
||||
// reusing the predecessor's is a later change.
|
||||
cacheUniqueId = fmt.Sprintf("%s%s%d-%08x", cacheUniqueId, takeoverCacheSuffix, os.Getpid(), rand.Uint32())
|
||||
} else {
|
||||
// A normal start has unmounted whatever was there: the directories of
|
||||
// takeover generations that crashed are stale.
|
||||
option.removeStaleTakeoverCacheDirs(cacheUniqueId)
|
||||
}
|
||||
option.uniqueCacheDirForRead = path.Join(option.CacheDirForRead, cacheUniqueId)
|
||||
os.MkdirAll(option.uniqueCacheDirForRead, os.FileMode(0777)&^option.Umask)
|
||||
option.uniqueCacheDirForWrite = filepath.Join(path.Join(option.CacheDirForWrite, cacheUniqueId), "swap")
|
||||
os.MkdirAll(option.uniqueCacheDirForWrite, os.FileMode(0777)&^option.Umask)
|
||||
}
|
||||
|
||||
// takeoverCacheSuffix separates the instance of a process that took a mount
|
||||
// over from the base cache directory id: <id>.t<pid>.
|
||||
const takeoverCacheSuffix = ".t"
|
||||
|
||||
func (option *Option) removeStaleTakeoverCacheDirs(id string) {
|
||||
for _, base := range []string{option.CacheDirForRead, option.CacheDirForWrite} {
|
||||
if base == "" {
|
||||
continue
|
||||
}
|
||||
stale, _ := filepath.Glob(filepath.Join(base, id+takeoverCacheSuffix+"*"))
|
||||
for _, dir := range stale {
|
||||
glog.V(0).Infof("remove stale cache directory %s of a mount taken over earlier", dir)
|
||||
os.RemoveAll(dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (option *Option) getUniqueCacheDirForWrite() string {
|
||||
return option.uniqueCacheDirForWrite
|
||||
}
|
||||
|
||||
@@ -22,7 +22,11 @@ func (wfs *WFS) loopProactiveFlush() {
|
||||
glog.V(0).Infof("proactive chunk flusher started (idle=%v maxHold=%v)", proactiveIdleThreshold, proactiveMaxHoldTime)
|
||||
|
||||
for range ticker.C {
|
||||
if !wfs.beginBackgroundWork() {
|
||||
continue
|
||||
}
|
||||
wfs.proactiveFlushOnce()
|
||||
wfs.endBackgroundWork()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,11 @@ func (wfs *WFS) loopFlushDirtyMetadata() {
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
if !wfs.beginBackgroundWork() {
|
||||
continue
|
||||
}
|
||||
wfs.flushAllDirtyMetadata()
|
||||
wfs.endBackgroundWork()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user