mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* pb: add mount_handover.proto, the state a mount hands to its successor Messages for the in-memory state a new `weed mount` process needs to take over a live FUSE connection. The stream is a small header followed by length-delimited HandoverFrame messages, one record per frame, so a table of millions of inodes is neither encoded nor decoded as a whole. Protobuf keeps the state readable across builds: fields are only added, and a reader ignores fields and frame bodies it does not know, so a newer build imports what an older one exported. File entries reuse filer_pb.Entry. Generated with protoc 33.4 and protoc-gen-go 1.36.6, as mount.pb.go is. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: export and import the in-memory state of a mount for a handover ExportHandoverState / ImportHandoverState carry what a new weed mount process needs to serve the kernel's existing node and handle ids: the inode table (paths, hard-link names, lookup counts, which inodes are directories), open file handles under their fh ids with entry, base entry, entry version and the flags that change later operations, directory handles with the window of entries the kernel is inside, held POSIX/flock locks and the routed (-dlm) session id with its mirror, the mount signature, the sticky per-inode write errors, atime/dir-mtime overlays, removed-directory entries, the -nfsExport records, and the metadata subscription position. Nothing is carried that cannot be: the export is refused, naming every cause, for dirty pages, uploads or deferred flushes, an unpublished create, a handle busy under its lock, a blocked lock waiter (never answered with EINTR, which the kernel turns into a restart only for a caller with a signal pending), a background create, or a filer token. The handle of an unlinked file crosses dirty, as its entry exists only there. Encoding: protobuf (weed/pb/mount_handover.proto), one length-delimited frame per record behind a header with a format version, ending in a frame with the CRC-32. Frames stream, so a million-inode table is neither encoded nor decoded as a whole, and the importer builds the final maps directly. Import verifies the checksum before it changes anything, refuses another mount root, cache mode or a WFS that already holds state, and makes no filer call: a manifest chunk is resolved lazily on the first read, as after a failed resolution. A caller's *bufio.Reader is used as it is and left right behind the state, so more can follow on the same connection. Every structure documents next to its type what crosses, what is rebuilt and what must be empty; a test fails when a field is added without a place in it. Three hooks in existing code, none of which changes behaviour: - MetaCache.SubscribedTsNs is the log position of the last subscribed event handled, applied or skipped as the mount's own. The subscription's start is its first position, so a mount that hands over before its first event still passes one on. WFS.handoverMetaTsNs, which only an import sets, is where StartBackgroundTasks starts the subscription instead of at the start time. - WFS.asyncCreates and WFS.routedLockWaiters count the writeback Mknod create goroutines and the SETLKW calls polling a routed lock. Neither has a handle or a table entry to inspect, and a handover must not drop either. No caller yet: the handover itself follows. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: flush everything a handover would refuse to carry FlushForHandover flushes every open handle that has dirty pages, dirty metadata (this publishes deferred creates, whose only copy is a placeholder in the meta cache that does not cross) or a deferred close flush, through doFlush as fsync does, and waits for the closed files draining in the background and the creates still being sent, all bounded by a context. No new flush logic. It is safe while requests are served, like an fsync of every open file from another thread, which keeps the bulk of the uploads out of the pause. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: measure the handover of a million-inode table Skipped with -short. Logs encode and decode time and bytes for 1M inodes: 1.3 s to export, 1.6 s to import and 39 MB on a 2-vCPU VM. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: hand over a file whose first open was closed Each open of a file has its own fh id over one shared handle. The handle's own id is that of the first open, and stays so when that open is closed: it keys the handle's lock. The import required it to be among the live opens, so a file opened twice and then closed through its first descriptor was exported, and refused by the successor before anything was installed. The import now only requires the handle ids to be distinct, as the lock table does. Tested for both close orders. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: export the subscription position only with its events applied The metadata subscription moves its position on as soon as an event is in the meta cache. What the event does to the inode table and to the open handles, a rename by another mount or a newer entry, is queued for the invalidation worker and happens later. An export in between carried the position of the event without its change, and the successor, resuming behind the event, never applied it: an open file kept its old entry and a renamed inode its old path. The export now refuses while the subscription runs, since it would keep feeding the worker, and waits for the worker to be through what it holds before it takes the handle locks, which the worker needs. The wait is bounded at 5 s and ends in a refusal: the worker can sit in a kernel notification that needs a request served, which nobody does while the FUSE server is stopped. Hooks: WFS.metaFollowers counts the subscription goroutines, and MetaCache.WaitForEntryInvalidationsWithin is the bounded drain. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: an imported subscription position survives another handover The import kept the position for StartBackgroundTasks only, and the export reads the meta cache's, which stayed zero until the subscription started. A mount that handed over again before that passed on no position, and its successor would have followed from its own start time, missing the events in between. The import now also records the position in the meta cache. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: refuse a handover between different lock modes The advisory locks an application holds are either in the mount's own table or, with -dlm and no writeback cache, on the filer, and each mode only asks its own place. The import installed whatever it was given: a successor started with -dlm kept the predecessor's local locks in a table it no longer consults, so a second lock on the same range was granted; one started without it kept routed locks whose leases nothing renews. The mode now crosses in the identity (Identity.routed_locks) and the import refuses another one before it changes anything, as for the cache mode. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: read a handle's dirty state under its lock in the handover flush FlushForHandover runs once while requests are served, and looked for the handles to flush by reading their dirty flags and page state under the handle map's lock only. Writes, truncates and flushes change those under the handle's flush lock, so the read raced with them. Each handle is now examined under its own flush lock, in the worker that flushes it, with the map's lock held only to list the handles: a handle's lock is never taken under the map's. A handle closed since it was listed is left to its release or to the background drain. asyncFlushPending is still read under the map's lock, as RELEASE reads it. The new test runs the flush next to writers and to opens and closes; with the handle lock taken out again the race detector reports the read. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: hand over the nfs export records not yet written to the filer With -nfsExport one background writer keeps the filer's record of every open file. The export listed the inodes that have a path or an open count and marked those still queued for the writer. Two kinds of pending work were missing: - a record to remove. When the removal timer of a closed file fires, the inode has no path and no open left, only its place in the writer's queue, so it was not listed and the registration stayed on the filer; - a write the writer had taken from its queue: in flight, or failed and waiting a second for its retry. It is lost with the process, and the record crossed as clean. The writer now counts what it has taken and not finished (exportedHandles.unwritten), and the export lists queued and unfinished inodes too and marks both dirty. Writes in flight are not waited for: the successor writes the record again under the same owner, with the same result. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * mount: keep followMetadataUpdates' doc comment on its function Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: hand over the owner of the nfs export registrations The owner is a hash of the hostname and mount directory, so a successor in a replaced pod has another one: the records it rewrites or removes would sit next to the exporter's instead of replacing them. The importer takes the exporter's owner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: bound the wait for the held nfs record write in the handover test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: stop the nfs export writer once a handover export starts The successor registers under the exporter's owner, so a record write of the exporter landing after one of the successor's took the record back, and a removal timer firing in the exporter dropped the successor's entry. The export now stops the writer before it captures the records: a write not yet at its put drops it and stays dirty, a put already sent is waited for (the export refuses if it does not return in time), and the writer starts again when the export fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: let the drain test's events through only once the export waits TestHandoverExportWaitsForEventsToReachTheState released the held invalidations 100 ms after it started the export goroutine. A goroutine that started later found the events applied already, and the test passed without testing the wait. The export now calls a test hook, handoverEventSettleStarted, when it starts that wait, with the subscription's position already taken. The test lets the events through only after the hook, and after checking that the export did not finish while they were held. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: wait for the exporter's removal timer instead of a fixed sleep Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: confirm the stopped writer took the removal's wake in the handover test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: whitebear009 <whitebear009@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
467 lines
17 KiB
Go
467 lines
17 KiB
Go
package mount
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"hash"
|
|
"hash/crc32"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
hpb "github.com/seaweedfs/seaweedfs/weed/pb/mount_handover_pb"
|
|
)
|
|
|
|
// Handover state: what a new `weed mount` process needs, beyond the FUSE
|
|
// connection itself, to answer the requests the kernel still holds ids for.
|
|
// The kernel keeps referring to node ids (inodes, with lookup counts) and to
|
|
// file and directory handle ids that this process handed out; the successor
|
|
// must resolve exactly the same ids.
|
|
//
|
|
// Stream layout (schema in weed/pb/mount_handover.proto):
|
|
//
|
|
// magic (8 bytes) | format version (uint32, big endian) |
|
|
// frames: uvarint length, then a HandoverFrame message, one record each |
|
|
// a last frame, End, carrying the CRC-32 (IEEE) of everything before it.
|
|
//
|
|
// Protobuf, framed per record, so the inode table (millions of records) is
|
|
// encoded one record at a time and decoded straight into the table's final
|
|
// maps: neither side holds the encoding or a second copy of the table. It also
|
|
// keeps the state readable across builds, which a handover between two
|
|
// releases needs, as the newer importer reads what the older exporter wrote:
|
|
// fields are only added, and unknown fields and frame bodies are ignored.
|
|
// Entries are filer_pb.Entry. The format version changes only for a change an
|
|
// old reader could not survive; an importer refuses a version it does not
|
|
// know, and its caller keeps the old process serving.
|
|
//
|
|
// Import decodes everything into private structures and verifies the checksum
|
|
// before it touches the WFS, so a truncated or corrupt stream changes nothing.
|
|
//
|
|
// The state carries chunk cipher keys (they are part of file entries): send it
|
|
// over a private channel such as a unix socket, never to disk.
|
|
//
|
|
// Filer tokens (-filer.tokenFile): the read tokens and chunk assignment proofs
|
|
// (readAuth, chunkProofs) are not carried, so a mount with a token source
|
|
// refuses to export instead.
|
|
const (
|
|
handoverMagic = "SWMNTHO\x00"
|
|
handoverFormatVersion = uint32(1)
|
|
|
|
// handoverMaxFrame bounds one record; a file entry with a huge chunk list
|
|
// is the largest.
|
|
handoverMaxFrame = 1 << 30
|
|
)
|
|
|
|
// handoverBlockers collects the reasons an export is refused, so the caller
|
|
// sees all of them at once rather than one per attempt.
|
|
type handoverBlockers []string
|
|
|
|
func (b *handoverBlockers) add(format string, args ...any) {
|
|
*b = append(*b, fmt.Sprintf(format, args...))
|
|
}
|
|
|
|
func (b handoverBlockers) err() error {
|
|
if len(b) == 0 {
|
|
return nil
|
|
}
|
|
const shown = 8
|
|
list := b
|
|
more := ""
|
|
if len(list) > shown {
|
|
more = fmt.Sprintf(" (and %d more)", len(list)-shown)
|
|
list = list[:shown]
|
|
}
|
|
return fmt.Errorf("mount state cannot be handed over: %s%s", strings.Join(list, "; "), more)
|
|
}
|
|
|
|
type handoverEncoder struct {
|
|
w io.Writer
|
|
crc hash.Hash32
|
|
frames uint64
|
|
buf []byte
|
|
}
|
|
|
|
func (e *handoverEncoder) write(frame *hpb.HandoverFrame) error {
|
|
var err error
|
|
e.buf, err = proto.MarshalOptions{}.MarshalAppend(e.buf[:0], frame)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var prefix [binary.MaxVarintLen64]byte
|
|
n := binary.PutUvarint(prefix[:], uint64(len(e.buf)))
|
|
e.crc.Write(prefix[:n])
|
|
e.crc.Write(e.buf)
|
|
e.frames++
|
|
if _, err := e.w.Write(prefix[:n]); err != nil {
|
|
return err
|
|
}
|
|
_, err = e.w.Write(e.buf)
|
|
return err
|
|
}
|
|
|
|
// ExportHandoverState writes the state a successor process needs to serve the
|
|
// kernel's existing node and handle ids. The caller must have stopped reading
|
|
// FUSE requests and drained those in flight (go-fuse Server.Stop), must have
|
|
// ended the metadata subscription (stopMetadataFollow), and should have run
|
|
// FlushForHandover; nothing here talks to the filer.
|
|
//
|
|
// It refuses, naming every cause, when something cannot be carried safely: a
|
|
// file handle with dirty pages, uploads in flight or a deferred close flush; a
|
|
// handle busy under its lock (a delete, rename or flush still running); an
|
|
// unpublished create (it exists only as a placeholder in the meta cache, which
|
|
// does not cross); a lock waiter still blocked, in the local table or polling
|
|
// a routed lock (it is never answered with EINTR, which the kernel turns into
|
|
// a restart only for a caller with a signal pending); a background create or
|
|
// close flush; a metadata subscription still running, or events of it that
|
|
// did not reach the open files in time; an nfs export record still being
|
|
// written; a filer token. The caller then resumes serving. The inode table is
|
|
// read under its lock while it is encoded, so w must not block for long.
|
|
func (wfs *WFS) ExportHandoverState(w io.Writer) (err error) {
|
|
var blockers handoverBlockers
|
|
if wfs.option.FilerTokenSource != nil || wfs.chunkProofs != nil {
|
|
blockers.add("a filer token is configured: read tokens and chunk proofs do not cross")
|
|
}
|
|
// Before the handle locks: the invalidation worker takes them.
|
|
metaResumeTsNs, eventBlockers := wfs.settleMetadataEvents()
|
|
blockers = append(blockers, eventBlockers...)
|
|
handles, release, handleBlockers := wfs.lockHandlesForHandover()
|
|
defer release()
|
|
blockers = append(blockers, handleBlockers...)
|
|
locks, lockBlockers := wfs.captureLocalLocks()
|
|
blockers = append(blockers, lockBlockers...)
|
|
if n := wfs.routedLockWaiters.Load(); n > 0 {
|
|
blockers.add("%d routed lock requests still waiting", n)
|
|
}
|
|
dirHandles, dirBlockers := wfs.captureDirHandles()
|
|
blockers = append(blockers, dirBlockers...)
|
|
wfs.pendingAsyncFlushMu.Lock()
|
|
pending := len(wfs.pendingAsyncFlush)
|
|
wfs.pendingAsyncFlushMu.Unlock()
|
|
if pending > 0 {
|
|
blockers.add("%d closed files still flush in the background", pending)
|
|
}
|
|
if n := wfs.asyncCreates.Load(); n > 0 {
|
|
blockers.add("%d file creates are still being sent to the filer", n)
|
|
}
|
|
if err := wfs.exportedHandles.handOver(handoverEventSettleWait); err != nil {
|
|
blockers.add("%v", err)
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
wfs.exportedHandles.resume()
|
|
}
|
|
}()
|
|
if err := blockers.err(); err != nil {
|
|
return err
|
|
}
|
|
|
|
bw := bufio.NewWriterSize(w, 1<<16)
|
|
if _, err := bw.WriteString(handoverMagic); err != nil {
|
|
return err
|
|
}
|
|
if err := binary.Write(bw, binary.BigEndian, handoverFormatVersion); err != nil {
|
|
return err
|
|
}
|
|
crc := crc32.NewIEEE()
|
|
e := &handoverEncoder{w: bw, crc: crc}
|
|
|
|
identity := &hpb.Identity{
|
|
MountRoot: wfs.option.FilerMountRootPath,
|
|
Writeback: wfs.option.WritebackCache,
|
|
NfsExport: wfs.exportedHandles != nil,
|
|
Signature: wfs.signature,
|
|
PosixSid: wfs.posixSid,
|
|
|
|
MetaResumeTsNs: metaResumeTsNs,
|
|
RoutedLocks: wfs.crossMountLocks(),
|
|
}
|
|
if wfs.exportedHandles != nil {
|
|
identity.NfsOwner = wfs.exportedHandles.owner
|
|
}
|
|
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_Identity{Identity: identity}}); err != nil {
|
|
return err
|
|
}
|
|
if err := wfs.inodeToPath.exportHandover(e); err != nil {
|
|
return err
|
|
}
|
|
if err := wfs.exportFileHandles(e, handles); err != nil {
|
|
return err
|
|
}
|
|
for _, dh := range dirHandles {
|
|
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_DirHandle{DirHandle: dh}}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := wfs.exportLocks(e, locks); err != nil {
|
|
return err
|
|
}
|
|
if err := wfs.exportOverlays(e); err != nil {
|
|
return err
|
|
}
|
|
end := &hpb.End{Crc32: crc.Sum32(), Frames: e.frames}
|
|
// The end frame is outside its own checksum.
|
|
if err := e.write(&hpb.HandoverFrame{Body: &hpb.HandoverFrame_End{End: end}}); err != nil {
|
|
return err
|
|
}
|
|
return bw.Flush()
|
|
}
|
|
|
|
// handoverEventSettleWait bounds how long an export waits for the metadata
|
|
// events already received to reach the open files. A variable for tests.
|
|
var handoverEventSettleWait = 5 * time.Second
|
|
|
|
// handoverEventSettleStarted is called when an export starts that wait, with
|
|
// the subscription's position already taken. A hook for tests.
|
|
var handoverEventSettleStarted = func() {}
|
|
|
|
// settleMetadataEvents returns the log position the successor resumes the
|
|
// metadata subscription from, once every event up to it has had its effect on
|
|
// the state exported next. The subscription moves its position on as soon as an
|
|
// event is in the meta cache, while what the event does to the inode table and
|
|
// to the open handles (a rename by another mount, a newer entry) is queued for
|
|
// the invalidation worker. An export between the two would carry the position
|
|
// without the change, and the successor, resuming behind the event, would
|
|
// never apply it. So the subscription has to be over, or it would keep feeding
|
|
// the worker, and the worker has to be through what it holds. The wait is
|
|
// bounded: the worker may sit in a kernel notification that needs a request
|
|
// served, which no one does while the FUSE server is stopped.
|
|
func (wfs *WFS) settleMetadataEvents() (resumeTsNs int64, blockers handoverBlockers) {
|
|
if wfs.metaCache == nil {
|
|
return 0, nil
|
|
}
|
|
if wfs.metaFollowers.Load() > 0 {
|
|
blockers.add("the metadata subscription is still running")
|
|
return 0, blockers
|
|
}
|
|
resumeTsNs = wfs.metaCache.SubscribedTsNs()
|
|
handoverEventSettleStarted()
|
|
if !wfs.metaCache.WaitForEntryInvalidationsWithin(handoverEventSettleWait) {
|
|
blockers.add("metadata events are still being applied to the open files")
|
|
}
|
|
return resumeTsNs, blockers
|
|
}
|
|
|
|
// handoverImport is a decoded stream, held apart from the WFS until it has
|
|
// been verified in full.
|
|
type handoverImport struct {
|
|
identity *hpb.Identity
|
|
inodes *handoverInodeTable
|
|
fileHandles []*hpb.FileHandle
|
|
dirHandles []*hpb.DirHandle
|
|
localLocks []*hpb.LockSet
|
|
fhLocks []*hpb.LockOwners
|
|
lockHints []*hpb.LockOwners
|
|
routed []*hpb.RoutedKey
|
|
nfs []*hpb.NfsRecord
|
|
atimes []*hpb.InodeTime
|
|
dirMtimes []*hpb.InodeTime
|
|
removedDirs []*hpb.RemovedDir
|
|
contentErrs []*hpb.ContentError
|
|
}
|
|
|
|
// ImportHandoverState installs the state ExportHandoverState wrote into a WFS
|
|
// that has just been constructed: before StartBackgroundTasks, before any
|
|
// request is served, with nothing opened or looked up. It makes no filer call.
|
|
// A stream that is truncated, corrupt, of an unknown version or meant for
|
|
// another mount root, cache mode or lock mode (-dlm) is refused before anything
|
|
// is changed, and so is a WFS that already holds state. Afterwards
|
|
// NewServerFromDev can serve the connection: the kernel's ids resolve as they
|
|
// did in the old process, file handles read, write, flush and release like
|
|
// live ones and refresh their entries lazily, directory listings in progress
|
|
// continue where the kernel is, and the metadata subscription resumes from the
|
|
// exported position instead of the start time.
|
|
//
|
|
// The stream is read through a buffer, which may take more from r than the
|
|
// state. A caller with more to read after it, such as the rest of a handover
|
|
// conversation on the same socket, passes its own *bufio.Reader: that one is
|
|
// used as it is, and is left right behind the End frame.
|
|
func (wfs *WFS) ImportHandoverState(r io.Reader) error {
|
|
br, ok := r.(*bufio.Reader)
|
|
if !ok {
|
|
br = bufio.NewReaderSize(r, 1<<16)
|
|
}
|
|
magic := make([]byte, len(handoverMagic))
|
|
if _, err := io.ReadFull(br, magic); err != nil {
|
|
return fmt.Errorf("read handover state header: %w", unexpectedEOF(err))
|
|
}
|
|
if string(magic) != handoverMagic {
|
|
return errors.New("handover state: bad magic")
|
|
}
|
|
var version uint32
|
|
if err := binary.Read(br, binary.BigEndian, &version); err != nil {
|
|
return fmt.Errorf("read handover state version: %w", unexpectedEOF(err))
|
|
}
|
|
if version != handoverFormatVersion {
|
|
return fmt.Errorf("handover state: format version %d, this build reads %d", version, handoverFormatVersion)
|
|
}
|
|
crc := crc32.NewIEEE()
|
|
imp := &handoverImport{}
|
|
var buf []byte
|
|
var frames uint64
|
|
for {
|
|
length, err := binary.ReadUvarint(br)
|
|
if err != nil {
|
|
return fmt.Errorf("handover state: read frame length: %w", unexpectedEOF(err))
|
|
}
|
|
if length > handoverMaxFrame {
|
|
return fmt.Errorf("handover state: frame of %d bytes", length)
|
|
}
|
|
if uint64(cap(buf)) < length {
|
|
buf = make([]byte, length)
|
|
}
|
|
buf = buf[:length]
|
|
if _, err := io.ReadFull(br, buf); err != nil {
|
|
return fmt.Errorf("handover state: read frame: %w", unexpectedEOF(err))
|
|
}
|
|
frame := &hpb.HandoverFrame{}
|
|
if err := proto.Unmarshal(buf, frame); err != nil {
|
|
return fmt.Errorf("handover state: decode frame: %w", err)
|
|
}
|
|
if end := frame.GetEnd(); end != nil {
|
|
if end.Crc32 != crc.Sum32() || end.Frames != frames {
|
|
return fmt.Errorf("handover state: checksum or frame count mismatch (stream %08x/%d, computed %08x/%d)", end.Crc32, end.Frames, crc.Sum32(), frames)
|
|
}
|
|
break
|
|
}
|
|
var prefix [binary.MaxVarintLen64]byte
|
|
crc.Write(prefix[:binary.PutUvarint(prefix[:], length)])
|
|
crc.Write(buf)
|
|
frames++
|
|
if err := imp.add(frame); err != nil {
|
|
return fmt.Errorf("handover state: %w", err)
|
|
}
|
|
}
|
|
if imp.identity == nil || imp.inodes == nil {
|
|
return errors.New("handover state: identity or inode table missing")
|
|
}
|
|
return wfs.installHandover(imp)
|
|
}
|
|
|
|
func unexpectedEOF(err error) error {
|
|
if errors.Is(err, io.EOF) {
|
|
return io.ErrUnexpectedEOF
|
|
}
|
|
return err
|
|
}
|
|
|
|
// add files one decoded frame. A body this build does not know is skipped.
|
|
func (imp *handoverImport) add(frame *hpb.HandoverFrame) error {
|
|
switch body := frame.Body.(type) {
|
|
case *hpb.HandoverFrame_Identity:
|
|
imp.identity = body.Identity
|
|
case *hpb.HandoverFrame_Inode:
|
|
return imp.table().addInode(body.Inode)
|
|
case *hpb.HandoverFrame_NameFixup:
|
|
imp.table().fixups = append(imp.table().fixups, body.NameFixup)
|
|
case *hpb.HandoverFrame_Forgotten:
|
|
imp.table().forgotten = append(imp.table().forgotten, body.Forgotten)
|
|
case *hpb.HandoverFrame_FileHandle:
|
|
imp.fileHandles = append(imp.fileHandles, body.FileHandle)
|
|
case *hpb.HandoverFrame_DirHandle:
|
|
imp.dirHandles = append(imp.dirHandles, body.DirHandle)
|
|
case *hpb.HandoverFrame_LockSet:
|
|
imp.localLocks = append(imp.localLocks, body.LockSet)
|
|
case *hpb.HandoverFrame_FhLockOwners:
|
|
imp.fhLocks = append(imp.fhLocks, body.FhLockOwners)
|
|
case *hpb.HandoverFrame_LockHint:
|
|
imp.lockHints = append(imp.lockHints, body.LockHint)
|
|
case *hpb.HandoverFrame_RoutedKey:
|
|
imp.routed = append(imp.routed, body.RoutedKey)
|
|
case *hpb.HandoverFrame_NfsRecord:
|
|
imp.nfs = append(imp.nfs, body.NfsRecord)
|
|
case *hpb.HandoverFrame_Atime:
|
|
imp.atimes = append(imp.atimes, body.Atime)
|
|
case *hpb.HandoverFrame_DirMtime:
|
|
imp.dirMtimes = append(imp.dirMtimes, body.DirMtime)
|
|
case *hpb.HandoverFrame_RemovedDir:
|
|
imp.removedDirs = append(imp.removedDirs, body.RemovedDir)
|
|
case *hpb.HandoverFrame_ContentError:
|
|
imp.contentErrs = append(imp.contentErrs, body.ContentError)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (imp *handoverImport) table() *handoverInodeTable {
|
|
if imp.inodes == nil {
|
|
imp.inodes = newHandoverInodeTable()
|
|
}
|
|
return imp.inodes
|
|
}
|
|
|
|
// installHandover puts a verified import into the WFS. Everything that can
|
|
// fail on the data is checked before the first map is replaced.
|
|
func (wfs *WFS) installHandover(imp *handoverImport) error {
|
|
if imp.identity.MountRoot != wfs.option.FilerMountRootPath {
|
|
return fmt.Errorf("handover state is for mount root %q, this mount serves %q", imp.identity.MountRoot, wfs.option.FilerMountRootPath)
|
|
}
|
|
if imp.identity.Writeback != wfs.option.WritebackCache {
|
|
return fmt.Errorf("handover state was exported with writebackCache=%v, this mount runs with %v", imp.identity.Writeback, wfs.option.WritebackCache)
|
|
}
|
|
// The held locks are either in the mount's table or on the filer, and each
|
|
// mode only asks its own place: with another mode here, a lock an
|
|
// application holds would no longer exclude anyone, and one held on the
|
|
// filer would lose the keepalive that renews its lease.
|
|
if imp.identity.RoutedLocks != wfs.crossMountLocks() {
|
|
return fmt.Errorf("handover state was exported with distributed locks (-dlm) in effect=%v, this mount runs with %v", imp.identity.RoutedLocks, wfs.crossMountLocks())
|
|
}
|
|
if err := wfs.requireFreshForHandover(); err != nil {
|
|
return err
|
|
}
|
|
if err := imp.inodes.check(); err != nil {
|
|
return err
|
|
}
|
|
if err := checkHandoverHandles(imp); err != nil {
|
|
return err
|
|
}
|
|
dirHandles := restoreDirHandles(imp.dirHandles)
|
|
if imp.identity.NfsExport && wfs.exportedHandles == nil && len(imp.nfs) > 0 {
|
|
glog.Warningf("handover: dropping %d nfs export records, this mount does not register them", len(imp.nfs))
|
|
}
|
|
|
|
wfs.signature = imp.identity.Signature
|
|
wfs.posixSid = imp.identity.PosixSid
|
|
wfs.handoverMetaTsNs = imp.identity.MetaResumeTsNs
|
|
if wfs.metaCache != nil {
|
|
// Also what this process exports, should it hand over before its own
|
|
// subscription started.
|
|
wfs.metaCache.NoteSubscribedTsNs(wfs.handoverMetaTsNs)
|
|
}
|
|
wfs.inodeToPath.installHandover(imp.inodes)
|
|
wfs.importContentErrors(imp.contentErrs)
|
|
wfs.installFileHandles(imp.fileHandles)
|
|
wfs.dhMap.Lock()
|
|
for id, dh := range dirHandles {
|
|
wfs.dhMap.dir2inode[id] = dh
|
|
}
|
|
wfs.dhMap.Unlock()
|
|
wfs.importLocks(imp)
|
|
wfs.importOverlays(imp)
|
|
return nil
|
|
}
|
|
|
|
// requireFreshForHandover refuses a WFS that already serves or holds state:
|
|
// the import replaces the tables, so it would silently drop what they hold.
|
|
func (wfs *WFS) requireFreshForHandover() error {
|
|
wfs.inodeToPath.RLock()
|
|
inodes := len(wfs.inodeToPath.inode2path)
|
|
wfs.inodeToPath.RUnlock()
|
|
wfs.fhMap.RLock()
|
|
handles := len(wfs.fhMap.inode2fh) + len(wfs.fhMap.fh2inode)
|
|
wfs.fhMap.RUnlock()
|
|
wfs.dhMap.Lock()
|
|
dirHandles := len(wfs.dhMap.dir2inode)
|
|
wfs.dhMap.Unlock()
|
|
wfs.posixLocks.mu.Lock()
|
|
locks := len(wfs.posixLocks.inodes)
|
|
wfs.posixLocks.mu.Unlock()
|
|
if inodes > 1 || handles > 0 || dirHandles > 0 || locks > 0 {
|
|
return fmt.Errorf("handover state can only be imported into a fresh mount (inodes %d, file handles %d, directory handles %d, lock tables %d)", inodes, handles, dirHandles, locks)
|
|
}
|
|
return nil
|
|
}
|