mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
* mount: drop the issue number from the shutdown test comment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: end the filer walk when the consumer stopped following Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pb: end the follow when a retried event reports a stop Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: check the subscriber is gone before the late event can end it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: never retry a filer call whose consumer stopped following The walk already stopped on pb.ErrStopFollowing, but RetryOnError still classified the wrapped error by its cause, so a transport-looking cause reran the whole filer walk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pb: keep the cursor behind an event whose retry the follow ended Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: close the meta cache after the follow-cancel test joins it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
364 lines
13 KiB
Go
364 lines
13 KiB
Go
package pb
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/metadata"
|
|
)
|
|
|
|
type EventErrorType int
|
|
|
|
const (
|
|
TrivialOnError EventErrorType = iota
|
|
FatalOnError
|
|
RetryForeverOnError
|
|
DontLogError
|
|
)
|
|
|
|
// MetadataFollowOption is used to control the behavior of the metadata following
|
|
// process. Part of it is used as a cursor to resume the following process.
|
|
type MetadataFollowOption struct {
|
|
ClientName string
|
|
ClientId int32
|
|
ClientEpoch int32
|
|
SelfSignature int32
|
|
PathPrefix string
|
|
AdditionalPathPrefixes []string
|
|
DirectoriesToWatch []string
|
|
StartTsNs int64
|
|
StopTsNs int64
|
|
EventErrorType EventErrorType
|
|
// LogFileReaderFn, when non-nil, enables metadata chunks mode:
|
|
// the server sends log file chunk fids instead of streaming events,
|
|
// and the client reads directly from volume servers.
|
|
LogFileReaderFn LogFileReaderFn
|
|
// FilerJwtProvider, when non-nil, signs the subscription with the source
|
|
// cluster's own filer key instead of this process's configuration.
|
|
FilerJwtProvider security.FilerJwtProvider
|
|
// FilerTokenSource, when non-nil, supplies the receiving filer's admin
|
|
// token for this endpoint on each subscription attempt. An empty token
|
|
// preserves the legacy subscription-credential fallback above the client.
|
|
FilerTokenSource security.FilerTokenSource
|
|
// OnIdleHeartbeat, when non-nil, opts in to idle heartbeats: while the
|
|
// subscriber is caught up the server periodically sends an empty response
|
|
// carrying the current time, and this is called with that timestamp. It is
|
|
// a freshness signal only and does not advance StartTsNs, so the resume
|
|
// checkpoint stays on the last real event.
|
|
OnIdleHeartbeat func(tsNs int64)
|
|
// GetResumeTsNs, when non-nil, supplies the reconnect position instead of
|
|
// StartTsNs. It is read on every subscribe, so a callback can return the
|
|
// durably processed watermark while StartTsNs keeps tracking positions the
|
|
// stream has merely seen.
|
|
GetResumeTsNs func() int64
|
|
// ParentContext bounds the subscription itself. Cancelling it ends the
|
|
// stream, so a consumer that is shutting down can quiesce the follow
|
|
// before closing what the events are applied to. Nil follows the stream's
|
|
// own lifetime, which is the subscription call alone.
|
|
ParentContext context.Context
|
|
// Resubscribe, when closed, drops the stream with ErrResubscribe so the
|
|
// caller's reconnect loop resubscribes from GetResumeTsNs and replays the
|
|
// events still pinning the processed watermark. Target-side job failures
|
|
// never surface on this stream, so without it a pinned event waits for an
|
|
// unrelated source-stream reconnect (or a restart) to be replayed.
|
|
Resubscribe <-chan struct{}
|
|
}
|
|
|
|
// ErrResubscribe ends a metadata follow when the consumer asked for the
|
|
// stream to drop so the reconnect replays what the resume watermark pins.
|
|
var ErrResubscribe = errors.New("resubscribe to replay events behind the failed offset")
|
|
|
|
// ErrStopFollowing ends a metadata follow because the consumer reported a
|
|
// condition that no later event on this stream can get past — a metadata cache
|
|
// that has been closed, for one. Unlike the errors that reach the event error
|
|
// modes, it is not a failure of one event but the end of the subscription, so
|
|
// it leaves the stream instead of being logged per event. It also keeps a
|
|
// consumer's FatalOnError from firing on its own shutdown: the mount exiting is
|
|
// not a fatal condition.
|
|
var ErrStopFollowing = errors.New("stop following metadata")
|
|
|
|
type ProcessMetadataFunc func(resp *filer_pb.SubscribeMetadataResponse) error
|
|
|
|
func FollowMetadata(filerAddress ServerAddress, grpcDialOption grpc.DialOption, option *MetadataFollowOption, processEventFn ProcessMetadataFunc) error {
|
|
|
|
err := WithFilerClient(true, option.SelfSignature, filerAddress, grpcDialOption, makeSubscribeMetadataFunc(option, processEventFn))
|
|
if err != nil {
|
|
return fmt.Errorf("subscribing filer meta change: %w", err)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func WithFilerClientFollowMetadata(filerClient filer_pb.FilerClient, option *MetadataFollowOption, processEventFn ProcessMetadataFunc) error {
|
|
|
|
err := filerClient.WithFilerClient(true, makeSubscribeMetadataFunc(option, processEventFn))
|
|
if err != nil {
|
|
return fmt.Errorf("subscribing filer meta change: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn ProcessMetadataFunc) func(client filer_pb.SeaweedFilerClient) error {
|
|
return func(client filer_pb.SeaweedFilerClient) error {
|
|
parent := option.ParentContext
|
|
if parent == nil {
|
|
parent = context.Background()
|
|
}
|
|
ctx, cancel := context.WithCancel(parent)
|
|
defer cancel()
|
|
sinceNs := option.StartTsNs
|
|
if option.GetResumeTsNs != nil {
|
|
sinceNs = option.GetResumeTsNs()
|
|
}
|
|
subscribeCtx := ctx
|
|
if option.FilerTokenSource != nil {
|
|
var authErr error
|
|
subscribeCtx, authErr = security.WithFilerSubscriptionToken(ctx, option.FilerTokenSource)
|
|
if authErr != nil {
|
|
return fmt.Errorf("resolve subscription credentials: %w", authErr)
|
|
}
|
|
if md, ok := metadata.FromOutgoingContext(subscribeCtx); !ok || len(md.Get("authorization")) == 0 {
|
|
subscribeCtx = security.WithMetadataSubscriptionCredentials(subscribeCtx, option.FilerJwtProvider)
|
|
}
|
|
} else {
|
|
subscribeCtx = security.WithMetadataSubscriptionCredentials(subscribeCtx, option.FilerJwtProvider)
|
|
}
|
|
stream, err := client.SubscribeMetadata(subscribeCtx, &filer_pb.SubscribeMetadataRequest{
|
|
ClientName: option.ClientName,
|
|
PathPrefix: option.PathPrefix,
|
|
PathPrefixes: option.AdditionalPathPrefixes,
|
|
Directories: option.DirectoriesToWatch,
|
|
SinceNs: sinceNs,
|
|
Signature: option.SelfSignature,
|
|
ClientId: option.ClientId,
|
|
ClientEpoch: option.ClientEpoch,
|
|
UntilNs: option.StopTsNs,
|
|
ClientSupportsBatching: true,
|
|
ClientSupportsMetadataChunks: option.LogFileReaderFn != nil,
|
|
ClientSupportsIdleHeartbeat: option.OnIdleHeartbeat != nil,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("subscribe: %w", err)
|
|
}
|
|
|
|
if option.Resubscribe != nil {
|
|
go func() {
|
|
select {
|
|
case <-option.Resubscribe:
|
|
cancel()
|
|
case <-ctx.Done():
|
|
}
|
|
}()
|
|
}
|
|
|
|
resubscribeOr := func(err error) error {
|
|
select {
|
|
case <-option.Resubscribe:
|
|
return ErrResubscribe
|
|
default:
|
|
}
|
|
return err
|
|
}
|
|
|
|
handleErr := func(resp *filer_pb.SubscribeMetadataResponse, err error) error {
|
|
sourcePath := filer_pb.MetadataEventSourceFullPath(resp)
|
|
targetPath := filer_pb.MetadataEventTargetFullPath(resp)
|
|
switch option.EventErrorType {
|
|
case TrivialOnError:
|
|
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
|
|
case FatalOnError:
|
|
glog.Fatalf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
|
|
case RetryForeverOnError:
|
|
waitTime := time.Second
|
|
for ctx.Err() == nil {
|
|
err := processEventFn(resp)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if errors.Is(err, ErrStopFollowing) {
|
|
return err
|
|
}
|
|
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-time.After(waitTime):
|
|
}
|
|
if waitTime < util.RetryWaitTime {
|
|
waitTime += waitTime / 2
|
|
}
|
|
}
|
|
// The follow ended before the event applied: keep the cursor behind it.
|
|
return resubscribeOr(ctx.Err())
|
|
case DontLogError:
|
|
// pass
|
|
default:
|
|
glog.Errorf("process %s -> %s ts_ns=%d: %v", sourcePath, targetPath, resp.TsNs, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// handleOneEvent processes a single response, whether it arrived as the
|
|
// batch envelope or inside resp.Events. Freshness signals carry a timestamp
|
|
// but no entry: the idle heartbeat (nil EventNotification) and the
|
|
// MaxUnsyncedEvents marker (empty one). Both route to OnIdleHeartbeat,
|
|
// else the marker pins sync_offset to the stale processed watermark and a
|
|
// nil heartbeat folded into a batch nil-derefs in the sync job path.
|
|
handleOneEvent := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
|
if resp.EventNotification == nil || filer_pb.IsEmpty(resp) {
|
|
if resp.TsNs > 0 && option.OnIdleHeartbeat != nil {
|
|
option.OnIdleHeartbeat(resp.TsNs)
|
|
}
|
|
// The marker advances the resume cursor past the filtered range; the
|
|
// heartbeat leaves it put so a restart cannot outrun a straggler. A
|
|
// consumer with a resume callback keeps its cursor in its processed
|
|
// watermark, so it sees the marker instead.
|
|
if resp.EventNotification != nil && resp.TsNs > 0 {
|
|
if option.GetResumeTsNs != nil {
|
|
if err := processEventFn(resp); err != nil {
|
|
if errors.Is(err, ErrStopFollowing) {
|
|
return err
|
|
}
|
|
if err := handleErr(resp, err); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
} else {
|
|
option.StartTsNs = resp.TsNs
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := processEventFn(resp); err != nil {
|
|
// A consumer that reported the end of the subscription is not a
|
|
// failed event: the error modes would log it per event, and
|
|
// FatalOnError would abort a process that is only shutting down.
|
|
if errors.Is(err, ErrStopFollowing) {
|
|
return err
|
|
}
|
|
if err := handleErr(resp, err); err != nil {
|
|
return err
|
|
}
|
|
// RetryForeverOnError only returns once the event was handled;
|
|
// other modes leave it failed and the cursor stays behind it.
|
|
if option.EventErrorType != RetryForeverOnError {
|
|
return nil
|
|
}
|
|
}
|
|
if option.GetResumeTsNs == nil {
|
|
option.StartTsNs = resp.TsNs
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var pendingRefs []*filer_pb.LogFileChunkRef
|
|
|
|
// drainPendingRefs reads whatever chunk refs have accumulated. The server
|
|
// sends refs in their own responses, so they can only be read once
|
|
// something tells us the run of refs has ended — either a normal event, or
|
|
// the end of the stream. A bounded subscription (StopTsNs set, range
|
|
// already in the past) may get nothing but refs and then EOF, so draining
|
|
// only on the former silently returns no events at all.
|
|
drainPendingRefs := func() error {
|
|
if len(pendingRefs) == 0 || option.LogFileReaderFn == nil {
|
|
return nil
|
|
}
|
|
readFromNs := option.StartTsNs
|
|
var progressFn func(tsNs int64)
|
|
if option.GetResumeTsNs != nil {
|
|
// The resume cursor lives in the processed watermark, so a
|
|
// resubscribed ref replay must not be filtered by positions the
|
|
// previous stream had only seen.
|
|
readFromNs = sinceNs
|
|
} else {
|
|
// Checkpoint each settled entry so a dropped stream resumes the
|
|
// replay where it stopped instead of re-reading the whole set.
|
|
progressFn = func(tsNs int64) {
|
|
if tsNs > option.StartTsNs {
|
|
option.StartTsNs = tsNs
|
|
}
|
|
}
|
|
}
|
|
lastTs, readErr := ReadLogFileRefs(pendingRefs, option.LogFileReaderFn,
|
|
readFromNs, option.StopTsNs,
|
|
PathFilter{
|
|
PathPrefix: option.PathPrefix,
|
|
AdditionalPathPrefixes: option.AdditionalPathPrefixes,
|
|
DirectoriesToWatch: option.DirectoriesToWatch,
|
|
},
|
|
processEventFn, progressFn)
|
|
if readErr != nil {
|
|
return fmt.Errorf("%w: %w", ErrLogFileRead, readErr)
|
|
}
|
|
// lastTs is the last settled entry's own timestamp; never rewind
|
|
// below the progress checkpoint it may lag.
|
|
if option.GetResumeTsNs == nil && lastTs > option.StartTsNs {
|
|
option.StartTsNs = lastTs
|
|
}
|
|
pendingRefs = nil
|
|
return nil
|
|
}
|
|
|
|
for {
|
|
resp, listenErr := stream.Recv()
|
|
if listenErr == io.EOF {
|
|
return drainPendingRefs()
|
|
}
|
|
if listenErr != nil {
|
|
return resubscribeOr(listenErr)
|
|
}
|
|
|
|
// Accumulate log file chunk references (metadata chunks mode)
|
|
if len(resp.LogFileRefs) > 0 {
|
|
pendingRefs = append(pendingRefs, resp.LogFileRefs...)
|
|
continue
|
|
}
|
|
|
|
// Process accumulated refs before handling normal events (transition point)
|
|
if err := drainPendingRefs(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Process the envelope event (top-level fields) and any batched tail.
|
|
// The server folds a backlog into one response: the first event lives in
|
|
// the top-level fields, the rest in resp.Events. Either slot can hold a
|
|
// freshness signal, so both go through the same handler.
|
|
if err := handleOneEvent(resp); err != nil {
|
|
return err
|
|
}
|
|
for _, batchedEvent := range resp.Events {
|
|
if err := handleOneEvent(batchedEvent); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func AddOffsetFunc(processEventFn ProcessMetadataFunc, offsetInterval time.Duration, offsetFunc func(counter int64, offset int64) error) ProcessMetadataFunc {
|
|
var counter int64
|
|
var lastWriteTime = time.Now()
|
|
return func(resp *filer_pb.SubscribeMetadataResponse) error {
|
|
if err := processEventFn(resp); err != nil {
|
|
return err
|
|
}
|
|
counter++
|
|
if lastWriteTime.Add(offsetInterval).Before(time.Now()) {
|
|
lastWriteTime = time.Now()
|
|
if err := offsetFunc(counter, resp.TsNs); err != nil {
|
|
return err
|
|
}
|
|
counter = 0
|
|
}
|
|
return nil
|
|
}
|
|
|
|
}
|