mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* 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>
872 lines
28 KiB
Go
872 lines
28 KiB
Go
//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
|
|
}
|