//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 }