diff --git a/other/metrics/grafana_seaweedfs.json b/other/metrics/grafana_seaweedfs.json index 1b114ebc3b..1436b24270 100644 --- a/other/metrics/grafana_seaweedfs.json +++ b/other/metrics/grafana_seaweedfs.json @@ -15239,6 +15239,412 @@ "pluginVersion": "10.3.1" } ] + }, + { + "type": "row", + "title": "S3 Notifications", + "collapsed": true, + "id": 275, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 30 + }, + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Notification records delivered", + "type": "timeseries", + "id": 276, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 31 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "ops", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (target) (rate(SeaweedFS_s3_notification_delivered_records_total{cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{target}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Notification lag", + "description": "Undelivered bucket event records the forwarder can see: current ranges, ranges held back behind an older generation, and sealed retired ranges. An old range still being sealed after a repartition cannot be read yet and is not counted.", + "type": "timeseries", + "id": 277, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 31 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (target) (SeaweedFS_s3_notification_lag_records{cluster=~\"$cluster\"})", + "range": true, + "refId": "A", + "legendFormat": "{{target}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Notification send retries", + "type": "timeseries", + "id": 278, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 39 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "ops", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (target) (rate(SeaweedFS_s3_notification_send_retries_total{cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{target}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Notification records skipped or lost", + "type": "timeseries", + "id": 279, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 39 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (target, reason) (increase(SeaweedFS_s3_notification_skipped_records_total{cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{target}} skipped {{reason}}" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "sum by (target) (increase(SeaweedFS_s3_notification_retention_gap_records_total{cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "B", + "legendFormat": "{{target}} retention gap" + } + ], + "pluginVersion": "10.3.1" + } + ] } ], "refresh": "30s", diff --git a/weed/mq/offset/consumer_group_fence_test.go b/weed/mq/offset/consumer_group_fence_test.go new file mode 100644 index 0000000000..fbbef36fec --- /dev/null +++ b/weed/mq/offset/consumer_group_fence_test.go @@ -0,0 +1,436 @@ +package offset + +import ( + "context" + "errors" + "net" + "slices" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer_client" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// conditionalFiler keeps entries in memory and evaluates the two write +// conditions a fenced save uses. +type conditionalFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + mu sync.Mutex + entries map[string]*filer_pb.Entry + // beforeWrite runs once, ahead of the next transaction, to model a + // concurrent writer landing between a save's read and its write. + beforeWrite func() + // looked counts the lookups of each path + looked map[string]int + // failLookups fails the lookups of these paths, as a filer that cannot read them + failLookups map[string]bool +} + +func (f *conditionalFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.looked == nil { + f.looked = map[string]int{} + } + f.looked[req.Directory+"/"+req.Name]++ + if f.failLookups[req.Directory+"/"+req.Name] { + return nil, status.Error(codes.Unavailable, "store unavailable") + } + entry, ok := f.entries[req.Directory+"/"+req.Name] + if !ok { + return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error()) + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil +} + +func (f *conditionalFiler) ObjectTransaction(ctx context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) { + f.mu.Lock() + hook := f.beforeWrite + f.beforeWrite = nil + f.mu.Unlock() + if hook != nil { + hook() + } + f.mu.Lock() + defer f.mu.Unlock() + current := f.entries[req.ConditionKey] + for _, clause := range req.Condition.GetClauses() { + held := true + switch clause.Kind { + case filer_pb.WriteCondition_IF_NOT_EXISTS: + held = current == nil + case filer_pb.WriteCondition_IF_ENTRY_EQUAL: + held = current != nil && proto.Equal(current, clause.ExpectedEntry) + } + if !held { + return &filer_pb.ObjectTransactionResponse{ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED, Error: "precondition failed"}, nil + } + } + for _, m := range req.Mutations { + f.entries[m.Directory+"/"+m.Entry.Name] = proto.Clone(m.Entry).(*filer_pb.Entry) + } + return &filer_pb.ObjectTransactionResponse{}, nil +} + +func (f *conditionalFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry) + return &filer_pb.CreateEntryResponse{}, nil +} + +func (f *conditionalFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry) + return &filer_pb.UpdateEntryResponse{}, nil +} + +// ListEntries lists the stored entries directly under req.Directory and the +// directories their paths imply. +func (f *conditionalFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + f.mu.Lock() + children := map[string]*filer_pb.Entry{} + for path, entry := range f.entries { + rest, ok := strings.CutPrefix(path, req.Directory+"/") + if !ok { + continue + } + if name, _, deeper := strings.Cut(rest, "/"); deeper { + children[name] = &filer_pb.Entry{Name: name, IsDirectory: true} + } else { + children[name] = entry + } + } + f.mu.Unlock() + names := make([]string, 0, len(children)) + for name := range children { + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + if name <= req.StartFromFileName { + continue + } + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: children[name]}); err != nil { + return err + } + } + return nil +} + +func TestListConsumerGroupPositionsAcrossGenerations(t *testing.T) { + _, s := newFencedStorage(t) + later := topic.Partition{RingSize: 4096, RangeStart: 1024, RangeStop: 2048, UnixTimeNs: 3_000_000_000} + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, later, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: 20}); err != nil { + t.Fatal(err) + } + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, later, "other", &ConsumerGroupPosition{Type: "offset", Value: 30}); err != nil { + t.Fatal(err) + } + // a partition only another group has a position in is listed without one + untouched := topic.Partition{RingSize: 4096, RangeStart: 2048, RangeStop: 4096, UnixTimeNs: 3_000_000_000} + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, untouched, "other", &ConsumerGroupPosition{Type: "offset", Value: 40}); err != nil { + t.Fatal(err) + } + positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", nil) + if err != nil { + t.Fatal(err) + } + value := func(p topic.Partition) int64 { + if position := positions[topic.PartitionDir(fenceTopic, p)]; position != nil { + return position.Value + } + return -1 + } + none, listed := positions[topic.PartitionDir(fenceTopic, untouched)] + if len(positions) != 3 || value(fencePartition) != 10 || value(later) != 20 || !listed || none != nil { + t.Fatalf("listed %v", positions) + } +} + +// A listing whose read of one position fails still returns the positions it +// read, so a caller retrying need not read them again. +func TestListConsumerGroupPositionsReturnsWhatItReadOnAFailure(t *testing.T) { + f, s := newFencedStorage(t) + var dirs []string + for generation := int64(1); generation <= 3; generation++ { + p := topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 4096, UnixTimeNs: generation * 1_000_000_000} + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, p, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: generation}); err != nil { + t.Fatal(err) + } + dirs = append(dirs, topic.PartitionDir(fenceTopic, p)) + } + f.mu.Lock() + f.failLookups = map[string]bool{dirs[1] + "/consumers/forwarder.offset": true} + f.mu.Unlock() + + positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", nil) + if err == nil { + t.Fatal("listing with an unreadable position succeeded") + } + first, third := positions[dirs[0]], positions[dirs[2]] + if _, failed := positions[dirs[1]]; len(positions) != 2 || failed || first == nil || first.Value != 1 || third == nil || third.Value != 3 { + t.Fatalf("listed %v, want the two positions that could be read", positions) + } +} + +// Of many historical partition directories, a listing reads the positions of +// only those the caller does not already know about. +func TestListConsumerGroupPositionsLoadsOnlyWhatIsNotSkipped(t *testing.T) { + f, s := newFencedStorage(t) + var unknown []string + for generation := int64(1); generation <= 40; generation++ { + p := topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 4096, UnixTimeNs: generation * 1_000_000_000} + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, p, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: generation}); err != nil { + t.Fatal(err) + } + if generation%20 == 0 { + unknown = append(unknown, topic.PartitionDir(fenceTopic, p)) + } + } + f.mu.Lock() + f.looked = nil + f.mu.Unlock() + + positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", func(dir string) bool { + return !slices.Contains(unknown, dir) + }) + if err != nil { + t.Fatal(err) + } + first, second := positions[unknown[0]], positions[unknown[1]] + if len(positions) != 2 || first == nil || first.Value != 20 || second == nil || second.Value != 40 { + t.Fatalf("listed %v, want only %v", positions, unknown) + } + f.mu.Lock() + defer f.mu.Unlock() + loads := 0 + for path, n := range f.looked { + if strings.HasSuffix(path, ".offset") { + loads += n + } + } + if loads != 2 { + t.Fatalf("%d position loads, want 2", loads) + } +} + +func startConditionalFiler(t *testing.T) (*conditionalFiler, pb.ServerAddress) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + f := &conditionalFiler{entries: map[string]*filer_pb.Entry{}} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, f) + go server.Serve(listener) + t.Cleanup(server.Stop) + return f, pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port) +} + +func newFencedStorage(t *testing.T) (*conditionalFiler, *FilerConsumerGroupOffsetStorage) { + t.Helper() + f, address := startConditionalFiler(t) + accessor := filer_client.NewFilerClientAccessor([]pb.ServerAddress{address}, grpc.WithTransportCredentials(insecure.NewCredentials())) + return f, NewFilerConsumerGroupOffsetStorageWithAccessor(accessor) +} + +func TestLoadReadsAtTheOwnerFiler(t *testing.T) { + // the accessor's filer still holds an older position than the key's owner + _, s := newFencedStorage(t) + if err := savePosition(s, 50, 5, "a"); err != nil { + t.Fatal(err) + } + _, ownerAddress := startConditionalFiler(t) + s.WriteOwner = func(routeKey string) pb.ServerAddress { return ownerAddress } + if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("load before the owner holds a position: %v, want ErrNotFound", err) + } + if err := savePosition(s, 100, 6, "b"); err != nil { + t.Fatal(err) + } + got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder") + if err != nil { + t.Fatal(err) + } + if got.Value != 100 || got.Generation != 6 { + t.Fatalf("loaded %+v, want the owner's offset 100 at generation 6", got) + } +} + +// While the owner of a position is not known yet, as before the lock ring is +// learned, another filer's answer is not taken: its "not found" may only mean +// it has not caught up, and a takeover there would rewind the partition. +func TestAPositionWaitsForItsOwnerToBeKnown(t *testing.T) { + _, s := newFencedStorage(t) + s.WriteOwner = func(string) pb.ServerAddress { return "" } + if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); err == nil || errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("load with no owner known: %v, want an error other than not found", err) + } + if err := savePosition(s, 10, 5, "a"); err == nil { + t.Fatal("fenced save with no owner known succeeded") + } +} + +func TestFencedSaveReadsAndWritesAtTheOwnerFiler(t *testing.T) { + // the accessor's filer holds an older copy than the key's owner + replica, s := newFencedStorage(t) + owner, ownerAddress := startConditionalFiler(t) + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + var routed []string + s.WriteOwner = func(routeKey string) pb.ServerAddress { + routed = append(routed, routeKey) + return ownerAddress + } + if err := savePosition(s, 20, 7, "c"); err != nil { + t.Fatal(err) + } + if err := savePosition(s, 30, 6, "b"); !errors.Is(err, ErrStaleGeneration) { + t.Fatalf("save below the owner's generation: %v, want ErrStaleGeneration", err) + } + path := topic.PartitionDir(fenceTopic, fencePartition) + "/consumers/forwarder.offset" + if len(routed) != 2 || routed[0] != s3_constants.ObjectWriteRouteKeyPrefix+path { + t.Fatalf("routed %v", routed) + } + owner.mu.Lock() + stored := string(owner.entries[path].GetContent()) + owner.mu.Unlock() + replica.mu.Lock() + stale := string(replica.entries[path].GetContent()) + replica.mu.Unlock() + if !strings.Contains(stored, `"generation":7`) || !strings.Contains(stale, `"generation":5`) { + t.Fatalf("owner holds %s, replica %s", stored, stale) + } +} + +var ( + fenceTopic = topic.NewTopic("s3", "notify-orders") + fencePartition = topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 1024, UnixTimeNs: 1} +) + +func savePosition(s *FilerConsumerGroupOffsetStorage, value, generation int64, writer string) error { + return s.SaveConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder", &ConsumerGroupPosition{ + Type: "offset", Value: value, Generation: generation, Writer: writer, + }) +} + +func TestFencedSaveRefusesAnOlderGeneration(t *testing.T) { + _, s := newFencedStorage(t) + if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("load of a missing position: %v, want ErrNotFound", err) + } + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + if err := savePosition(s, 20, 6, "b"); err != nil { + t.Fatalf("newer generation refused: %v", err) + } + if err := savePosition(s, 30, 5, "a"); !errors.Is(err, ErrStaleGeneration) { + t.Fatalf("deposed writer's save: %v, want ErrStaleGeneration", err) + } + if err := savePosition(s, 30, 6, "c"); !errors.Is(err, ErrStaleGeneration) { + t.Fatalf("another writer at the same generation: %v, want ErrStaleGeneration", err) + } + if err := savePosition(s, 25, 6, "b"); err != nil { + t.Fatalf("holder's own save refused: %v", err) + } + got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder") + if err != nil { + t.Fatal(err) + } + if got.Value != 25 || got.Generation != 6 || got.Writer != "b" { + t.Fatalf("stored %+v", got) + } +} + +// A new generation's first save takes over the partition at the offset the old +// generation committed last, not the one the new one loaded before it, even +// when the old one commits again between that save's read and its write. +func TestATakeoverKeepsTheOffsetItReplaces(t *testing.T) { + f, s := newFencedStorage(t) + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + // generation 6 loaded 10; generation 5 commits 20 and then 30 + if err := savePosition(s, 20, 5, "a"); err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.beforeWrite = func() { + if err := savePosition(s, 30, 5, "a"); err != nil { + t.Error(err) + } + } + f.mu.Unlock() + claim := &ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 6, Writer: "b", Metadata: "claimed"} + if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder", claim); err != nil { + t.Fatal(err) + } + if claim.Value != 30 || claim.Metadata != "" { + t.Fatalf("takeover answered offset %d metadata %q, want offset 30 and the replaced entry's metadata", claim.Value, claim.Metadata) + } + got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder") + if err != nil { + t.Fatal(err) + } + if got.Value != 30 || got.Generation != 6 || got.Writer != "b" { + t.Fatalf("stored %+v, want offset 30 at generation 6 by b", got) + } +} + +func TestFencedSaveRechecksWhenAWriterLandsBetweenReadAndWrite(t *testing.T) { + f, s := newFencedStorage(t) + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + // a newer generation lands after this save read generation 5 + f.mu.Lock() + f.beforeWrite = func() { + if err := savePosition(s, 40, 7, "c"); err != nil { + t.Error(err) + } + } + f.mu.Unlock() + if err := savePosition(s, 20, 6, "b"); !errors.Is(err, ErrStaleGeneration) { + t.Fatalf("save racing a newer generation: %v, want ErrStaleGeneration", err) + } + got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder") + if err != nil { + t.Fatal(err) + } + // generation 7 took over at the offset generation 5 committed + if got.Value != 10 || got.Generation != 7 || got.Writer != "c" { + t.Fatalf("stored %+v, want the newer generation's", got) + } +} + +func TestUnfencedSaveStillOverwrites(t *testing.T) { + _, s := newFencedStorage(t) + if err := savePosition(s, 10, 5, "a"); err != nil { + t.Fatal(err) + } + if err := s.SaveConsumerGroupOffset(fenceTopic, fencePartition, "forwarder", 3); err != nil { + t.Fatal(err) + } + got, err := s.LoadConsumerGroupOffset(fenceTopic, fencePartition, "forwarder") + if err != nil || got != 3 { + t.Fatalf("offset %d, %v", got, err) + } +} diff --git a/weed/mq/offset/consumer_group_storage.go b/weed/mq/offset/consumer_group_storage.go index 13721c707e..e3de9fe3d6 100644 --- a/weed/mq/offset/consumer_group_storage.go +++ b/weed/mq/offset/consumer_group_storage.go @@ -3,17 +3,32 @@ package offset import ( "context" "encoding/json" + "errors" "fmt" "io" + "math" + "sync" "time" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/filer_client" "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" + "golang.org/x/sync/errgroup" ) +// ErrStaleGeneration refuses a save fenced by a generation that another +// writer has superseded. +var ErrStaleGeneration = errors.New("consumer group position is held by a newer generation") + +// fencedSaveAttempts bounds the retries of a fenced save whose stored position +// changed between its read and its write. +const fencedSaveAttempts = 5 + // ConsumerGroupPosition represents a consumer's position in a partition // This can be either a timestamp or an offset type ConsumerGroupPosition struct { @@ -22,6 +37,15 @@ type ConsumerGroupPosition struct { OffsetType string `json:"offset_type"` // Optional: OffsetType enum name (e.g., "EXACT_OFFSET") CommittedAt int64 `json:"committed_at"` // Unix timestamp in milliseconds when committed Metadata string `json:"metadata"` // Optional: application-specific metadata + // Generation, when set, fences the save: it is refused when the stored + // position carries a newer generation, or the same one from another Writer. + Generation int64 `json:"generation,omitempty"` + Writer string `json:"writer,omitempty"` +} + +// supersedes reports whether a stored position fences out a save of p. +func (stored *ConsumerGroupPosition) supersedes(p *ConsumerGroupPosition) bool { + return stored.Generation > p.Generation || (stored.Generation == p.Generation && stored.Writer != p.Writer) } // ConsumerGroupOffsetStorage handles consumer group offset persistence @@ -31,14 +55,15 @@ type ConsumerGroupOffsetStorage interface { // SaveConsumerGroupOffset saves the committed offset for a consumer group SaveConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string, offset int64) error - // SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group - SaveConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error + // SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group; + // a position with a Generation is refused with ErrStaleGeneration when a newer one is stored + SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error // LoadConsumerGroupOffset loads the committed offset for a consumer group (backward compatible) LoadConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string) (int64, error) // LoadConsumerGroupPosition loads the committed position for a consumer group - LoadConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) + LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) // ListConsumerGroups returns all consumer groups for a topic partition ListConsumerGroups(t topic.Topic, p topic.Partition) ([]string, error) @@ -50,6 +75,10 @@ type ConsumerGroupOffsetStorage interface { // FilerConsumerGroupOffsetStorage implements ConsumerGroupOffsetStorage using SeaweedFS filer type FilerConsumerGroupOffsetStorage struct { filerClientAccessor *filer_client.FilerClientAccessor + // WriteOwner, when set, names the filer owning a route key. Loads and + // fenced saves then go there, so a save's condition is checked against what + // it read and a load sees the latest save, not another filer's copy. + WriteOwner func(routeKey string) pb.ServerAddress } // NewFilerConsumerGroupOffsetStorageWithAccessor creates storage using a shared filer client accessor @@ -69,31 +98,111 @@ func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupOffset(t topic.Topic, OffsetType: schema_pb.OffsetType_EXACT_OFFSET.String(), CommittedAt: time.Now().UnixMilli(), } - return f.SaveConsumerGroupPosition(t, p, consumerGroup, position) + return f.SaveConsumerGroupPosition(context.Background(), t, p, consumerGroup, position) } // SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group // Stores as JSON: /topics/{namespace}/{topic}/{version}/{partition}/consumers/{consumer_group}.offset -func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error { +func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error { partitionDir := topic.PartitionDir(t, p) consumersDir := fmt.Sprintf("%s/consumers", partitionDir) offsetFileName := fmt.Sprintf("%s.offset", consumerGroup) - // Marshal position to JSON - jsonBytes, err := json.Marshal(position) - if err != nil { - return fmt.Errorf("failed to marshal position to JSON: %w", err) + if position.Generation == 0 { + jsonBytes, err := json.Marshal(position) + if err != nil { + return fmt.Errorf("failed to marshal position to JSON: %w", err) + } + return f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + return filer.SaveInsideFiler(ctx, client, consumersDir, offsetFileName, jsonBytes) + }) } + return f.saveFencedPosition(ctx, consumersDir, offsetFileName, position) +} - return f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return filer.SaveInsideFiler(context.Background(), client, consumersDir, offsetFileName, jsonBytes) +// saveFencedPosition writes the position only while no newer generation is +// stored, as a conditional write on the stored entry routed to its owner filer. +// A save taking over from an older generation keeps the offset and metadata +// that generation committed last, and sets them in position. +func (f *FilerConsumerGroupOffsetStorage) saveFencedPosition(ctx context.Context, dir, name string, position *ConsumerGroupPosition) error { + path := dir + "/" + name + routeKey := s3_constants.ObjectWriteRouteKeyPrefix + path + // a refusal is returned from outside the accessor, which would otherwise + // try the next filer and flatten the error + var stale *ConsumerGroupPosition + requested, requestedMetadata := position.Value, position.Metadata + err := f.withPositionFiler(routeKey, func(client filer_pb.SeaweedFilerClient) error { + for attempt := 1; ; attempt++ { + condition := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS} + position.Value, position.Metadata = requested, requestedMetadata + resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name}) + switch { + case err == nil: + stored := &ConsumerGroupPosition{} + if json.Unmarshal(resp.Entry.Content, stored) == nil { + if stored.supersedes(position) { + stale = stored + return nil + } + if stored.Generation < position.Generation { + position.Value, position.Metadata = stored.Value, stored.Metadata + } + } + condition = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: resp.Entry} + case !errors.Is(err, filer_pb.ErrNotFound): + return err + } + content, err := json.Marshal(position) + if err != nil { + return fmt.Errorf("failed to marshal position to JSON: %w", err) + } + now := time.Now() + entry := &filer_pb.Entry{ + Name: name, + Attributes: &filer_pb.FuseAttributes{ + Mtime: now.Unix(), + Crtime: now.Unix(), + FileMode: uint32(0644), + FileSize: uint64(len(content)), + Md5: util.Md5(content), + }, + Content: content, + } + txn, err := client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{ + LockKey: path, + RouteKey: routeKey, + ConditionKey: path, + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{condition}}, + Mutations: []*filer_pb.ObjectMutation{{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry}}, + }) + if err != nil { + return err + } + if txn.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && attempt < fencedSaveAttempts { + continue + } + if txn.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED { + return fmt.Errorf("save %s: changed by another writer %d times in a row", path, attempt) + } + if txn.Error != "" { + return fmt.Errorf("save %s: %s", path, txn.Error) + } + return nil + } }) + if err != nil { + return err + } + if stale != nil { + return fmt.Errorf("%s at generation %d by %s: %w", path, stale.Generation, stale.Writer, ErrStaleGeneration) + } + return nil } // LoadConsumerGroupOffset loads the committed offset for a consumer group // This method provides backward compatibility and returns just the offset value func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string) (int64, error) { - position, err := f.LoadConsumerGroupPosition(t, p, consumerGroup) + position, err := f.LoadConsumerGroupPosition(context.Background(), t, p, consumerGroup) if err != nil { return -1, err } @@ -101,14 +210,21 @@ func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupOffset(t topic.Topic, } // LoadConsumerGroupPosition loads the committed position for a consumer group -func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) { +func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) { partitionDir := topic.PartitionDir(t, p) consumersDir := fmt.Sprintf("%s/consumers", partitionDir) offsetFileName := fmt.Sprintf("%s.offset", consumerGroup) var position *ConsumerGroupPosition - err := f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - data, err := filer.ReadInsideFiler(context.Background(), client, consumersDir, offsetFileName) + notFound := false + routeKey := s3_constants.ObjectWriteRouteKeyPrefix + consumersDir + "/" + offsetFileName + err := f.withPositionFiler(routeKey, func(client filer_pb.SeaweedFilerClient) error { + data, err := filer.ReadInsideFiler(ctx, client, consumersDir, offsetFileName) + if errors.Is(err, filer_pb.ErrNotFound) { + // answered by a reachable filer, so no other filer is asked + notFound = true + return nil + } if err != nil { return err } @@ -125,10 +241,97 @@ func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(t topic.Topi if err != nil { return nil, err } + if notFound { + return nil, fmt.Errorf("%s/%s: %w", consumersDir, offsetFileName, filer_pb.ErrNotFound) + } return position, nil } +// ListConsumerGroupPositions lists every partition directory of every generation +// of t but those skip reports, with consumerGroup's position in it, nil where +// the group stored none. Only the directories listed have their position read. +// When a read fails, as on ctx ending, it returns the positions read along with +// the error, so a caller retrying can skip those next time. +func (f *FilerConsumerGroupOffsetStorage) ListConsumerGroupPositions(ctx context.Context, t topic.Topic, consumerGroup string, skip func(dir string) bool) (map[string]*ConsumerGroupPosition, error) { + var partitions []topic.Partition + err := f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + partitions = nil + var versions []string + err := filer_pb.SeaweedList(ctx, client, t.Dir(), "", func(entry *filer_pb.Entry, isLast bool) error { + if _, parseErr := topic.ParseTopicVersion(entry.Name); entry.IsDirectory && parseErr == nil { + versions = append(versions, entry.Name) + } + return nil + }, "", false, math.MaxInt32) + if err != nil { + return err + } + for _, version := range versions { + versionTime, _ := topic.ParseTopicVersion(version) + err := filer_pb.SeaweedList(ctx, client, t.Dir()+"/"+version, "", func(entry *filer_pb.Entry, isLast bool) error { + if start, stop := topic.ParsePartitionBoundary(entry.Name); entry.IsDirectory && start != stop { + partitions = append(partitions, topic.Partition{RangeStart: start, RangeStop: stop, UnixTimeNs: versionTime.UnixNano()}) + } + return nil + }, "", false, math.MaxInt32) + if err != nil { + return err + } + } + return nil + }) + if errors.Is(err, filer_pb.ErrNotFound) { + return nil, nil + } + if err != nil { + return nil, err + } + var mu sync.Mutex + positions := map[string]*ConsumerGroupPosition{} + var loads errgroup.Group + loads.SetLimit(listPositionLoads) + for _, p := range partitions { + dir := topic.PartitionDir(t, p) + if skip != nil && skip(dir) { + continue + } + loads.Go(func() error { + position, err := f.LoadConsumerGroupPosition(ctx, t, p, consumerGroup) + if errors.Is(err, filer_pb.ErrNotFound) { + position, err = nil, nil + } + if err != nil { + return err + } + mu.Lock() + positions[dir] = position + mu.Unlock() + return nil + }) + } + err = loads.Wait() + return positions, err +} + +// listPositionLoads bounds the position reads a listing has in flight. +const listPositionLoads = 8 + +// withPositionFiler runs fn against the filer owning routeKey when WriteOwner +// is set, so a load sees what a fenced save there wrote, else any filer. With +// WriteOwner set but no owner known yet it fails rather than ask another filer, +// whose "not found" may only mean it has not caught up. +func (f *FilerConsumerGroupOffsetStorage) withPositionFiler(routeKey string, fn func(filer_pb.SeaweedFilerClient) error) error { + if f.WriteOwner != nil { + owner := f.WriteOwner(routeKey) + if owner == "" { + return fmt.Errorf("no filer owns %s yet", routeKey) + } + return pb.WithGrpcFilerClient(false, 0, owner, f.filerClientAccessor.GetGrpcDialOption(), f.filerClientAccessor.TokenSource, fn) + } + return f.filerClientAccessor.WithFilerClient(false, fn) +} + // ListConsumerGroups returns all consumer groups for a topic partition func (f *FilerConsumerGroupOffsetStorage) ListConsumerGroups(t topic.Topic, p topic.Partition) ([]string, error) { partitionDir := topic.PartitionDir(t, p) diff --git a/weed/s3api/s3api_bucket_notification_test.go b/weed/s3api/s3api_bucket_notification_test.go index 4aeec47dc6..23df5023d1 100644 --- a/weed/s3api/s3api_bucket_notification_test.go +++ b/weed/s3api/s3api_bucket_notification_test.go @@ -103,15 +103,16 @@ func (f *fakeNotificationPublisher) published() []s3notification.Message { return append([]s3notification.Message(nil), f.messages...) } -func TestNotificationTargetsChangeSyncsThePublisher(t *testing.T) { - publisher := &fakeNotificationPublisher{} - s3a := &S3ApiServer{notificationPublisher: publisher} +func TestNotificationTargetsChangeSyncsThePublisherAndForwarder(t *testing.T) { + publisher, forwarder := &fakeNotificationPublisher{}, &fakeNotificationPublisher{} + s3a := &S3ApiServer{notificationPublisher: publisher, notificationForwarder: forwarder} dir, file := s3notification.TargetsDirectory, s3notification.TargetsFile s3a.onNotificationTargetsChange(dir, nil, targetsEntry(file, testNotificationTargets)) s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), targetsEntry(file, `{"targets":[{"name":"x","type":"nope"}]}`)) s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), nil) require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, publisher.synced) + require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, forwarder.synced) } func TestLoadNotificationTargets(t *testing.T) { diff --git a/weed/s3api/s3api_notification_publish.go b/weed/s3api/s3api_notification_publish.go index 126fec4257..4dac08a6a1 100644 --- a/weed/s3api/s3api_notification_publish.go +++ b/weed/s3api/s3api_notification_publish.go @@ -2,13 +2,17 @@ package s3api import ( "context" + "fmt" "net/http" "slices" "sync" "time" "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/filer_client" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/mq/offset" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" @@ -17,6 +21,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/request_id" + "google.golang.org/grpc" ) const notificationBrokerListTimeout = 5 * time.Second @@ -40,6 +45,42 @@ func (s3a *S3ApiServer) newNotificationPublisher() notificationPublisher { return s3notification.NewPublisher(s3a.notificationBrokers, dialOption) } +// notificationForwarder is what the gateway needs from s3notification.Forwarder. +type notificationForwarder interface { + Sync(reg *s3notification.Registry) + Close() +} + +// newNotificationForwarder elects forwarders through the filers' lock ring and +// stores their offsets in the filer; without filers there is neither. As for +// the publisher, an unusable grpc.msg_broker client TLS config leaves it off. +func (s3a *S3ApiServer) newNotificationForwarder() notificationForwarder { + if s3a.objectWriteLockClient == nil || len(s3a.option.Filers) == 0 { + return nil + } + dialOption, err := security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker") + if err != nil { + glog.Errorf("bucket notification forwarding is off: %v", err) + return nil + } + accessor := &filer_client.FilerClientAccessor{ + GetGrpcDialOption: func() grpc.DialOption { return s3a.option.GrpcDialOption }, + GetFilers: func() []pb.ServerAddress { + if s3a.filerClient != nil { + if filers := s3a.filerClient.GetAllFilers(); len(filers) > 0 { + return filers + } + } + return s3a.option.Filers + }, + TokenSource: security.FilerAdminToken, + } + positions := offset.NewFilerConsumerGroupOffsetStorageWithAccessor(accessor) + positions.WriteOwner = s3a.objectWriteLockClient.PrimaryForKey + owner := fmt.Sprintf("s3-%s-%d", util.JoinHostPort(s3a.option.AdvertisedHost(), s3a.option.Port), s3a.randomClientId) + return s3notification.NewForwarder(s3a.notificationBrokers, dialOption, positions, s3a.objectWriteLockClient, owner) +} + // notificationBrokers lists the brokers a publisher bootstraps from: the one // beside this gateway first, then every broker the masters know. func (s3a *S3ApiServer) notificationBrokers() []string { @@ -207,9 +248,13 @@ func notificationPrincipal(r *http.Request) string { return s3_constants.AccountAnonymousId } -// syncNotificationPublisher gives every target in reg a publisher worker. +// syncNotificationPublisher gives every target in reg a publisher worker and, +// when it has a destination, a forwarder. func (s3a *S3ApiServer) syncNotificationPublisher(reg *s3notification.Registry) { if s3a.notificationPublisher != nil { s3a.notificationPublisher.Sync(reg) } + if s3a.notificationForwarder != nil { + s3a.notificationForwarder.Sync(reg) + } } diff --git a/weed/s3api/s3api_notification_publish_test.go b/weed/s3api/s3api_notification_publish_test.go index a55fb2b346..fe008bd5a1 100644 --- a/weed/s3api/s3api_notification_publish_test.go +++ b/weed/s3api/s3api_notification_publish_test.go @@ -3,8 +3,12 @@ package s3api import ( "testing" + "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) func TestNotificationBrokersStartWithTheGatewaysOwn(t *testing.T) { @@ -28,3 +32,18 @@ func TestABadBrokerTLSConfigTurnsNotificationsOff(t *testing.T) { require.NotNil(t, publisher) publisher.Close() } + +func TestABadBrokerTLSConfigTurnsForwardingOff(t *testing.T) { + v := util.GetViper() + v.Set("grpc.msg_broker.cert", "/nonexistent/broker.crt") + t.Cleanup(func() { v.Set("grpc.msg_broker.cert", "") }) + + option := &S3ApiServerOption{Filers: []pb.ServerAddress{"127.0.0.1:8888"}, GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())} + s3a := &S3ApiServer{option: option, objectWriteLockClient: cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])} + require.Nil(t, s3a.newNotificationForwarder(), "a cert without its key must leave forwarding off, not stop the gateway") + + v.Set("grpc.msg_broker.cert", "") + forwarder := s3a.newNotificationForwarder() + require.NotNil(t, forwarder) + forwarder.Close() +} diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index ce95cfa37f..8bb98cb754 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -171,6 +171,7 @@ type S3ApiServer struct { notificationTargets atomic.Pointer[s3notification.Registry] notificationPublisher notificationPublisher + notificationForwarder notificationForwarder } type objectWriteLock interface { @@ -588,6 +589,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl watched = append(watched, dir) } s3ApiServer.notificationPublisher = s3ApiServer.newNotificationPublisher() + s3ApiServer.notificationForwarder = s3ApiServer.newNotificationForwarder() s3ApiServer.loadNotificationTargets() go s3ApiServer.subscribeMetaEvents("s3", startTsNs, filer.DirectoryEtcRoot, watched) @@ -634,6 +636,9 @@ func (s3a *S3ApiServer) Shutdown() { if s3a.notificationPublisher != nil { s3a.notificationPublisher.Close() } + if s3a.notificationForwarder != nil { + s3a.notificationForwarder.Close() + } } // getFilerAddress returns the current active filer address diff --git a/weed/s3api/s3notification/forwarder.go b/weed/s3api/s3notification/forwarder.go new file mode 100644 index 0000000000..204e457bc3 --- /dev/null +++ b/weed/s3api/s3notification/forwarder.go @@ -0,0 +1,1021 @@ +package s3notification + +import ( + "context" + "errors" + "fmt" + "maps" + "math" + "reflect" + "slices" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/mq/broker" + "github.com/seaweedfs/seaweedfs/weed/mq/offset" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" + "github.com/seaweedfs/seaweedfs/weed/stats" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" +) + +const ( + // ForwarderGroup is the consumer group forwarders store their offsets under. + ForwarderGroup = "forwarder" + // claimedPosition marks an offset a lead claimed but read nothing from yet + claimedPosition = "claimed" + // ForwarderLockPrefix and the target name make the lock that elects the + // gateway forwarding a target. + ForwarderLockPrefix = "s3.notify." + + forwardBatchMessages = 100 + forwardBatchBytes = 1 << 20 + forwardRPCTimeout = 30 * time.Second + + forwardLockCheckInterval = time.Second + forwardIdleWait = time.Second + forwardMinBackoff = time.Second + forwardMaxBackoff = time.Minute + forwardPartitionRefresh = 30 * time.Second + forwardHoldLogInterval = time.Minute + forwardStallWarnInterval = time.Minute + // A lock still held this long after a refused save was renewed after the + // refusal, so the generation that refused it no longer holds the lock. + forwardReclaimWait = 2 * lock_manager.LiveLockTTL +) + +// errDeposed means a newer forwarder of the target stored a partition's offset. +var errDeposed = errors.New("a newer forwarder holds the target") + +// forwarderLock is what a forwarder needs from cluster.LiveLock. +type forwarderLock interface { + IsLocked() bool + Generation() int64 + Stop() error +} + +// positionStore is what a forwarder needs from offset.ConsumerGroupOffsetStorage. +type positionStore interface { + LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*offset.ConsumerGroupPosition, error) + SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *offset.ConsumerGroupPosition) error + ListConsumerGroupPositions(ctx context.Context, t topic.Topic, consumerGroup string, skip func(dir string) bool) (map[string]*offset.ConsumerGroupPosition, error) +} + +// Forwarder delivers each target's topic to the target's destination. Every +// gateway runs one, and a lock per target elects the gateway that forwards +// it, so targets spread across gateways. A topic target has no forwarder. +type Forwarder struct { + brokers func() []string + grpcDialOption grpc.DialOption + positions positionStore + owner string + startLock func(key string) forwarderLock + newDestination func(t *Target) destination + + lockCheckInterval time.Duration + idleWait time.Duration + minBackoff time.Duration + maxBackoff time.Duration + reclaimWait time.Duration + partitionRefresh time.Duration + // loopEnded, when set, runs as a forwarding loop ends, after it is marked ended + loopEnded func(err error) + + mu sync.Mutex + targets map[string]*targetForwarder + // stopping are removed targets not done releasing their locks, which Close waits for + stopping map[*targetForwarder]bool + closed bool +} + +// NewForwarder returns a forwarder that reads topics through the brokers listed +// by brokers, stores offsets in positions, and elects itself per target through +// lockClient as owner, which must be unique to this gateway process. +func NewForwarder(brokers func() []string, grpcDialOption grpc.DialOption, positions positionStore, lockClient *cluster.LockClient, owner string) *Forwarder { + return &Forwarder{ + brokers: brokers, + grpcDialOption: grpcDialOption, + positions: positions, + owner: owner, + startLock: func(key string) forwarderLock { + return lockClient.StartLongLivedLock(key, owner, func(newOwner string) { + glog.V(1).Infof("notification forwarder lock %s is held by %s", key, newOwner) + }, lock_manager.LiveLockTTL) + }, + newDestination: newDestination, + lockCheckInterval: forwardLockCheckInterval, + idleWait: forwardIdleWait, + minBackoff: forwardMinBackoff, + maxBackoff: forwardMaxBackoff, + reclaimWait: forwardReclaimWait, + partitionRefresh: forwardPartitionRefresh, + targets: map[string]*targetForwarder{}, + stopping: map[*targetForwarder]bool{}, + } +} + +// newDestination is the destination of a target type that has a forwarder, or nil. +func newDestination(t *Target) destination { + if t.Type == TargetTypeWebhook { + return newWebhook(t) + } + return nil +} + +// Sync runs a forwarder for every enabled target in reg that has a destination, +// stops the others, and hands a changed target's settings to its forwarder. +func (f *Forwarder) Sync(reg *Registry) { + f.mu.Lock() + defer f.mu.Unlock() + if f.closed { + return + } + want := map[string]*Target{} + for _, name := range reg.Names() { + if t, ok := reg.Lookup(name); ok && t.Enabled && t.Type != TargetTypeTopic { + want[name] = t + } + } + for name, tf := range f.targets { + if t := want[name]; t == nil || t.Type != tf.settings().target.Type { + tf.cancel() + delete(f.targets, name) + f.stopping[tf] = true + go func() { + <-tf.done + f.mu.Lock() + delete(f.stopping, tf) + f.mu.Unlock() + }() + } + } + for name, t := range want { + tf := f.targets[name] + if tf != nil && reflect.DeepEqual(tf.settings().target, t) { + continue + } + dest := f.newDestination(t) + if dest == nil { + glog.V(1).Infof("notification target %s: type %s has no forwarder yet", name, t.Type) + continue + } + if tf != nil { + tf.current.Store(&forwardSettings{target: t, dest: dest}) + continue + } + f.targets[name] = f.start(t, dest) + } +} + +// Close stops every forwarder and waits for each to release its lock. +func (f *Forwarder) Close() { + f.mu.Lock() + f.closed = true + stopping := make([]*targetForwarder, 0, len(f.targets)) + for name, tf := range f.targets { + tf.cancel() + stopping = append(stopping, tf) + delete(f.targets, name) + } + for tf := range f.stopping { + stopping = append(stopping, tf) + } + f.mu.Unlock() + for _, tf := range stopping { + <-tf.done + } +} + +type forwardSettings struct { + target *Target + dest destination +} + +type targetForwarder struct { + f *Forwarder + name string + topic topic.Topic + current atomic.Pointer[forwardSettings] + cancel context.CancelFunc + done chan struct{} + + lagMu sync.Mutex + lags map[topic.Partition]int64 +} + +func (f *Forwarder) start(t *Target, dest destination) *targetForwarder { + ctx, cancel := context.WithCancel(context.Background()) + tf := &targetForwarder{ + f: f, + name: t.Name, + topic: topic.NewTopic(TopicNamespace, t.TopicName()), + cancel: cancel, + done: make(chan struct{}), + lags: map[topic.Partition]int64{}, + } + tf.current.Store(&forwardSettings{target: t, dest: dest}) + go tf.run(ctx) + return tf +} + +func (tf *targetForwarder) settings() *forwardSettings { + return tf.current.Load() +} + +// run forwards the target while this gateway holds its lock. A forwarder whose +// offset save was refused stops, and leads again only once it has held the +// lock through reclaimWait. +func (tf *targetForwarder) run(ctx context.Context) { + defer close(tf.done) + lock := tf.f.startLock(ForwarderLockPrefix + tf.name) + defer func() { + if err := lock.Stop(); err != nil { + glog.V(1).Infof("notification target %s: release forwarder lock: %v", tf.name, err) + } + }() + + var ( + stopLead context.CancelFunc + ended chan error + leadGeneration int64 + holdOffUntil time.Time + reclaim bool + ) + endLead := func() { + if stopLead == nil { + return + } + stopLead() + if ended != nil { + <-ended + } + stopLead, ended = nil, nil + tf.clearLag() + } + defer endLead() + + ticker := time.NewTicker(tf.f.lockCheckInterval) + defer ticker.Stop() + for { + held := lock.IsLocked() + if stopLead != nil && (!held || lock.Generation() != leadGeneration) { + glog.V(0).Infof("notification target %s: forwarder lock lost at generation %d", tf.name, leadGeneration) + endLead() + } + if held && stopLead == nil && !time.Now().Before(holdOffUntil) { + leadCtx, cancel := context.WithCancel(ctx) + stopLead, ended, leadGeneration = cancel, make(chan error, 1), lock.Generation() + glog.V(0).Infof("notification target %s: forwarding from this gateway at generation %d", tf.name, leadGeneration) + go func(ended chan<- error, generation int64, reclaim bool) { + ended <- tf.lead(leadCtx, lock, generation, reclaim) + }(ended, leadGeneration, reclaim) + reclaim = false + } + select { + case <-ctx.Done(): + return + case err := <-ended: + ended = nil + endLead() + if errors.Is(err, errDeposed) { + glog.Warningf("notification target %s: stopped forwarding: %v", tf.name, err) + holdOffUntil, reclaim = time.Now().Add(tf.f.reclaimWait), true + } + case <-ticker.C: + } + } +} + +// forwardPartition is a partition of the target's topic and its leader, which +// holds the partition's unflushed messages. +type forwardPartition struct { + partition topic.Partition + leader string + // retired is set for a sealed range of an earlier generation, read from its + // files by any broker; its loop ends once it reaches highWaterMark + retired atomic.Bool + highWaterMark atomic.Int64 + // removed is set once the topic lists the partition neither as assigned nor + // as retired, as while a drained range is not sealed yet; its loop ends after + // the batch in hand and starts again once the range is offered as retired + removed atomic.Bool + ended atomic.Bool +} + +// lead forwards every partition until ctx ends or one finds itself deposed. A +// reclaim lead may take over partitions whose stored generation is not older +// than its own: the lock server's counter restarted or moved to another filer. +// +// A key's records in a retired range precede its records in the ranges that +// replaced it, so retired ranges are forwarded first, one generation at a time, +// oldest first, and the current ranges only once none is left. +func (tf *targetForwarder) lead(ctx context.Context, lock forwarderLock, generation int64, reclaim bool) error { + var current, retired []*forwardPartition + b := tf.backoff() + for { + var err error + if current, retired, err = tf.lookUp(ctx); err == nil { + break + } + if b.failed() { + glog.Warningf("notification target %s: look up topic %s: %v", tf.name, tf.topic, err) + } + if !b.wait(ctx) { + return nil + } + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + settled := map[string]bool{} + var unsettled []string + // a failed check says nothing about the old ranges, so it holds every range not yet running + checked, checks := false, tf.backoff() + var recheck <-chan time.Time + check := func() { + held, err := tf.unsettledRanges(ctx, current, retired, settled) + if err != nil { + if checks.failed() { + glog.Warningf("notification target %s: holding its current partitions, list stored offsets: %v", tf.name, err) + } + checked, recheck = false, time.After(checks.delay()) + return + } + unsettled, checked, recheck = held, true, nil + checks.reset() + } + check() + var heldLogged time.Time + results := make(chan error) + // keyed by directory: the topic lists a retired range at the resolution of + // its generation's directory name, while its assignment carried nanoseconds + loops := map[string]*forwardPartition{} + dir := func(p *forwardPartition) string { return topic.PartitionDir(tf.topic, p.partition) } + running := 0 + start := func(p *forwardPartition) { + loops[dir(p)] = p + running++ + go func() { + err := tf.forward(ctx, lock, p, generation, reclaim) + tf.setLag(p.partition, 0) + if err != nil { + // stopped before it is marked ended, so no adopt takes a failed range as delivered + cancel() + } + p.ended.Store(true) + if tf.f.loopEnded != nil { + tf.f.loopEnded(err) + } + results <- err + }() + } + adopt := func() { + for key, p := range loops { + // a removed loop is replaced only once it ended, so one range never has two + if p.removed.Load() && p.ended.Load() { + delete(loops, key) + } + } + listed := map[string]bool{} + for _, r := range retired { + listed[dir(r)] = true + if p := loops[dir(r)]; p != nil { + // a range this lead forwarded as current, retired by a repartition since + p.highWaterMark.Store(r.highWaterMark.Load()) + p.retired.Store(true) + } + } + // the oldest generation with a retired range not yet delivered + oldest := int64(math.MaxInt64) + for _, r := range retired { + if p := loops[dir(r)]; p == nil || !p.ended.Load() { + oldest = min(oldest, r.partition.UnixTimeNs) + } + } + for _, p := range loops { + if p.retired.Load() && !p.ended.Load() { + oldest = min(oldest, p.partition.UnixTimeNs) + } + } + // an unsealed range holds back the retired generations after its own too + for _, d := range unsettled { + if p, ok := partitionOfDir(d, 0); ok { + oldest = min(oldest, p.UnixTimeNs) + } + } + for _, r := range retired { + if loops[dir(r)] == nil && checked && r.partition.UnixTimeNs == oldest { + glog.V(0).Infof("notification target %s: forwarding retired partition %v up to offset %d", tf.name, r.partition, r.highWaterMark.Load()) + start(r) + } + } + if len(unsettled) > 0 && time.Since(heldLogged) >= forwardHoldLogInterval { + heldLogged = time.Now() + glog.Warningf("notification target %s: holding its new partitions until %v, drained but not sealed yet, are offered as retired", tf.name, unsettled) + } + for _, c := range current { + listed[dir(c)] = true + if loops[dir(c)] == nil && oldest == math.MaxInt64 && checked && len(unsettled) == 0 { + start(c) + } + } + for key, p := range loops { + if listed[key] || p.removed.Load() { + continue + } + if p.ended.Load() { + delete(loops, key) + continue + } + if tf.lagOf(p.partition) > 0 { + glog.Warningf("notification target %s: topic %s lists partition %v neither as assigned nor as retired; pausing it until it is offered again", tf.name, tf.topic, p.partition) + } + p.removed.Store(true) + } + } + // ranges held back have no loop to report their lag + heldLag := func() { + var held []*forwardPartition + for _, p := range append(append([]*forwardPartition(nil), current...), retired...) { + if loops[dir(p)] == nil { + held = append(held, p) + } + } + var live []topic.Partition + for _, p := range loops { + if !p.ended.Load() { + live = append(live, p.partition) + } + } + tf.recordHeldLag(ctx, held, live) + } + adopt() + heldLag() + ticker := time.NewTicker(tf.f.partitionRefresh) + defer ticker.Stop() + var deposed error + done := ctx.Done() + // held, the lead stays to look again even with no loop running + for running > 0 || ((!checked || len(unsettled) > 0) && ctx.Err() == nil) { + refreshed := false + select { + case err := <-results: + running-- + if err != nil && deposed == nil { + deposed = err + } + case <-ticker.C: + if found, gone, err := tf.lookUp(ctx); err == nil { + current, retired = found, gone + check() + } + refreshed = true + case <-recheck: + check() + case <-done: + // running loops end on their own and report + done = nil + } + if ctx.Err() == nil { + adopt() + if refreshed { + heldLag() + } + } + } + return deposed +} + +// forward delivers one partition in offset order, one batch at a time, from +// its stored offset, and stores the next offset after each delivered batch. It +// returns errDeposed when a save is refused, and nil when ctx ends. +func (tf *targetForwarder) forward(ctx context.Context, lock forwarderLock, p *forwardPartition, generation int64, reclaim bool) error { + next, fence, stored, err := tf.claim(ctx, p.partition, generation, reclaim) + if err != nil || ctx.Err() != nil { + return err + } + b := tf.backoff() + var stallWarned time.Time + for ctx.Err() == nil && lock.IsLocked() && !p.removed.Load() { + if p.retired.Load() && next >= p.highWaterMark.Load() { + glog.V(0).Infof("notification target %s: retired partition %v delivered up to offset %d", tf.name, p.partition, next) + return nil + } + resp, err := tf.fetch(ctx, p, next) + if err == nil && resp.ErrorCode == broker.BrokerErrorOffsetOutOfRange && resp.LogStartOffset > next { + if stored { + stats.S3NotificationRetentionGapCounter.WithLabelValues(tf.name).Add(float64(resp.LogStartOffset - next)) + glog.Warningf("notification target %s partition %v: retention removed offsets %d to %d before they were delivered", + tf.name, p.partition, next, resp.LogStartOffset-1) + } + next, stored = resp.LogStartOffset, true + if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { + return err + } + continue + } + if err == nil && resp.ErrorCode != 0 { + err = fmt.Errorf("broker error %d: %s", resp.ErrorCode, resp.Error) + } + if err != nil { + if b.failed() { + glog.Warningf("notification target %s partition %v: fetch at offset %d from %s: %v", tf.name, p.partition, next, p.leader, err) + } + if !b.wait(ctx) { + return nil + } + tf.refreshLeader(ctx, p) + continue + } + b.reset() + if !stored { + // read from now, so a later lead counts what retention removes past it + if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { + return err + } + stored = true + } + records, offsets, advance := tf.fetchedBatch(resp, next) + tf.setLag(p.partition, resp.HighWaterMark-next) + if len(records) == 0 { + if advance > next { + next = advance + if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { + return err + } + continue + } + if next < resp.HighWaterMark && time.Since(stallWarned) >= forwardStallWarnInterval { + // the broker has records past next but returns none; waiting keeps them, skipping would lose them + stallWarned = time.Now() + glog.Warningf("notification target %s: topic %s partition %v returns no records at offset %d below its high-water mark %d", + tf.name, tf.topic, p.partition, next, resp.HighWaterMark) + } + // caught up; a short fetch at a segment boundary still advances above + select { + case <-ctx.Done(): + case <-time.After(tf.f.idleWait): + } + continue + } + if !tf.deliver(ctx, lock, records, offsets) { + return nil + } + next = advance + if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { + return err + } + tf.setLag(p.partition, resp.HighWaterMark-next) + } + return nil +} + +// fetchedBatch decodes the records of resp at or after next, in offset order, +// with their offsets, and returns the offset after them. A message the log +// could not place has no offset and is skipped; one that does not decode +// could never be delivered. +func (tf *targetForwarder) fetchedBatch(resp *mq_pb.FetchMessageResponse, next int64) (records []*schema_pb.RecordValue, offsets []int64, advance int64) { + advance = max(resp.NextOffset, next) + for i, m := range resp.Messages { + at := next + int64(i) // brokers that predate DataMessage.Offset leave it unset + if m.Offset != nil { + at = *m.Offset + } + if at < next { + continue + } + advance = max(advance, at+1) + record := &schema_pb.RecordValue{} + if err := proto.Unmarshal(m.Value, record); err != nil { + tf.skip(at, "undecodable", err) + continue + } + records = append(records, record) + offsets = append(offsets, at) + } + return records, offsets, advance +} + +// skip counts a record that can never be delivered; it is seen once, as the +// offset moves past it. +func (tf *targetForwarder) skip(at int64, reason string, err error) { + stats.S3NotificationSkippedCounter.WithLabelValues(tf.name, reason).Inc() + glog.Warningf("notification target %s: skipping %s record at offset %d: %v", tf.name, reason, at, err) +} + +// claim reads the partition's stored offset and stores it back under this +// forwarder's fence, the lock generation, so a forwarder of an older +// generation can no longer store. A stored generation at or above ours, from +// another forwarder, means this lock was lost unless this lead is a reclaim. +func (tf *targetForwarder) claim(ctx context.Context, partition topic.Partition, generation int64, reclaim bool) (next, fence int64, stored bool, err error) { + b := tf.backoff() + for { + loadCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + position, err := tf.f.positions.LoadConsumerGroupPosition(loadCtx, tf.topic, partition, ForwarderGroup) + cancel() + if err == nil || errors.Is(err, filer_pb.ErrNotFound) { + next, fence, stored = 0, generation, err == nil && position.Metadata != claimedPosition + if err == nil { + next = position.Value + if position.Generation > generation || (position.Generation == generation && position.Writer != tf.f.owner) { + if !reclaim { + return 0, 0, false, fmt.Errorf("partition %v stored at generation %d by %s, ours is %d: %w", + partition, position.Generation, position.Writer, generation, errDeposed) + } + fence = position.Generation + 1 + } + } + next, stored, err = tf.save(ctx, partition, next, fence, stored) + if err == nil || ctx.Err() != nil { + return next, fence, stored, err + } + if !reclaim { + return 0, 0, false, err + } + // another reclaim got there first; read its generation and go above it + continue + } + if b.failed() { + glog.Warningf("notification target %s partition %v: load offset: %v", tf.name, partition, err) + } + if !b.wait(ctx) { + return 0, 0, false, nil + } + } +} + +// save stores next under fence, retrying until it is stored, refused, or ctx +// ends. A position not established, as a claim's before anything was read +// from it, is marked so, and counts no retention gap later. It returns the +// offset stored and whether it is established: a save taking over from an +// older fence keeps what that fence committed last. +func (tf *targetForwarder) save(ctx context.Context, partition topic.Partition, next, fence int64, established bool) (int64, bool, error) { + b := tf.backoff() + for { + saveCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + position := &offset.ConsumerGroupPosition{ + Type: "offset", + Value: next, + OffsetType: schema_pb.OffsetType_EXACT_OFFSET.String(), + CommittedAt: time.Now().UnixMilli(), + Generation: fence, + Writer: tf.f.owner, + } + if !established { + position.Metadata = claimedPosition + } + err := tf.f.positions.SaveConsumerGroupPosition(saveCtx, tf.topic, partition, ForwarderGroup, position) + cancel() + if err == nil { + return position.Value, position.Metadata != claimedPosition, nil + } + if errors.Is(err, offset.ErrStaleGeneration) { + return next, established, fmt.Errorf("%v: %w", err, errDeposed) + } + // a takeover whose reply was lost may have stored what it kept; once the entry + // is ours a retry keeps nothing, so it retries with that + next, established = position.Value, position.Metadata != claimedPosition + if b.failed() { + glog.Warningf("notification target %s partition %v: store offset %d: %v", tf.name, partition, next, err) + } + if !b.wait(ctx) { + return next, established, nil + } + } +} + +// deliver sends records, found at offsets, until the destination takes them, +// retrying every failed send, a refusal included: a 401 is an operator fix +// away from succeeding. A record that cannot be rendered is skipped instead. +// It reports false when ctx ends or the lock is lost first. +func (tf *targetForwarder) deliver(ctx context.Context, lock forwarderLock, records []*schema_pb.RecordValue, offsets []int64) bool { + b := tf.backoff() + for len(records) > 0 { + // the lock may have gone while the batch was fetched; losing it mid-send cancels ctx + if !lock.IsLocked() { + return false + } + err := tf.settings().dest.Send(ctx, records) + var unrenderable *unrenderableError + if errors.As(err, &unrenderable) { + keptRecords, keptOffsets := records[:0:0], offsets[:0:0] + for i := range records { + if slices.Contains(unrenderable.indexes, i) { + tf.skip(offsets[i], "unrenderable", unrenderable.err) + continue + } + keptRecords, keptOffsets = append(keptRecords, records[i]), append(keptOffsets, offsets[i]) + } + records, offsets = keptRecords, keptOffsets + continue + } + if err == nil { + stats.S3NotificationDeliveredCounter.WithLabelValues(tf.name).Add(float64(len(records))) + return true + } + if ctx.Err() != nil { + return false + } + stats.S3NotificationSendRetriesCounter.WithLabelValues(tf.name).Inc() + if b.failed() { + glog.Warningf("notification target %s: send %d records: %v", tf.name, len(records), err) + } + if !b.wait(ctx) { + return false + } + } + return true +} + +func (tf *targetForwarder) fetch(ctx context.Context, p *forwardPartition, next int64) (resp *mq_pb.FetchMessageResponse, err error) { + addresses := []string{p.leader} + if p.retired.Load() { + // any broker reads a retired range from its files + addresses = append(addresses, tf.f.brokers()...) + } + err = errors.New("partition has no leader") + var refused *mq_pb.FetchMessageResponse + tried := map[string]bool{} + for _, address := range addresses { + if address == "" || tried[address] { + continue + } + tried[address] = true + fetchCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + err = pb.WithBrokerGrpcClient(false, address, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error { + resp, err = client.FetchMessage(fetchCtx, &mq_pb.FetchMessageRequest{ + Topic: tf.topic.ToPbTopic(), + Partition: p.partition.ToPbPartition(), + StartOffset: next, + MaxMessages: forwardBatchMessages, + MaxBytes: forwardBatchBytes, + ConsumerGroup: ForwarderGroup, + ConsumerId: tf.f.owner, + }) + return err + }) + cancel() + if err == nil && p.retired.Load() && resp.ErrorCode != 0 && resp.ErrorCode != broker.BrokerErrorOffsetOutOfRange { + // another broker may read the files this one cannot + refused = resp + continue + } + if err == nil { + return resp, nil + } + } + if refused != nil { + return refused, nil + } + return nil, err +} + +// lookUp asks the brokers for the topic's partitions and their leaders, and +// for the retired ranges that still hold data. +func (tf *targetForwarder) lookUp(ctx context.Context) (current, retired []*forwardPartition, err error) { + brokers := tf.f.brokers() + if len(brokers) == 0 { + return nil, nil, errors.New("no message queue broker found") + } + var lastErr error + for _, address := range brokers { + var resp *mq_pb.LookupTopicBrokersResponse + lastErr = pb.WithBrokerGrpcClient(false, address, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) (err error) { + lookupCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + defer cancel() + resp, err = client.LookupTopicBrokers(lookupCtx, &mq_pb.LookupTopicBrokersRequest{Topic: tf.topic.ToPbTopic(), IncludeRetired: true}) + return err + }) + if lastErr != nil { + lastErr = fmt.Errorf("%s: %w", address, lastErr) + continue + } + current = nil + for _, assignment := range resp.BrokerPartitionAssignments { + if assignment.Partition != nil { + current = append(current, &forwardPartition{ + partition: topic.FromPbPartition(assignment.Partition), + leader: assignment.LeaderBroker, + }) + } + } + if len(current) == 0 { + lastErr = fmt.Errorf("%s: topic has no partitions", address) + continue + } + retired = nil + for _, r := range resp.RetiredPartitions { + if r.Partition != nil { + p := &forwardPartition{partition: topic.FromPbPartition(r.Partition)} + p.retired.Store(true) + p.highWaterMark.Store(r.HighWaterMark) + retired = append(retired, p) + } + } + return current, retired, nil + } + return nil, nil, lastErr +} + +// unsettledRanges lists the partition directories the topic offers neither as +// assigned nor as retired that may still hold records past their stored offset, +// or past 0 for one with none stored: a range a repartition drained but has not +// sealed yet. Its records precede the new ranges' records of the same keys, so +// while one is unsettled the new ranges wait. A range that answers a read with +// nothing left past that offset, sealed and empty or already delivered, is settled. +// A check that fails partway still keeps the ranges it found settled, so the +// next one goes on from there. +func (tf *targetForwarder) unsettledRanges(ctx context.Context, current, retired []*forwardPartition, settled map[string]bool) ([]string, error) { + var ringSize int32 + offered := map[string]bool{} + for _, p := range append(append([]*forwardPartition(nil), current...), retired...) { + offered[topic.PartitionDir(tf.topic, p.partition)] = true + ringSize = p.partition.RingSize + } + listCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + defer cancel() + // only the ranges not offered and not yet settled have their positions read + stored, listErr := tf.f.positions.ListConsumerGroupPositions(listCtx, tf.topic, ForwarderGroup, func(dir string) bool { + return offered[dir] || settled[dir] + }) + var unsettled []string + for dir, position := range stored { + partition, ok := partitionOfDir(dir, ringSize) + if !ok { + continue + } + var next int64 + if position != nil { + next = position.Value + } + probe := &forwardPartition{partition: partition} + probe.retired.Store(true) + resp, err := tf.fetch(ctx, probe, next) + if err == nil && (resp.ErrorCode == 0 || resp.ErrorCode == broker.BrokerErrorOffsetOutOfRange) && resp.HighWaterMark <= max(next, resp.LogStartOffset) { + // sealed, so it stays settled + settled[dir] = true + continue + } + unsettled = append(unsettled, dir) + } + if listErr != nil { + // the ranges not read yet may be unsettled + return nil, listErr + } + slices.Sort(unsettled) + return unsettled, nil +} + +// partitionOfDir is the partition a directory ...// names. +func partitionOfDir(dir string, ringSize int32) (topic.Partition, bool) { + parts := strings.Split(dir, "/") + if len(parts) < 2 { + return topic.Partition{}, false + } + version, err := topic.ParseTopicVersion(parts[len(parts)-2]) + start, stop := topic.ParsePartitionBoundary(parts[len(parts)-1]) + if err != nil || start == stop { + return topic.Partition{}, false + } + return topic.Partition{RingSize: ringSize, RangeStart: start, RangeStop: stop, UnixTimeNs: version.UnixNano()}, true +} + +// refreshLeader looks the partition's leader up again after a failed fetch. +func (tf *targetForwarder) refreshLeader(ctx context.Context, p *forwardPartition) { + partitions, _, err := tf.lookUp(ctx) + if err != nil { + return + } + for _, found := range partitions { + if found.partition.Equals(p.partition) { + p.leader = found.leader + return + } + } +} + +// setLag records how far a partition's committed offset trails its high-water +// mark; the target's gauge is the sum over its partitions. +func (tf *targetForwarder) setLag(partition topic.Partition, lag int64) { + tf.lagMu.Lock() + defer tf.lagMu.Unlock() + tf.lags[partition] = max(lag, 0) + tf.reportLagLocked() +} + +func (tf *targetForwarder) reportLagLocked() { + var total int64 + for _, l := range tf.lags { + total += l + } + stats.S3NotificationLagGauge.WithLabelValues(tf.name).Set(float64(total)) +} + +// recordHeldLag sets the lag of the ranges held back behind an older +// generation, from their stored offset to their high-water mark, and drops +// that of ranges neither held nor running any more. +func (tf *targetForwarder) recordHeldLag(ctx context.Context, held []*forwardPartition, running []topic.Partition) { + lags := map[topic.Partition]int64{} + keep := map[topic.Partition]bool{} + for _, p := range running { + keep[p] = true + } + for _, p := range held { + keep[p.partition] = true + loadCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + position, err := tf.f.positions.LoadConsumerGroupPosition(loadCtx, tf.topic, p.partition, ForwarderGroup) + cancel() + var next int64 + if err == nil { + next = position.Value + } else if !errors.Is(err, filer_pb.ErrNotFound) { + continue + } + hwm := p.highWaterMark.Load() + if !p.retired.Load() { + err = pb.WithBrokerGrpcClient(false, p.leader, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error { + infoCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) + defer cancel() + resp, err := client.GetPartitionRangeInfo(infoCtx, &mq_pb.GetPartitionRangeInfoRequest{Topic: tf.topic.ToPbTopic(), Partition: p.partition.ToPbPartition()}) + if err == nil && resp.Error != "" { + err = errors.New(resp.Error) + } + hwm = resp.GetOffsetRange().GetHighWaterMark() + return err + }) + if err != nil { + continue + } + } + lags[p.partition] = max(hwm-next, 0) + } + tf.lagMu.Lock() + defer tf.lagMu.Unlock() + for partition := range tf.lags { + if !keep[partition] { + delete(tf.lags, partition) + } + } + maps.Copy(tf.lags, lags) + tf.reportLagLocked() +} + +func (tf *targetForwarder) lagOf(partition topic.Partition) int64 { + tf.lagMu.Lock() + defer tf.lagMu.Unlock() + return tf.lags[partition] +} + +// clearLag drops the gauge when this gateway stops forwarding the target, so +// only the forwarding gateway reports it. +func (tf *targetForwarder) clearLag() { + tf.lagMu.Lock() + defer tf.lagMu.Unlock() + clear(tf.lags) + stats.S3NotificationLagGauge.DeleteLabelValues(tf.name) +} + +func (tf *targetForwarder) backoff() *backoff { + return &backoff{min: tf.f.minBackoff, max: tf.f.maxBackoff} +} + +// backoff doubles a wait from min up to max. +type backoff struct { + min, max, next time.Duration + failures int +} + +// failed counts a failure and reports whether it is worth logging: the first, +// and each one once the wait is capped. +func (b *backoff) failed() bool { + b.failures++ + return b.failures == 1 || b.next >= b.max +} + +func (b *backoff) reset() { + b.next, b.failures = 0, 0 +} + +// delay doubles the wait and returns it. +func (b *backoff) delay() time.Duration { + b.next = min(max(2*b.next, b.min), b.max) + return b.next +} + +// wait sleeps the current wait and doubles it; false means ctx ended first. +func (b *backoff) wait(ctx context.Context) bool { + select { + case <-ctx.Done(): + return false + case <-time.After(b.delay()): + return true + } +} diff --git a/weed/s3api/s3notification/forwarder_test.go b/weed/s3api/s3notification/forwarder_test.go new file mode 100644 index 0000000000..b96d65230b --- /dev/null +++ b/weed/s3api/s3notification/forwarder_test.go @@ -0,0 +1,1361 @@ +package s3notification + +import ( + "context" + "fmt" + "net" + "net/http" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/seaweedfs/seaweedfs/weed/filer_client" + "github.com/seaweedfs/seaweedfs/weed/mq/broker" + "github.com/seaweedfs/seaweedfs/weed/mq/offset" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" + "github.com/seaweedfs/seaweedfs/weed/stats" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// fakeLog is one partition's messages; offsets below start were removed by retention. +type fakeLog struct { + start int64 + values [][]byte +} + +// fakeLogKey is a partition by its generation and range start. +type fakeLogKey struct { + version int64 + rangeStart int32 +} + +// atSecond is a generation at the resolution of its directory name, at which +// the broker lists retired ranges and the filer keys stored positions. +func atSecond(version int64) int64 { + return version - version%int64(time.Second) +} + +func (b *fakeBroker) appendLocked(key fakeLogKey, value []byte) { + if b.logs == nil { + b.logs = map[fakeLogKey]*fakeLog{} + } + log := b.logs[key] + if log == nil { + log = &fakeLog{} + b.logs[key] = log + } + log.values = append(log.values, value) +} + +// appendRecords adds one record per name to the first partition of the current generation. +func (b *fakeBroker) appendRecords(names ...string) { + b.mu.Lock() + defer b.mu.Unlock() + for _, name := range names { + value, err := proto.Marshal(namedRecord(name)) + if err != nil { + panic(err) + } + b.appendLocked(fakeLogKey{b.version, 0}, value) + } +} + +func (b *fakeBroker) purgeBefore(rangeStart int32, start int64) { + b.mu.Lock() + defer b.mu.Unlock() + b.logs[fakeLogKey{b.version, rangeStart}].start = start +} + +// repartition replaces the current generation, which is retired and sealed, +// after adding last records to its first partition in the same step. +func (b *fakeBroker) repartition(version int64, count int32, last ...string) { + b.mu.Lock() + defer b.mu.Unlock() + for _, name := range last { + value, err := proto.Marshal(namedRecord(name)) + if err != nil { + panic(err) + } + b.appendLocked(fakeLogKey{b.version, 0}, value) + } + if b.retired == nil { + b.retired = map[int64]int32{} + } + b.retired[b.version] = int32(TopicPartitionCount) + if b.partitionCount > 0 { + b.retired[b.version] = b.partitionCount + } + b.version, b.partitionCount = version, count +} + +func (b *fakeBroker) setSealed(version int64, sealed bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.unsealed == nil { + b.unsealed = map[int64]bool{} + } + b.unsealed[version] = !sealed +} + +// appendTo adds one record per name to the partition at key. +func (b *fakeBroker) appendTo(key fakeLogKey, names ...string) { + b.mu.Lock() + defer b.mu.Unlock() + for _, name := range names { + value, err := proto.Marshal(namedRecord(name)) + if err != nil { + panic(err) + } + b.appendLocked(key, value) + } +} + +func (b *fakeBroker) fetchCount(key fakeLogKey) int { + b.mu.Lock() + defer b.mu.Unlock() + return b.fetches[key] +} + +// GetPartitionRangeInfo answers for the current generation's ranges, as their leader does. +func (b *fakeBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_pb.GetPartitionRangeInfoRequest) (*mq_pb.GetPartitionRangeInfoResponse, error) { + b.mu.Lock() + defer b.mu.Unlock() + for _, p := range b.assignedLocked() { + if atSecond(p.UnixTimeNs) == atSecond(req.Partition.UnixTimeNs) && p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop { + log := b.logs[fakeLogKey{p.UnixTimeNs, p.RangeStart}] + if log == nil { + log = &fakeLog{} + } + return &mq_pb.GetPartitionRangeInfoResponse{OffsetRange: &mq_pb.OffsetRangeInfo{EarliestOffset: log.start, HighWaterMark: int64(len(log.values))}}, nil + } + } + return &mq_pb.GetPartitionRangeInfoResponse{Error: "partition not found"}, nil +} + +func (b *fakeBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchMessageRequest) (*mq_pb.FetchMessageResponse, error) { + b.mu.Lock() + hook := b.onFetch + b.mu.Unlock() + if hook != nil { + hook() + } + b.mu.Lock() + defer b.mu.Unlock() + if b.failFetches > 0 { + b.failFetches-- + return nil, status.Error(codes.Unavailable, "broker restarting") + } + if b.fetchErrorCode != 0 { + return &mq_pb.FetchMessageResponse{Error: "storage unavailable", ErrorCode: b.fetchErrorCode, NextOffset: req.StartOffset}, nil + } + key := fakeLogKey{req.Partition.UnixTimeNs, req.Partition.RangeStart} + if b.fetches == nil { + b.fetches = map[fakeLogKey]int{} + } + b.fetches[key]++ + // like the real broker, serve a retired range of an earlier generation from + // its files, and otherwise only an assigned range of the generation named + assigned := false + for version, count := range b.retired { + if b.unsealed[version] || atSecond(version) != atSecond(req.Partition.UnixTimeNs) || atSecond(req.Partition.UnixTimeNs) == atSecond(b.version) { + continue + } + for _, p := range generationPartitions(version, count) { + if p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop { + assigned, key = true, fakeLogKey{version, p.RangeStart} + } + } + } + for _, p := range b.assignedLocked() { + sameGeneration := req.Partition.UnixTimeNs == 0 || atSecond(p.UnixTimeNs) == atSecond(req.Partition.UnixTimeNs) + if !assigned && sameGeneration && p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop { + assigned, key = true, fakeLogKey{p.UnixTimeNs, p.RangeStart} + } + } + if !assigned { + return &mq_pb.FetchMessageResponse{Error: "partition not found", ErrorCode: 1, NextOffset: req.StartOffset}, nil + } + log := b.logs[key] + if log == nil { + log = &fakeLog{} + } + hwm := int64(len(log.values)) + if req.StartOffset < log.start { + return &mq_pb.FetchMessageResponse{ + HighWaterMark: hwm, + LogStartOffset: log.start, + NextOffset: req.StartOffset, + Error: "offset out of range", + ErrorCode: broker.BrokerErrorOffsetOutOfRange, + }, nil + } + end := min(hwm, req.StartOffset+int64(req.MaxMessages)) + if b.holding && req.StartOffset == b.holdAt { + end = req.StartOffset + } + if b.segment > 0 { + end = min(end, (req.StartOffset/b.segment+1)*b.segment) + } + resp := &mq_pb.FetchMessageResponse{HighWaterMark: hwm, LogStartOffset: log.start, NextOffset: max(end, req.StartOffset)} + for at := req.StartOffset; at < end; at++ { + resp.Messages = append(resp.Messages, &mq_pb.DataMessage{Value: log.values[at], Offset: proto.Int64(at)}) + } + resp.EndOfPartition = resp.NextOffset >= hwm + return resp, nil +} + +// memoryPositions stores positions with the same fencing rule as the filer storage. +type memoryPositions struct { + mu sync.Mutex + positions map[fakeLogKey]offset.ConsumerGroupPosition + partitions map[fakeLogKey]topic.Partition + refused int + listed []string + // failLists is how many more listings fail + failLists int + // afterLoad runs once a load returns, as another writer landing before the next save + afterLoad func() + // lostSaves is how many more saves are applied but answered with an error, as a lost reply + lostSaves int + // loadLimit, when set, is how many positions a listing reads before it runs out of time + loadLimit int +} + +func newMemoryPositions() *memoryPositions { + return &memoryPositions{positions: map[fakeLogKey]offset.ConsumerGroupPosition{}, partitions: map[fakeLogKey]topic.Partition{}} +} + +func (m *memoryPositions) LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, group string) (*offset.ConsumerGroupPosition, error) { + m.mu.Lock() + hook := m.afterLoad + m.mu.Unlock() + if hook != nil { + defer hook() + } + m.mu.Lock() + defer m.mu.Unlock() + position, ok := m.positions[fakeLogKey{atSecond(p.UnixTimeNs), p.RangeStart}] + if !ok { + return nil, filer_pb.ErrNotFound + } + return &position, nil +} + +func (m *memoryPositions) SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, group string, position *offset.ConsumerGroupPosition) error { + m.mu.Lock() + defer m.mu.Unlock() + if group != ForwarderGroup || t.Namespace != TopicNamespace { + return fmt.Errorf("saved %s under %s", group, t) + } + key := fakeLogKey{atSecond(p.UnixTimeNs), p.RangeStart} + m.partitions[key] = p + if stored, ok := m.positions[key]; ok && position.Generation != 0 && + (stored.Generation > position.Generation || (stored.Generation == position.Generation && stored.Writer != position.Writer)) { + m.refused++ + return fmt.Errorf("refused: %w", offset.ErrStaleGeneration) + } + if stored, ok := m.positions[key]; ok && position.Generation != 0 && stored.Generation < position.Generation { + // a takeover keeps the offset the older generation committed last + position.Value, position.Metadata = stored.Value, stored.Metadata + } + m.positions[key] = *position + if m.lostSaves > 0 { + m.lostSaves-- + return fmt.Errorf("reply lost") + } + return nil +} + +// ListConsumerGroupPositions lists every partition directory but those skip +// reports, with what was saved in it, and remembers the directories loaded. +func (m *memoryPositions) ListConsumerGroupPositions(ctx context.Context, t topic.Topic, group string, skip func(dir string) bool) (map[string]*offset.ConsumerGroupPosition, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.failLists > 0 { + m.failLists-- + return nil, fmt.Errorf("filer unavailable") + } + positions := map[string]*offset.ConsumerGroupPosition{} + for key, p := range m.partitions { + if skip != nil && skip(topic.PartitionDir(t, p)) { + continue + } + if m.loadLimit > 0 && len(positions) == m.loadLimit { + return positions, fmt.Errorf("listing ran out of time: %w", context.DeadlineExceeded) + } + positions[topic.PartitionDir(t, p)] = nil + if position, ok := m.positions[key]; ok { + positions[topic.PartitionDir(t, p)] = &position + } + m.listed = append(m.listed, topic.PartitionDir(t, p)) + } + return positions, nil +} + +// get is the position of the first generation's partition at rangeStart. +func (m *memoryPositions) get(rangeStart int32) offset.ConsumerGroupPosition { + return m.getAt(fakeLogKey{0, rangeStart}) +} + +func (m *memoryPositions) getAt(key fakeLogKey) offset.ConsumerGroupPosition { + m.mu.Lock() + defer m.mu.Unlock() + return m.positions[fakeLogKey{atSecond(key.version), key.rangeStart}] +} + +func (m *memoryPositions) set(rangeStart int32, position offset.ConsumerGroupPosition) { + m.mu.Lock() + defer m.mu.Unlock() + m.positions[fakeLogKey{0, rangeStart}] = position +} + +// addDirs lists the partition directories of a generation of count partitions, +// as the topic's directory does once they hold data. +func (m *memoryPositions) addDirs(version int64, count int32) { + m.mu.Lock() + defer m.mu.Unlock() + for _, p := range generationPartitions(atSecond(version), count) { + m.partitions[fakeLogKey{atSecond(version), p.RangeStart}] = topic.FromPbPartition(p) + } +} + +func (m *memoryPositions) refusals() int { + m.mu.Lock() + defer m.mu.Unlock() + return m.refused +} + +// fakeLocks grants each key to one lock at a time, in request order, with a +// new generation per grant. +type fakeLocks struct { + mu sync.Mutex + generation int64 + holders map[string]*fakeLock + waiting map[string][]*fakeLock + // Stop waits for stopGate while it is set, as a release the lock server is slow to answer + stopGate chan struct{} +} + +type fakeLock struct { + locks *fakeLocks + key string + held atomic.Bool + generation atomic.Int64 +} + +func newFakeLocks() *fakeLocks { + return &fakeLocks{holders: map[string]*fakeLock{}, waiting: map[string][]*fakeLock{}} +} + +func (s *fakeLocks) start(key string) forwarderLock { + s.mu.Lock() + defer s.mu.Unlock() + l := &fakeLock{locks: s, key: key} + if s.holders[key] == nil { + s.grantLocked(l) + } else { + s.waiting[key] = append(s.waiting[key], l) + } + return l +} + +func (s *fakeLocks) grantLocked(l *fakeLock) { + s.generation++ + l.generation.Store(s.generation) + l.held.Store(true) + s.holders[l.key] = l +} + +func (s *fakeLocks) holder(key string) *fakeLock { + s.mu.Lock() + defer s.mu.Unlock() + return s.holders[key] +} + +func (l *fakeLock) IsLocked() bool { return l.held.Load() } +func (l *fakeLock) Generation() int64 { return l.generation.Load() } + +func (l *fakeLock) Stop() error { + s := l.locks + s.mu.Lock() + gate := s.stopGate + s.mu.Unlock() + if gate != nil { + <-gate + } + s.mu.Lock() + defer s.mu.Unlock() + if s.holders[l.key] != l { + waiting := s.waiting[l.key] + for i, w := range waiting { + if w == l { + s.waiting[l.key] = append(waiting[:i], waiting[i+1:]...) + } + } + return nil + } + l.held.Store(false) + delete(s.holders, l.key) + if waiting := s.waiting[l.key]; len(waiting) > 0 { + s.waiting[l.key] = waiting[1:] + s.grantLocked(waiting[0]) + } + return nil +} + +type forwarderSetup struct { + broker *fakeBroker + positions *memoryPositions + locks *fakeLocks + hook *webhookServer +} + +func newForwarderSetup(t *testing.T) *forwarderSetup { + return &forwarderSetup{broker: startFakeBroker(t, &fakeBroker{}), positions: newMemoryPositions(), locks: newFakeLocks(), hook: newWebhookServer(t)} +} + +func (s *forwarderSetup) forwarder(t *testing.T, owner string) *Forwarder { + t.Helper() + f := NewForwarder(func() []string { return []string{s.broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()), s.positions, nil, owner) + f.startLock = s.locks.start + f.lockCheckInterval = 10 * time.Millisecond + f.idleWait = 10 * time.Millisecond + f.minBackoff = 10 * time.Millisecond + f.maxBackoff = 50 * time.Millisecond + f.reclaimWait = time.Hour + f.partitionRefresh = 20 * time.Millisecond + t.Cleanup(f.Close) + return f +} + +func (s *forwarderSetup) registry(t *testing.T, name string) *Registry { + t.Helper() + reg, err := ParseTargets([]byte(fmt.Sprintf(`{"targets":[{"name":%q,"type":"webhook","enabled":true,"endpoint":%q,"bearer_token":"tok","allowed_buckets":["*"]}]}`, name, s.hook.URL))) + if err != nil { + t.Fatal(err) + } + return reg +} + +// deliveredNames lists the records the webhook took, in the order it took them. +func (s *webhookServer) deliveredNames(t *testing.T) []string { + t.Helper() + var names []string + for _, body := range s.delivered() { + names = append(names, bodyNames(t, body)...) + } + return names +} + +func sequence(from, to int) []string { + var names []string + for i := from; i < to; i++ { + names = append(names, fmt.Sprint(i)) + } + return names +} + +func waitForRecords(t *testing.T, hook *webhookServer, want []string) { + t.Helper() + waitUntil(t, fmt.Sprintf("%d records delivered", len(want)), func() bool { return len(hook.deliveredNames(t)) >= len(want) }) + if got := hook.deliveredNames(t); strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("delivered %v, want %v", got, want) + } +} + +func TestForwarderDeliversInOffsetOrderAcrossSegmentBoundaries(t *testing.T) { + s := newForwarderSetup(t) + s.broker.segment = 4 + s.broker.appendRecords(sequence(0, 25)...) + deliveredBefore := testutil.ToFloat64(stats.S3NotificationDeliveredCounter.WithLabelValues("ordered")) + f := s.forwarder(t, "gw1") + f.Sync(s.registry(t, "ordered")) + + waitForRecords(t, s.hook, sequence(0, 25)) + waitUntil(t, "offset 25 stored", func() bool { return s.positions.get(0).Value == 25 }) + if posts := len(s.hook.delivered()); posts < 7 { + t.Fatalf("%d posts, want one per fetch that stops at a segment boundary", posts) + } + if got := s.positions.get(0); got.Writer != "gw1" || got.Generation == 0 { + t.Fatalf("stored %+v", got) + } + waitUntil(t, "lag 0", func() bool { + return testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("ordered")) == 0 + }) + if got := testutil.ToFloat64(stats.S3NotificationDeliveredCounter.WithLabelValues("ordered")) - deliveredBefore; got != 25 { + t.Fatalf("delivered counter rose by %v, want 25", got) + } + s.hook.mu.Lock() + defer s.hook.mu.Unlock() + for _, auth := range s.hook.auth { + if auth != "Bearer tok" { + t.Fatalf("authorization %q", auth) + } + } +} + +func TestForwarderRetriesRejectedSendsAndCommitsOnlyAfterSuccess(t *testing.T) { + s := newForwarderSetup(t) + s.hook.setStatus(http.StatusInternalServerError) + s.broker.appendRecords("a", "b") + f := s.forwarder(t, "gw1") + f.Sync(s.registry(t, "flaky")) + + start := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("flaky")) + retries := func() float64 { + return testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("flaky")) - start + } + waitUntil(t, "retries after 500", func() bool { return retries() >= 2 }) + s.hook.setStatus(http.StatusUnauthorized) + before := retries() + waitUntil(t, "retries after 401", func() bool { return retries() >= before+2 }) + if got := s.positions.get(0).Value; got != 0 { + t.Fatalf("offset %d stored before the batch was taken", got) + } + if lag := testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("flaky")); lag != 2 { + t.Fatalf("lag %v while blocked, want 2", lag) + } + + s.hook.setStatus(http.StatusAccepted) + waitForRecords(t, s.hook, []string{"a", "b"}) + waitUntil(t, "offset 2 stored", func() bool { return s.positions.get(0).Value == 2 }) +} + +// A lead claiming a partition starts where the previous lead committed last, +// though that lead committed again after the claim loaded the offset. +func TestAClaimStartsAtTheOffsetItReplaces(t *testing.T) { + s := newForwarderSetup(t) + f := s.forwarder(t, "gw2") + tf := &targetForwarder{f: f, name: "claimed", topic: topic.NewTopic(TopicNamespace, "claimed"), lags: map[topic.Partition]int64{}} + partition := topic.FromPbPartition(generationPartitions(0, TopicPartitionCount)[0]) + s.positions.mu.Lock() + s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 1, Writer: "gw1"} + s.positions.afterLoad = func() { + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + s.positions.afterLoad = nil + s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 20, Generation: 1, Writer: "gw1"} + } + s.positions.mu.Unlock() + + next, fence, _, err := tf.claim(context.Background(), partition, 2, false) + if err != nil { + t.Fatal(err) + } + if next != 20 || fence != 2 { + t.Fatalf("claimed at offset %d fence %d, want offset 20 fence 2", next, fence) + } +} + +// A claim whose takeover was applied but whose reply was lost retries at the +// offset the takeover kept, not the one it loaded: by then the stored entry +// is its own, so a retry at the loaded offset would rewind the partition. +func TestAClaimRetriedAfterALostReplyDoesNotRewind(t *testing.T) { + s := newForwarderSetup(t) + f := s.forwarder(t, "gw2") + tf := &targetForwarder{f: f, name: "lost", topic: topic.NewTopic(TopicNamespace, "lost"), lags: map[topic.Partition]int64{}} + partition := topic.FromPbPartition(generationPartitions(0, TopicPartitionCount)[0]) + s.positions.mu.Lock() + s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 1, Writer: "gw1"} + s.positions.afterLoad = func() { + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + s.positions.afterLoad = nil + s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 20, Generation: 1, Writer: "gw1"} + } + s.positions.lostSaves = 1 + s.positions.mu.Unlock() + + next, _, _, err := tf.claim(context.Background(), partition, 2, false) + if err != nil { + t.Fatal(err) + } + if stored := s.positions.get(0); next != 20 || stored.Value != 20 { + t.Fatalf("claimed at offset %d, stored %+v; want both at 20", next, stored) + } +} + +func TestForwarderResumesFromTheStoredOffset(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords(sequence(0, 10)...) + s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 6}) + f := s.forwarder(t, "gw1") + f.Sync(s.registry(t, "resume")) + waitForRecords(t, s.hook, sequence(6, 10)) + + // a restart picks up where the last batch was stored + waitUntil(t, "offset 10 stored", func() bool { return s.positions.get(0).Value == 10 }) + f.Close() + s.broker.appendRecords(sequence(10, 13)...) + s.forwarder(t, "gw1-restarted").Sync(s.registry(t, "resume")) + waitForRecords(t, s.hook, sequence(6, 13)) +} + +func TestForwarderSkipsRecordsThatCanNeverBeDelivered(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a", "unrenderable", "b") + s.broker.mu.Lock() + s.broker.appendLocked(fakeLogKey{}, []byte(`{"Records":[]}`)) // not a RecordValue + s.broker.mu.Unlock() + s.broker.appendRecords("c") + skipped := func(reason string) float64 { + return testutil.ToFloat64(stats.S3NotificationSkippedCounter.WithLabelValues("poison", reason)) + } + unrenderableBefore, undecodableBefore := skipped("unrenderable"), skipped("undecodable") + retriesBefore := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("poison")) + f := s.forwarder(t, "gw1") + f.newDestination = func(t *Target) destination { + hook := newWebhook(t) + hook.render = renderRefusing + return hook + } + f.Sync(s.registry(t, "poison")) + + waitForRecords(t, s.hook, []string{"a", "b", "c"}) + waitUntil(t, "offset 5 stored", func() bool { return s.positions.get(0).Value == 5 }) + if got := skipped("unrenderable") - unrenderableBefore; got != 1 { + t.Fatalf("skipped %v unrenderable records, want 1", got) + } + if got := skipped("undecodable") - undecodableBefore; got != 1 { + t.Fatalf("skipped %v undecodable records, want 1", got) + } + if got := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("poison")) - retriesBefore; got != 0 { + t.Fatalf("%v send retries for a record that cannot render", got) + } +} + +// position of name in delivered, failing when it is not there exactly once. +func position(t *testing.T, delivered []string, name string) int { + t.Helper() + at := -1 + for i, got := range delivered { + if got == name { + if at >= 0 { + t.Fatalf("%s delivered twice in %v", name, delivered) + } + at = i + } + } + if at < 0 { + t.Fatalf("%s not delivered in %v", name, delivered) + } + return at +} + +// A repartition leaves records undelivered in the retired ranges; they go out +// first, in order, and the new ranges only after them, so a key's records keep +// their order across the repartition, after a restart too. +// A forwarder taking over after a repartition finds the retired ranges it never +// read and delivers them before the new ones. +func TestForwarderDeliversRetiredRangesItNeverRead(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a1", "a2") + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("a3") + s.forwarder(t, "gw1").Sync(s.registry(t, "late")) + waitForRecords(t, s.hook, []string{"a1", "a2", "a3"}) +} + +func TestForwarderDeliversARepartitionedTopicInOrder(t *testing.T) { + s := newForwarderSetup(t) + // one record per fetch, so a2 is still in the old range when it is retired + s.broker.segment = 1 + s.hook.setStatus(http.StatusServiceUnavailable) + s.broker.appendRecords("a1", "a2") + s.broker.appendTo(fakeLogKey{0, 630}, "x1") + first := s.forwarder(t, "gw1") + first.Sync(s.registry(t, "split")) + waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 }) + + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("a3") + s.broker.appendTo(fakeLogKey{7_000_000_123, 1260}, "y1") + // several re-lists see the repartition while the endpoint still refuses + time.Sleep(10 * 20 * time.Millisecond) + s.hook.setStatus(http.StatusOK) + waitUntil(t, "five records delivered", func() bool { return len(s.hook.deliveredNames(t)) >= 5 }) + delivered := s.hook.deliveredNames(t) + a1, a2, a3 := position(t, delivered, "a1"), position(t, delivered, "a2"), position(t, delivered, "a3") + x1, y1 := position(t, delivered, "x1"), position(t, delivered, "y1") + if !(a1 < a2 && a2 < a3 && x1 < a3 && x1 < y1 && a2 < y1) { + t.Fatalf("delivered %v, want every retired record before the new ranges' and a's in order", delivered) + } + waitUntil(t, "the offsets stored", func() bool { + return s.positions.get(0).Value == 2 && s.positions.get(630).Value == 1 && s.positions.getAt(fakeLogKey{7_000_000_123, 0}).Value == 1 && + s.positions.getAt(fakeLogKey{7_000_000_123, 1260}).Value == 1 + }) + + // a restart forwards nothing twice and carries on in the new ranges + first.Close() + s.broker.appendRecords("a4") + s.forwarder(t, "gw2").Sync(s.registry(t, "split")) + waitUntil(t, "a4 delivered", func() bool { return len(s.hook.deliveredNames(t)) >= 6 }) + time.Sleep(100 * time.Millisecond) + delivered = s.hook.deliveredNames(t) + if len(delivered) != 6 || position(t, delivered, "a4") != 5 { + t.Fatalf("after the restart delivered %v", delivered) + } +} + +// A range retired while its batch is retried keeps its one loop, though the +// topic lists it at the second its generation's directory is named for. +func TestForwarderKeepsOneLoopForARangeRetiredMidBatch(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.segment = 1 + s.hook.setStatus(http.StatusServiceUnavailable) + s.broker.appendRecords("a1", "a2") + s.forwarder(t, "gw1").Sync(s.registry(t, "midbatch")) + waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 }) + + s.broker.repartition(9_000_000_456, 2) + // several re-lists see the retired range while the endpoint still refuses + time.Sleep(10 * 20 * time.Millisecond) + s.hook.setStatus(http.StatusOK) + waitForRecords(t, s.hook, []string{"a1", "a2"}) + time.Sleep(200 * time.Millisecond) + if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1,a2" { + t.Fatalf("delivered %v, want a1,a2 once each", got) + } +} + +// A range drained but not sealed yet pauses its loop; offered again as +// retired, it is forwarded once that loop has finished its batch. +func TestForwarderReplacesAPausedLoopOnlyOnceItEnds(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.segment = 1 + s.hook.setStatus(http.StatusServiceUnavailable) + s.broker.appendRecords("a1", "a2") + s.forwarder(t, "gw1").Sync(s.registry(t, "unsealed")) + waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 }) + + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(9_000_000_456, 2) + time.Sleep(10 * 20 * time.Millisecond) + s.broker.setSealed(5_000_000_123, true) + // several re-lists offer the retired range while the paused loop still retries + time.Sleep(10 * 20 * time.Millisecond) + s.hook.setStatus(http.StatusOK) + waitForRecords(t, s.hook, []string{"a1", "a2"}) + time.Sleep(200 * time.Millisecond) + if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1,a2" { + t.Fatalf("delivered %v, want a1,a2 once each", got) + } +} + +// While a drained range is not sealed yet, the topic offers it neither as +// assigned nor as retired; the new ranges wait for it, so no key's new record +// goes out before its old ones. +func TestForwarderHoldsTheNewRangesWhileAnOldOneIsUnsealed(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.appendRecords("a1") + s.forwarder(t, "gw1").Sync(s.registry(t, "held")) + waitForRecords(t, s.hook, []string{"a1"}) + + // a2 lands just before the repartition, whose drain has not sealed the old range + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(9_000_000_456, 4, "a2") + s.broker.appendRecords("a3") + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1" { + t.Fatalf("delivered %v while the old range was unsealed, want only a1", got) + } + + s.broker.setSealed(5_000_000_123, true) + waitForRecords(t, s.hook, []string{"a1", "a2", "a3"}) +} + +// A forwarder starting for the first time while a drained range is still +// unsealed has no offset stored in it, and still holds the new ranges until +// that range is offered as retired and delivered. +func TestAFreshForwarderHoldsTheNewRangesWhileAnOldOneIsUnsealed(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.appendRecords("a1") + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(9_000_000_456, 4, "a2") + s.broker.appendRecords("a3") + s.positions.addDirs(5_000_000_123, 2) + s.positions.addDirs(9_000_000_456, 4) + + s.forwarder(t, "gw1").Sync(s.registry(t, "fresh")) + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); len(got) != 0 { + t.Fatalf("delivered %v with the old range unsealed, want nothing yet", got) + } + // the held new range's record counts toward the lag; the unsealed range's cannot be read yet + waitUntil(t, "the held range's lag", func() bool { + return testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("fresh")) == 1 + }) + + s.broker.setSealed(5_000_000_123, true) + waitForRecords(t, s.hook, []string{"a1", "a2", "a3"}) +} + +// A generation still unsealed holds back the retired generations after it, not +// only the current one, so each key's records keep their order across both. +func TestAnUnsealedGenerationHoldsTheRetiredOnesAfterIt(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.appendRecords("g1") + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("g2") + s.broker.repartition(9_000_000_456, 4) + s.broker.appendRecords("g3") + s.positions.addDirs(5_000_000_123, 2) + + s.forwarder(t, "gw1").Sync(s.registry(t, "barrier")) + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); len(got) != 0 { + t.Fatalf("delivered %v with the oldest generation unsealed, want nothing yet", got) + } + + s.broker.setSealed(5_000_000_123, true) + waitForRecords(t, s.hook, []string{"g1", "g2", "g3"}) +} + +// A lead reads the stored offset of a historical range once, until it finds it +// settled, and never that of a range the topic offers, however often it looks. +func TestALeadLoadsOnlyTheRangesItDoesNotKnow(t *testing.T) { + s := newForwarderSetup(t) + var historical []int64 + for i := int64(1); i <= 10; i++ { + version := i * 1_000_000_000 + s.broker.repartition(version, 2) + s.positions.addDirs(version, 2) + historical = append(historical, version) + } + s.broker.repartition(20_000_000_123, 4) + s.positions.addDirs(20_000_000_123, 4) + s.broker.appendRecords("a") + + s.forwarder(t, "gw1").Sync(s.registry(t, "known")) + waitForRecords(t, s.hook, []string{"a"}) + time.Sleep(10 * 20 * time.Millisecond) + + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + loads := map[string]int{} + for _, dir := range s.positions.listed { + loads[dir]++ + } + current := topic.NewTopic(TopicNamespace, topicPrefix+"known") + for _, p := range generationPartitions(20_000_000_123, 4) { + if n := loads[topic.PartitionDir(current, topic.FromPbPartition(p))]; n != 0 { + t.Errorf("current range %v loaded %d times", p, n) + } + } + for _, version := range historical { + for _, p := range generationPartitions(version, 2) { + if n := loads[topic.PartitionDir(current, topic.FromPbPartition(p))]; n != 1 { + t.Errorf("settled range %v loaded %d times, want once", p, n) + } + } + } +} + +// A retired range's loop that fails, as on being deposed, has not delivered its +// range, so the lead ends without starting the generation after it. +func TestAFailedRetiredLoopDoesNotLetTheNextGenerationStart(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a1") + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("c1") + // a newer holder has taken the retired range over + s.positions.mu.Lock() + s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 0, Generation: 1 << 40, Writer: "gw2"} + s.positions.mu.Unlock() + f := s.forwarder(t, "gw1") + var once sync.Once + f.loopEnded = func(err error) { + if err != nil { + // widen the moment between the loop ending and the lead stopping + once.Do(func() { time.Sleep(10 * 20 * time.Millisecond) }) + } + } + f.Sync(s.registry(t, "deposed")) + + time.Sleep(20 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); slices.Contains(got, "c1") { + t.Fatalf("delivered %v: the next generation started after the retired range's loop failed", got) + } +} + +// With no older generation unsealed, a failing listing alone holds both the +// retired and the current ranges, and they go out once a listing succeeds. +func TestAFailedListingAloneHoldsEveryRange(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("r1") + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("c1") + s.positions.mu.Lock() + s.positions.failLists = 1 << 20 + s.positions.mu.Unlock() + + s.forwarder(t, "gw1").Sync(s.registry(t, "unlisted-only")) + waitUntil(t, "several failed listings", func() bool { + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + return s.positions.failLists <= 1<<20-3 + }) + if got := s.hook.deliveredNames(t); len(got) != 0 { + t.Fatalf("delivered %v while the stored offsets could not be listed, want nothing yet", got) + } + + s.positions.mu.Lock() + s.positions.failLists = 0 + s.positions.mu.Unlock() + waitForRecords(t, s.hook, []string{"r1", "c1"}) +} + +// A history too long to check within one listing's time is checked over several: +// each keeps the ranges it found settled, the next reads only the rest, and the +// current ranges start once all are checked. +func TestALongHistoryIsCheckedAcrossListings(t *testing.T) { + s := newForwarderSetup(t) + var historical []int64 + for i := int64(1); i <= 10; i++ { + version := i * 1_000_000_000 + s.broker.repartition(version, 2) + s.positions.addDirs(version, 2) + historical = append(historical, version) + } + s.broker.repartition(20_000_000_123, 4) + s.broker.appendRecords("a") + s.positions.mu.Lock() + s.positions.loadLimit = 6 + s.positions.mu.Unlock() + + s.forwarder(t, "gw1").Sync(s.registry(t, "long")) + waitForRecords(t, s.hook, []string{"a"}) + + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + loads := map[string]int{} + for _, dir := range s.positions.listed { + loads[dir]++ + } + long := topic.NewTopic(TopicNamespace, topicPrefix+"long") + for _, version := range historical { + for _, p := range generationPartitions(version, 2) { + if n := loads[topic.PartitionDir(long, topic.FromPbPartition(p))]; n != 1 { + t.Errorf("range %v read %d times, want once", p, n) + } + } + } +} + +// While the stored offsets cannot be listed, an older generation may still be +// unsealed, so retired generations are held as well as the current ones. +func TestAFailedListingHoldsTheRetiredGenerations(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.appendRecords("g1") + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("g2") + s.broker.repartition(9_000_000_456, 4) + s.broker.appendRecords("g3") + s.positions.addDirs(5_000_000_123, 2) + s.positions.mu.Lock() + s.positions.failLists = 1 << 20 + s.positions.mu.Unlock() + + s.forwarder(t, "gw1").Sync(s.registry(t, "unlisted-retired")) + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); len(got) != 0 { + t.Fatalf("delivered %v while the stored offsets could not be listed, want nothing yet", got) + } + + s.positions.mu.Lock() + s.positions.failLists = 0 + s.positions.mu.Unlock() + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); len(got) != 0 { + t.Fatalf("delivered %v with the oldest generation unsealed, want nothing yet", got) + } + + s.broker.setSealed(5_000_000_123, true) + waitForRecords(t, s.hook, []string{"g1", "g2", "g3"}) +} + +// A lead that cannot list the stored offsets does not know whether an old range +// is still unsealed, so it holds the new ranges until a listing succeeds. +func TestForwarderHoldsTheNewRangesUntilItCanListStoredOffsets(t *testing.T) { + s := newForwarderSetup(t) + s.broker.repartition(5_000_000_123, 2) + s.broker.appendRecords("a1") + reg := s.registry(t, "unlisted") + first := s.forwarder(t, "gw1") + first.Sync(reg) + waitForRecords(t, s.hook, []string{"a1"}) + first.Close() + + s.broker.setSealed(5_000_000_123, false) + s.broker.repartition(9_000_000_456, 4, "a2") + s.broker.appendRecords("a3") + s.positions.mu.Lock() + s.positions.failLists = 3 + s.positions.mu.Unlock() + s.forwarder(t, "gw2").Sync(reg) + waitUntil(t, "the listings to fail", func() bool { + s.positions.mu.Lock() + defer s.positions.mu.Unlock() + return s.positions.failLists == 0 + }) + time.Sleep(10 * 20 * time.Millisecond) + if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1" { + t.Fatalf("delivered %v with the old range unsealed, want only a1", got) + } + + s.broker.setSealed(5_000_000_123, true) + waitForRecords(t, s.hook, []string{"a1", "a2", "a3"}) +} + +func TestForwarderWaitsAtAnOffsetTheBrokerReturnsNothingFor(t *testing.T) { + s := newForwarderSetup(t) + s.broker.segment = 1 + s.broker.holding, s.broker.holdAt = true, 1 + s.broker.appendRecords("a", "b", "c") + s.forwarder(t, "gw1").Sync(s.registry(t, "held")) + + waitForRecords(t, s.hook, []string{"a"}) + waitUntil(t, "fetches at the held offset", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 5 }) + if got := s.positions.get(0).Value; got != 1 { + t.Fatalf("offset %d stored past records never delivered", got) + } + if lag := testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("held")); lag != 2 { + t.Fatalf("lag %v, want 2", lag) + } + + s.broker.mu.Lock() + s.broker.holding = false + s.broker.mu.Unlock() + waitForRecords(t, s.hook, []string{"a", "b", "c"}) +} + +func TestForwarderRetriesFailedFetches(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a") + s.broker.failFetches = 8 + s.forwarder(t, "gw1").Sync(s.registry(t, "fetchfail")) + waitForRecords(t, s.hook, []string{"a"}) +} + +func TestForwarderSkipsWhatRetentionRemoved(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords(sequence(0, 10)...) + s.broker.purgeBefore(0, 5) + s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 2}) + gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("aged")) + s.forwarder(t, "gw1").Sync(s.registry(t, "aged")) + + waitForRecords(t, s.hook, sequence(5, 10)) + if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("aged")) - gapBefore; gap != 3 { + t.Fatalf("gap %v, want 3", gap) + } +} + +// A lead that claimed a partition and stopped before it read anything left an +// offset no records were delivered from, so the next lead counts no gap below +// the log start. +func TestAClaimNeverStartedCountsNoGap(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords(sequence(0, 10)...) + s.broker.purgeBefore(0, 5) + s.locks.mu.Lock() + s.locks.generation = 5 + s.locks.mu.Unlock() + s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 0, Generation: 5, Writer: "gw0", Metadata: claimedPosition}) + gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("unstarted")) + s.forwarder(t, "gw1").Sync(s.registry(t, "unstarted")) + + waitForRecords(t, s.hook, sequence(5, 10)) + if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("unstarted")) - gapBefore; gap != 0 { + t.Fatalf("gap %v below an offset only claimed, want 0", gap) + } +} + +// A lead that read an empty partition has established its offset, though it +// did not move, so records retention removes while no gateway forwards count +// as a gap for the next lead. +func TestAnOffsetReadButNotMovedCountsTheGapAfterIt(t *testing.T) { + s := newForwarderSetup(t) + reg := s.registry(t, "idle") + first := s.forwarder(t, "gw1") + first.Sync(reg) + waitUntil(t, "a few empty fetches", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 2 }) + first.Close() + + s.broker.appendRecords(sequence(0, 5)...) + s.broker.purgeBefore(0, 3) + gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("idle")) + s.forwarder(t, "gw2").Sync(reg) + waitForRecords(t, s.hook, sequence(3, 5)) + if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("idle")) - gapBefore; gap != 3 { + t.Fatalf("gap %v, want the 3 records retention removed while no gateway forwarded", gap) + } +} + +func TestForwarderStartsAtTheEarliestOffsetWithoutCountingAGap(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords(sequence(0, 4)...) + s.broker.purgeBefore(0, 1) + gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("fresh")) + s.forwarder(t, "gw1").Sync(s.registry(t, "fresh")) + + waitForRecords(t, s.hook, sequence(1, 4)) + if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("fresh")) - gapBefore; gap != 0 { + t.Fatalf("gap %v for a forwarder that never stored an offset", gap) + } +} + +func TestDeposedForwarderStopsDelivering(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a") + s.forwarder(t, "gw1").Sync(s.registry(t, "deposed")) + waitForRecords(t, s.hook, []string{"a"}) + waitUntil(t, "offset 1 stored", func() bool { return s.positions.get(0).Value == 1 }) + + // a newer forwarder claims the partition while this one still thinks it holds the lock + mine := s.positions.get(0) + s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 1, Generation: mine.Generation + 1, Writer: "gw2"}) + s.broker.appendRecords("b", "c") + waitUntil(t, "the save refused", func() bool { return s.positions.refusals() > 0 }) + // b and c went out once before the refused save; nothing goes out after it + s.broker.appendRecords("d") + time.Sleep(200 * time.Millisecond) + if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a,b,c" { + t.Fatalf("deposed forwarder delivered %v, want a,b,c", got) + } + if stored := s.positions.get(0); stored.Writer != "gw2" || stored.Value != 1 { + t.Fatalf("deposed forwarder overwrote the position: %+v", stored) + } +} + +func TestForwarderReclaimsAfterTheLockGenerationRestarts(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords(sequence(0, 3)...) + // stored before the lock server restarted and its generations began again + s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 1, Generation: 50, Writer: "gw-old"}) + f := s.forwarder(t, "gw1") + f.reclaimWait = 50 * time.Millisecond + f.Sync(s.registry(t, "restarted")) + + waitForRecords(t, s.hook, sequence(1, 3)) + waitUntil(t, "offset 3 stored", func() bool { return s.positions.get(0).Value == 3 }) + if got := s.positions.get(0); got.Generation != 51 || got.Writer != "gw1" { + t.Fatalf("stored %+v, want generation 51 by gw1", got) + } +} + +// stalledFiler answers no offset read until the caller gives up. +type stalledFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + stalled atomic.Int32 +} + +func (f *stalledFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.stalled.Add(1) + <-ctx.Done() + return nil, ctx.Err() +} + +// ListEntries lists no stored offsets, so the lead goes on to read one. +func (f *stalledFiler) ListEntries(*filer_pb.ListEntriesRequest, grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error { + return nil +} + +func TestForwarderCloseIsNotHeldByAStalledFiler(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + filer := &stalledFiler{} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + t.Cleanup(server.Stop) + address := pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port) + dialOption := grpc.WithTransportCredentials(insecure.NewCredentials()) + + s := newForwarderSetup(t) + f := s.forwarder(t, "gw1") + f.positions = offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filer_client.NewFilerClientAccessor([]pb.ServerAddress{address}, dialOption)) + f.Sync(s.registry(t, "stalled")) + waitUntil(t, "an offset read to stall", func() bool { return filer.stalled.Load() > 0 }) + + closed := make(chan struct{}) + go func() { + f.Close() + close(closed) + }() + select { + case <-closed: + case <-time.After(10 * time.Second): + t.Fatal("Close waited on a stalled filer") + } + if holder := s.locks.holder(ForwarderLockPrefix + "stalled"); holder != nil { + t.Fatal("the forwarder lock was not released") + } +} + +// A retired range is read from any broker, so one that answers with a storage +// error is passed over for the next. +func TestARetiredRangeIsReadPastABrokerThatCannotReadIt(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a1") + s.broker.repartition(7_000_000_123, 2) + s.broker.appendRecords("a2") + failing := startFakeBroker(t, &fakeBroker{failLookups: true, fetchErrorCode: broker.BrokerErrorStorageError}) + f := s.forwarder(t, "gw1") + f.brokers = func() []string { return []string{failing.addr, s.broker.addr} } + f.Sync(s.registry(t, "unreadable")) + waitForRecords(t, s.hook, []string{"a1", "a2"}) +} + +// A lead that loses its lock while it fetches a batch does not send it: the +// next holder starts from the stored offset and sends that batch itself. +func TestALeadThatLostItsLockDoesNotSend(t *testing.T) { + s := newForwarderSetup(t) + s.broker.appendRecords("a", "b") + var once sync.Once + s.broker.mu.Lock() + s.broker.onFetch = func() { + once.Do(func() { s.locks.holder(ForwarderLockPrefix + "lost").held.Store(false) }) + } + s.broker.mu.Unlock() + s.forwarder(t, "gw1").Sync(s.registry(t, "lost")) + waitUntil(t, "a fetch", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 0 }) + time.Sleep(10 * 20 * time.Millisecond) + if n := s.hook.attempts(); n != 0 { + t.Fatalf("%d sends after the lock was lost", n) + } +} + +// A target removed from the registry is still releasing its lock when the +// gateway closes, and Close waits for that release too. +func TestCloseWaitsForARemovedTargetToReleaseItsLock(t *testing.T) { + s := newForwarderSetup(t) + f := s.forwarder(t, "gw1") + f.Sync(s.registry(t, "removed")) + waitUntil(t, "the lock taken", func() bool { return s.locks.holder(ForwarderLockPrefix+"removed") != nil }) + + gate := make(chan struct{}) + s.locks.mu.Lock() + s.locks.stopGate = gate + s.locks.mu.Unlock() + empty, err := ParseTargets([]byte(`{"targets":[]}`)) + if err != nil { + t.Fatal(err) + } + f.Sync(empty) + closed := make(chan struct{}) + go func() { + f.Close() + close(closed) + }() + select { + case <-closed: + close(gate) + t.Fatal("Close returned while a removed target still held its lock") + case <-time.After(200 * time.Millisecond): + } + close(gate) + select { + case <-closed: + case <-time.After(10 * time.Second): + t.Fatal("Close never returned") + } + if holder := s.locks.holder(ForwarderLockPrefix + "removed"); holder != nil { + t.Fatal("the removed target's lock is still held") + } +} + +func TestOneForwarderPerTarget(t *testing.T) { + s := newForwarderSetup(t) + reg := s.registry(t, "elected") + first, second := s.forwarder(t, "gw1"), s.forwarder(t, "gw2") + first.Sync(reg) + waitUntil(t, "gw1 to take the lock", func() bool { return s.locks.holder(ForwarderLockPrefix+"elected") != nil }) + second.Sync(reg) + s.broker.appendRecords(sequence(0, 20)...) + waitForRecords(t, s.hook, sequence(0, 20)) + waitUntil(t, "offset 20 stored", func() bool { return s.positions.get(0).Value == 20 }) + if writer := s.positions.get(0).Writer; writer != "gw1" { + t.Fatalf("offsets stored by %s, want the lock holder gw1", writer) + } + + // the holder's gateway stops; the other takes over from the stored offset + first.Close() + waitUntil(t, "gw2 to hold the lock", func() bool { + h := s.locks.holder(ForwarderLockPrefix + "elected") + return h != nil && h.IsLocked() + }) + s.broker.appendRecords(sequence(20, 30)...) + waitForRecords(t, s.hook, sequence(0, 30)) + waitUntil(t, "gw2 to store", func() bool { return s.positions.get(0).Writer == "gw2" }) +} + +func TestForwarderFollowsTheRegistry(t *testing.T) { + s := newForwarderSetup(t) + f := s.forwarder(t, "gw1") + f.Sync(s.registry(t, "moving")) + s.broker.appendRecords("a") + waitForRecords(t, s.hook, []string{"a"}) + + // a new endpoint takes the next batch without giving up the lock + moved := newWebhookServer(t) + reg, err := ParseTargets([]byte(fmt.Sprintf(`{"targets":[{"name":"moving","type":"webhook","enabled":true,"endpoint":%q,"allowed_buckets":["*"]}]}`, moved.URL))) + if err != nil { + t.Fatal(err) + } + f.Sync(reg) + s.broker.appendRecords("b") + waitForRecords(t, moved, []string{"b"}) + + // a topic target and a removed one have no forwarder, and the lock is released + reg, err = ParseTargets([]byte(`{"targets":[{"name":"moving","type":"topic","enabled":true,"allowed_buckets":["*"]}]}`)) + if err != nil { + t.Fatal(err) + } + f.Sync(reg) + waitUntil(t, "the lock released", func() bool { return s.locks.holder(ForwarderLockPrefix+"moving") == nil }) + f.mu.Lock() + running := len(f.targets) + f.mu.Unlock() + if running != 0 { + t.Fatalf("%d forwarders running for a topic target", running) + } +} + +func TestPublishedEventsReachTheWebhook(t *testing.T) { + s := newForwarderSetup(t) + reg := s.registry(t, "e2e") + p := NewPublisher(func() []string { return []string{s.broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials())) + t.Cleanup(p.Close) + p.Sync(reg) + s.forwarder(t, "gw1").Sync(reg) + + var messages []Message + for _, key := range []string{"a", "b", "c"} { + messages = append(messages, Message{Target: "e2e", Key: MessageKey("photos", "same"), Value: namedRecord(key)}) + } + // a record not acked within the wait stays queued, so this publishes each once + p.Publish(context.Background(), messages) + waitForRecords(t, s.hook, []string{"a", "b", "c"}) +} diff --git a/weed/s3api/s3notification/publisher_test.go b/weed/s3api/s3notification/publisher_test.go index 676c026771..6e72eb2dc5 100644 --- a/weed/s3api/s3notification/publisher_test.go +++ b/weed/s3api/s3notification/publisher_test.go @@ -176,7 +176,10 @@ func TestPublishGivesUpWaitingButKeepsTheRecord(t *testing.T) { if waited := time.Since(start); waited < tp.ackWait || waited > tp.ackWait+time.Second { t.Fatalf("waited %v, want about %v", waited, tp.ackWait) } - waitUntil(t, "the record to reach the publisher", func() bool { return len(tp.topic("slow").published()) == 1 }) + waitUntil(t, "the record to reach the publisher", func() bool { + f := tp.topic("slow") + return f != nil && len(f.published()) == 1 + }) if d := dropped("slow"); d != 0 { t.Fatalf("a late record was counted dropped %v times", d) } @@ -469,7 +472,8 @@ func TestStoppingATargetReleasesAPublisherBlockedOnAFullBuffer(t *testing.T) { } // fakeBroker is an in-process broker that refuses topic configuration while -// it is "starting", then leads every partition and acks each message. +// it is "starting", then leads every partition, acks each message, and serves +// what it holds to FetchMessage. type fakeBroker struct { mq_pb.UnimplementedSeaweedMessagingServer addr string @@ -484,6 +488,28 @@ type fakeBroker struct { recordType []*schema_pb.RecordType // every record type a ConfigureTopic carried stored map[string][]string values [][]byte + logs map[fakeLogKey]*fakeLog + fetches map[fakeLogKey]int + // version and partitionCount are the generation and number of the + // partitions lookups list; a repartition changes them + version int64 + partitionCount int32 + // retired holds the partition count of each generation a repartition replaced + retired map[int64]int32 + // unsealed retired generations are neither listed nor served, as before a drain seals them + unsealed map[int64]bool + // segment, when set, ends each fetch at the next multiple of it, as a + // flushed segment's boundary does + segment int64 + failFetches int + // holding makes a fetch at holdAt return no records, as a broker that + // cannot read a span it reports below its high-water mark does + holding bool + holdAt int64 + // onFetch runs as a fetch arrives + onFetch func() + // fetchErrorCode, when set, answers every fetch with that broker error, as a broker that cannot read the files does + fetchErrorCode int32 } func (b *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) { @@ -509,21 +535,56 @@ func (b *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTo if b.failLookups { return nil, status.Error(codes.Unavailable, "no broker available") } + b.mu.Lock() + defer b.mu.Unlock() resp := &mq_pb.LookupTopicBrokersResponse{Topic: req.Topic} - width := int32(pub_balancer.MaxPartitionCount / TopicPartitionCount) - for i := int32(0); i < TopicPartitionCount; i++ { - stop := (i + 1) * width - if i == TopicPartitionCount-1 { - stop = pub_balancer.MaxPartitionCount - } + for _, partition := range b.assignedLocked() { resp.BrokerPartitionAssignments = append(resp.BrokerPartitionAssignments, &mq_pb.BrokerPartitionAssignment{ - Partition: &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop}, + Partition: partition, LeaderBroker: b.addr, }) } + if req.IncludeRetired { + for version, count := range b.retired { + if b.unsealed[version] { + continue + } + // listed as the broker finds them, from their directory names + for _, partition := range generationPartitions(atSecond(version), count) { + if log := b.logs[fakeLogKey{version, partition.RangeStart}]; log != nil && int64(len(log.values)) > log.start { + resp.RetiredPartitions = append(resp.RetiredPartitions, &mq_pb.RetiredPartition{ + Partition: partition, LogStartOffset: log.start, HighWaterMark: int64(len(log.values)), + }) + } + } + } + } return resp, nil } +// assignedLocked is the current generation's partitions, TopicPartitionCount +// of them unless a repartition set partitionCount. +func (b *fakeBroker) assignedLocked() []*schema_pb.Partition { + count := int32(TopicPartitionCount) + if b.partitionCount > 0 { + count = b.partitionCount + } + return generationPartitions(b.version, count) +} + +func generationPartitions(version int64, count int32) []*schema_pb.Partition { + width := pub_balancer.MaxPartitionCount / count + var partitions []*schema_pb.Partition + for i := int32(0); i < count; i++ { + stop := (i + 1) * width + if i == count-1 { + stop = pub_balancer.MaxPartitionCount + } + partitions = append(partitions, &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop, UnixTimeNs: version}) + } + return partitions +} + func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error { init, err := stream.Recv() if err != nil { @@ -548,6 +609,8 @@ func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessage b.mu.Lock() b.stored[partition] = append(b.stored[partition], string(data.Key)) b.values = append(b.values, data.Value) + p := init.GetInit().GetPartition() + b.appendLocked(fakeLogKey{p.GetUnixTimeNs(), p.GetRangeStart()}, data.Value) b.mu.Unlock() if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil { return err diff --git a/weed/s3api/s3notification/webhook.go b/weed/s3api/s3notification/webhook.go new file mode 100644 index 0000000000..33a063ae36 --- /dev/null +++ b/weed/s3api/s3notification/webhook.go @@ -0,0 +1,175 @@ +package s3notification + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" + "github.com/seaweedfs/seaweedfs/weed/util/netguard" +) + +const ( + webhookTimeout = 30 * time.Second + // webhookErrorBodyLimit is how much of a refusal's body is kept for the log. + webhookErrorBodyLimit = 256 + maxWebhookRedirects = 10 +) + +// destination delivers a batch of records in order; nil means the +// destination took all of them, and an *unrenderableError names records it +// never will. +type destination interface { + Send(ctx context.Context, records []*schema_pb.RecordValue) error +} + +// webhook POSTs a batch as one {"Records":[...]} body, a test event in its +// own body, and takes any 2xx as delivered. +type webhook struct { + endpoint string + token string + render func(records ...*schema_pb.RecordValue) ([]byte, error) + client *http.Client +} + +func newWebhook(t *Target) *webhook { + return &webhook{ + endpoint: t.Endpoint, + token: t.BearerToken, + render: Render, + client: &http.Client{ + Timeout: webhookTimeout, + Transport: &http.Transport{ + // no proxy, so the dialer checks the address actually connected to + Proxy: nil, + DialContext: netguard.DialContext(redactedEndpoint(t.Endpoint), netguard.Local), + ForceAttemptHTTP2: true, + MaxIdleConnsPerHost: 4, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + }, + CheckRedirect: sameHostRedirect, + }, + } +} + +// sameHostRedirect follows a redirect only to the endpoint's own host and +// never from https to http, so the token and records stay with the endpoint +// the operator configured. Only 307 and 308 are followed: on 301, 302 and 303 +// Go resends the POST as a bodiless GET, whose 2xx would pass for delivery. +func sameHostRedirect(req *http.Request, via []*http.Request) error { + if len(via) >= maxWebhookRedirects { + return fmt.Errorf("stopped after %d redirects", len(via)) + } + if code := req.Response.StatusCode; code != http.StatusTemporaryRedirect && code != http.StatusPermanentRedirect { + return fmt.Errorf("refusing redirect %d, which would drop the posted records", code) + } + from := via[0].URL + if req.URL.Host != from.Host || (from.Scheme == "https" && req.URL.Scheme != "https") { + return fmt.Errorf("refusing redirect from %s://%s to %s://%s", from.Scheme, from.Host, req.URL.Scheme, req.URL.Host) + } + return nil +} + +// redactedEndpoint names an endpoint in errors and logs without what it may +// carry in its userinfo, query or fragment. +func redactedEndpoint(endpoint string) string { + u, err := url.Parse(endpoint) + if err != nil { + return "unparsable endpoint" + } + return (&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path}).String() +} + +func (w *webhook) Send(ctx context.Context, records []*schema_pb.RecordValue) error { + if u, err := url.Parse(w.endpoint); err != nil { + return errors.New("unparsable endpoint") + } else if netguard.IsMetadataHost(u.Hostname()) { + return fmt.Errorf("endpoint %s targets the instance metadata service", u.Hostname()) + } + // render everything before posting anything, so dropping an unrenderable + // record and sending the rest again does not repeat a body + var bodies [][]byte + unrenderable := &unrenderableError{} + renderRun := func(start, end int) { + if start == end { + return + } + if body, err := w.render(records[start:end]...); err == nil { + bodies = append(bodies, body) + return + } + for i := start; i < end; i++ { + body, err := w.render(records[i]) + if err != nil { + unrenderable.indexes = append(unrenderable.indexes, i) + unrenderable.err = err + continue + } + bodies = append(bodies, body) + } + } + start := 0 + for i, r := range records { + if IsTestEvent(r) { + renderRun(start, i) + renderRun(i, i+1) + start = i + 1 + } + } + renderRun(start, len(records)) + if len(unrenderable.indexes) > 0 { + return unrenderable + } + for _, body := range bodies { + if err := w.post(ctx, body); err != nil { + return err + } + } + return nil +} + +// unrenderableError names the records of a batch that cannot be rendered, so +// sending them again cannot succeed. +type unrenderableError struct { + indexes []int // into the batch given to Send + err error +} + +func (e *unrenderableError) Error() string { + return fmt.Sprintf("%d records cannot be rendered: %v", len(e.indexes), e.err) +} + +func (e *unrenderableError) Unwrap() error { return e.err } + +func (w *webhook) post(ctx context.Context, body []byte) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.endpoint, bytes.NewReader(body)) + if err != nil { + return fmt.Errorf("post to %s: invalid request", redactedEndpoint(w.endpoint)) + } + req.Header.Set("Content-Type", "application/json") + if w.token != "" { + req.Header.Set("Authorization", "Bearer "+w.token) + } + resp, err := w.client.Do(req) + if err != nil { + var urlErr *url.Error + if errors.As(err, &urlErr) { + // the URL may carry credentials in its query; the cause is enough + return fmt.Errorf("post: %w", urlErr.Err) + } + return err + } + defer resp.Body.Close() + if resp.StatusCode/100 == 2 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024)) + return nil + } + detail, _ := io.ReadAll(io.LimitReader(resp.Body, webhookErrorBodyLimit)) + return fmt.Errorf("endpoint answered %s: %s", resp.Status, bytes.TrimSpace(detail)) +} diff --git a/weed/s3api/s3notification/webhook_test.go b/weed/s3api/s3notification/webhook_test.go new file mode 100644 index 0000000000..bc58610724 --- /dev/null +++ b/weed/s3api/s3notification/webhook_test.go @@ -0,0 +1,279 @@ +package s3notification + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" + "github.com/seaweedfs/seaweedfs/weed/util/netguard" +) + +// webhookServer records what reaches it and answers with status. +type webhookServer struct { + *httptest.Server + mu sync.Mutex + status int + bodies []string + auth []string + received int +} + +func newWebhookServer(t *testing.T) *webhookServer { + t.Helper() + s := &webhookServer{status: http.StatusOK} + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.received++ + status := s.status + if status/100 == 2 { + s.bodies = append(s.bodies, string(body)) + s.auth = append(s.auth, r.Header.Get("Authorization")) + } + s.mu.Unlock() + w.WriteHeader(status) + })) + t.Cleanup(s.Close) + return s +} + +func (s *webhookServer) setStatus(status int) { + s.mu.Lock() + defer s.mu.Unlock() + s.status = status +} + +func (s *webhookServer) delivered() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.bodies...) +} + +func (s *webhookServer) attempts() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.received +} + +func webhookTarget(endpoint string) *Target { + return &Target{Name: "hook", Type: TargetTypeWebhook, Enabled: true, Endpoint: endpoint, BearerToken: "secret"} +} + +// namedRecord is a PUT of the object name, or, for a name starting with +// test-event, an s3:TestEvent with that request id. +func namedRecord(name string) *schema_pb.RecordValue { + if strings.HasPrefix(name, "test-event") { + return TestEventRecord("photos", name, 1) + } + return (&Event{Name: EventObjectCreatedPut, Bucket: "photos", Key: name, LogTsNs: 1}).RecordValue("rule") +} + +// bodyNames is the object keys of a {"Records":[...]} body, or the request id +// of a test event. +func bodyNames(t *testing.T, body string) []string { + t.Helper() + var test TestEvent + if err := json.Unmarshal([]byte(body), &test); err == nil && test.Event == EventTest { + return []string{test.RequestID} + } + var batch Records + if err := json.Unmarshal([]byte(body), &batch); err != nil { + t.Fatalf("body %s: %v", body, err) + } + var names []string + for _, r := range batch.Records { + names = append(names, r.S3.Object.Key) + } + return names +} + +// renderRefusing renders as Render does, but refuses a record named unrenderable. +func renderRefusing(records ...*schema_pb.RecordValue) ([]byte, error) { + for _, r := range records { + if r.Fields[ColumnObjectKey].GetStringValue() == "unrenderable" { + return nil, errors.New("unrenderable record") + } + } + return Render(records...) +} + +func TestWebhookPostsATestEventOnItsOwnInOrder(t *testing.T) { + server := newWebhookServer(t) + hook := newWebhook(webhookTarget(server.URL)) + err := hook.Send(context.Background(), []*schema_pb.RecordValue{ + namedRecord("a"), namedRecord("test-event-1"), namedRecord("test-event-2"), namedRecord("b"), namedRecord("c"), + }) + if err != nil { + t.Fatal(err) + } + var got []string + for _, body := range server.delivered() { + got = append(got, strings.Join(bodyNames(t, body), ",")) + } + if want := "a|test-event-1|test-event-2|b,c"; strings.Join(got, "|") != want { + t.Fatalf("posted %v, want %s", got, want) + } +} + +func TestWebhookPostsOneBodyPerBatch(t *testing.T) { + server := newWebhookServer(t) + server.setStatus(http.StatusNoContent) + hook := newWebhook(webhookTarget(server.URL + "/events")) + if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a"), namedRecord("b")}); err != nil { + t.Fatal(err) + } + bodies := server.delivered() + if len(bodies) != 1 { + t.Fatalf("%d posts, want 1", len(bodies)) + } + if got := strings.Join(bodyNames(t, bodies[0]), ","); got != "a,b" { + t.Fatalf("body %s carries %s, want a,b", bodies[0], got) + } + server.mu.Lock() + defer server.mu.Unlock() + if server.auth[0] != "Bearer secret" { + t.Fatalf("authorization %q", server.auth[0]) + } +} + +func TestWebhookNamesTheRecordsItCannotRenderAndPostsNothing(t *testing.T) { + server := newWebhookServer(t) + hook := newWebhook(webhookTarget(server.URL)) + hook.render = renderRefusing + err := hook.Send(context.Background(), []*schema_pb.RecordValue{ + namedRecord("a"), namedRecord("test-event"), namedRecord("b"), namedRecord("unrenderable"), namedRecord("c"), + }) + var unrenderable *unrenderableError + if !errors.As(err, &unrenderable) || fmt.Sprint(unrenderable.indexes) != "[3]" { + t.Fatalf("send with an unrenderable record: %v", err) + } + if n := server.attempts(); n != 0 { + t.Fatalf("%d posts before the batch was known to render", n) + } +} + +func TestWebhookTreatsAnythingButTwoHundredsAsFailed(t *testing.T) { + server := newWebhookServer(t) + hook := newWebhook(webhookTarget(server.URL)) + for _, status := range []int{http.StatusInternalServerError, http.StatusUnauthorized, http.StatusBadRequest} { + server.setStatus(status) + if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err == nil || !strings.Contains(err.Error(), http.StatusText(status)) { + t.Fatalf("status %d: %v", status, err) + } + } +} + +func TestWebhookErrorsCarryNoEndpointSecrets(t *testing.T) { + original := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = original }) + netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil + } + for _, endpoint := range []string{ + "http://user:hunter2@169.254.169.254/hook?token=sekrit", + "http://user:hunter2@rebound.example.com:8080/hook?token=sekrit", + "http://user:hunter2@[fe80::1]:8080/hook?token=sekrit#frag", + } { + err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")}) + if err == nil { + t.Fatalf("%s: sent", endpoint) + } + for _, secret := range []string{"hunter2", "sekrit", "user"} { + if strings.Contains(err.Error(), secret) { + t.Errorf("error %q carries %q", err, secret) + } + } + if !strings.Contains(err.Error(), "/hook") { + t.Errorf("error %q no longer names the endpoint", err) + } + } +} + +func TestWebhookFollowsOnlyRedirectsThatKeepThePost(t *testing.T) { + for _, code := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { + var mu sync.Mutex + var landed []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/old" { + http.Redirect(w, r, "/new", code) + return + } + body, _ := io.ReadAll(r.Body) + mu.Lock() + landed = append(landed, r.Method+" "+string(body)) + mu.Unlock() + })) + err := newWebhook(webhookTarget(server.URL+"/old")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")}) + server.Close() + mu.Lock() + got := strings.Join(landed, "|") + mu.Unlock() + if method, body, ok := strings.Cut(got, " "); ok && method == "POST" && strings.HasPrefix(body, "{") { + got = "POST " + strings.Join(bodyNames(t, body), ",") + } + if code == http.StatusTemporaryRedirect || code == http.StatusPermanentRedirect { + if err != nil || got != "POST a" { + t.Errorf("%d: %v, landed %q, want the POST resent", code, err, got) + } + continue + } + if err == nil || got != "" { + t.Errorf("%d: %v, landed %q, want a failure and nothing sent", code, err, got) + } + } +} + +func TestWebhookFollowsOnlySameHostRedirects(t *testing.T) { + target := newWebhookServer(t) + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/moved" { + http.Redirect(w, r, "/here", http.StatusTemporaryRedirect) + return + } + if r.URL.Path == "/here" { + w.WriteHeader(http.StatusOK) + return + } + http.Redirect(w, r, target.URL+"/stolen", http.StatusTemporaryRedirect) + })) + t.Cleanup(redirector.Close) + + if err := newWebhook(webhookTarget(redirector.URL+"/moved")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err != nil { + t.Fatalf("same-host redirect: %v", err) + } + err := newWebhook(webhookTarget(redirector.URL+"/elsewhere")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}) + if err == nil || !strings.Contains(err.Error(), "refusing redirect") { + t.Fatalf("cross-host redirect: %v", err) + } + if n := target.attempts(); n != 0 { + t.Fatalf("the other host got %d requests", n) + } +} + +func TestWebhookRefusesMetadataAndLinkLocalAddresses(t *testing.T) { + original := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = original }) + netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil + } + for _, endpoint := range []string{ + "http://169.254.169.254/latest", + "http://[fe80::1]:8080/", + "http://metadata.google.internal/", + "http://rebound.example.com/hook", + } { + err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}) + if err == nil || !(strings.Contains(err.Error(), "metadata") || strings.Contains(err.Error(), "link-local")) { + t.Errorf("%s: %v", endpoint, err) + } + } +} diff --git a/weed/server/volume_grpc_remote.go b/weed/server/volume_grpc_remote.go index 503368f9ae..a6e7bb8d02 100644 --- a/weed/server/volume_grpc_remote.go +++ b/weed/server/volume_grpc_remote.go @@ -35,20 +35,9 @@ import ( "github.com/seaweedfs/seaweedfs/weed/storage/types" "github.com/seaweedfs/seaweedfs/weed/util" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" + "github.com/seaweedfs/seaweedfs/weed/util/netguard" ) -// lookupIPAddrFunc resolves a host to one or more IP addresses. It is a -// package-level variable so tests can substitute a deterministic resolver. -var lookupIPAddrFunc = net.DefaultResolver.LookupIPAddr - -// blockedIMDSHosts lists hostnames that target cloud instance metadata -// services (IMDS). These are blocked regardless of how they happen to -// resolve, because some environments alias the IMDS address under a name. -var blockedIMDSHosts = map[string]struct{}{ - "metadata.google.internal": {}, - "metadata": {}, -} - // validateRemoteEndpoint returns an error if the supplied S3 endpoint is not // safe to dial from a server that has network access to cluster-internal // hosts. It rejects empty/non-http(s) schemes, loopback/link-local/ @@ -72,7 +61,7 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error { return fmt.Errorf("remote endpoint %q has no host", endpoint) } lowerHost := strings.ToLower(host) - if _, ok := blockedIMDSHosts[lowerHost]; ok { + if netguard.IsMetadataHost(lowerHost) { return fmt.Errorf("remote endpoint %q targets instance metadata service", endpoint) } if ip := net.ParseIP(host); ip != nil { @@ -83,7 +72,7 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error { } resolveCtx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() - addrs, lookupErr := lookupIPAddrFunc(resolveCtx, host) + addrs, lookupErr := netguard.LookupIPAddr(resolveCtx, host) if lookupErr != nil { return fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr) } @@ -95,57 +84,8 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error { return nil } -// imdsIPv4 is the AWS/Azure/GCP IPv4 IMDS address. It is link-local and is -// already covered by IsLinkLocalUnicast, but is named explicitly so the -// error message is unambiguous in logs. -var imdsIPv4 = net.ParseIP("169.254.169.254") - -// cgnatNet is the RFC 6598 carrier-grade NAT range (100.64.0.0/10). The -// stdlib's IsPrivate covers RFC 1918 but not CGNAT, so check it explicitly. -var cgnatNet = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} - func checkBlockedIP(endpoint string, ip net.IP) error { - return checkBlockedIPPolicy(endpoint, ip, false) -} - -// checkBlockedIPPolicy rejects addresses that must never be dialed from a -// server with cluster-internal reach. allowPrivate keeps RFC 1918 / CGNAT -// reachable for callers whose target legitimately sits on an internal network -// (peer volume servers), while still blocking loopback, link-local (IMDS) and -// unspecified. -func checkBlockedIPPolicy(endpoint string, ip net.IP, allowPrivate bool) error { - if ip == nil { - return nil - } - if ip.Equal(imdsIPv4) { - return fmt.Errorf("remote endpoint %q targets instance metadata service %s", endpoint, ip) - } - switch { - case ip.IsLoopback(): - return fmt.Errorf("remote endpoint %q resolves to loopback address %s", endpoint, ip) - case ip.IsUnspecified(): - return fmt.Errorf("remote endpoint %q resolves to unspecified address %s", endpoint, ip) - case ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(): - return fmt.Errorf("remote endpoint %q resolves to link-local address %s", endpoint, ip) - case ip.IsInterfaceLocalMulticast(): - return fmt.Errorf("remote endpoint %q resolves to interface-local address %s", endpoint, ip) - } - if !allowPrivate { - switch { - case ip.IsPrivate(): - return fmt.Errorf("remote endpoint %q resolves to private address %s", endpoint, ip) - case cgnatNet.Contains(ip): - return fmt.Errorf("remote endpoint %q resolves to CGNAT address %s", endpoint, ip) - } - } - // IPv6 transition addresses embed an IPv4 destination that routes to the - // same host wherever the matching relay exists (common in IPv6-only cloud). - // net.IP only normalizes ::ffff: mapped addresses, so pull the embedded - // IPv4 out of the other forms and re-check it against the deny list. - if embedded := embeddedTransitionIPv4(ip); embedded != nil { - return checkBlockedIPPolicy(endpoint, embedded, allowPrivate) - } - return nil + return netguard.CheckIP(endpoint, ip, netguard.Public) } // validateReplicaTarget rejects a peer volume server address that could @@ -169,110 +109,31 @@ func validateReplicaTarget(ctx context.Context, target string) error { if host == "" { return fmt.Errorf("replica target %q has no host", target) } - if _, ok := blockedIMDSHosts[strings.ToLower(host)]; ok { + if netguard.IsMetadataHost(host) { return fmt.Errorf("replica target %q targets instance metadata service", target) } if ip := net.ParseIP(host); ip != nil { - return checkBlockedIPPolicy(target, ip, true) + return netguard.CheckIP(target, ip, netguard.Private) } resolveCtx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() - addrs, lookupErr := lookupIPAddrFunc(resolveCtx, host) + addrs, lookupErr := netguard.LookupIPAddr(resolveCtx, host) if lookupErr != nil { return fmt.Errorf("resolve replica target host %q: %w", host, lookupErr) } for _, addr := range addrs { - if err := checkBlockedIPPolicy(target, addr.IP, true); err != nil { + if err := netguard.CheckIP(target, addr.IP, netguard.Private); err != nil { return err } } return nil } -// embeddedTransitionIPv4 returns the IPv4 address carried by an IPv6 transition -// address -- NAT64 64:ff9b::/96 (RFC 6052), 6to4 2002::/16 (RFC 3056), Teredo -// 2001:0000::/32 (RFC 4380), and the deprecated IPv4-compatible ::/96 (RFC -// 4291) -- or nil when ip is not one of those. IPv4-mapped ::ffff:0:0/96 is -// excluded because net.IP already normalizes it via To4. -func embeddedTransitionIPv4(ip net.IP) net.IP { - v6 := ip.To16() - if v6 == nil || ip.To4() != nil { - return nil - } - switch { - case v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && allZero(v6[4:12]): - return net.IPv4(v6[12], v6[13], v6[14], v6[15]) - case v6[0] == 0x20 && v6[1] == 0x02: - return net.IPv4(v6[2], v6[3], v6[4], v6[5]) - case v6[0] == 0x20 && v6[1] == 0x01 && v6[2] == 0x00 && v6[3] == 0x00: - // Teredo obfuscates the client IPv4 as its ones' complement. - return net.IPv4(v6[12]^0xff, v6[13]^0xff, v6[14]^0xff, v6[15]^0xff) - case allZero(v6[:12]): - // IPv4-compatible ::a.b.c.d; :: and ::1 are already handled above. - return net.IPv4(v6[12], v6[13], v6[14], v6[15]) - } - return nil -} - -func allZero(b []byte) bool { - for _, c := range b { - if c != 0 { - return false - } - } - return true -} - -// guardedDialer returns a DialContext that resolves the host itself and -// re-applies checkBlockedIP to every resolved address immediately before -// dialing. This closes the DNS-rebinding window between -// validateRemoteEndpoint and the actual TCP connect performed by the AWS S3 -// client: even if the attacker's DNS flips to 127.0.0.1 (or any other -// blocked range) after the up-front check, the dial is refused. +// guardedDialer returns a DialContext that refuses, at connect time, every +// address checkBlockedIP rejects, closing the DNS-rebinding window between +// validateRemoteEndpoint and the TCP connect performed by the AWS S3 client. func guardedDialer(endpoint string) func(ctx context.Context, network, addr string) (net.Conn, error) { - return guardedDialerPolicy(endpoint, false) -} - -// guardedDialerPolicy is guardedDialer with the same allowPrivate knob as -// checkBlockedIPPolicy, so the replica upload path can keep dialing private -// peers while still refusing loopback / link-local / unspecified at connect -// time (closing the rebinding window for replica hostnames too). -func guardedDialerPolicy(endpoint string, allowPrivate bool) func(ctx context.Context, network, addr string) (net.Conn, error) { - return func(ctx context.Context, network, addr string) (net.Conn, error) { - host, port, splitErr := net.SplitHostPort(addr) - if splitErr != nil { - return nil, splitErr - } - // If the host is already a literal IP just validate and dial it. - if ip := net.ParseIP(host); ip != nil { - if err := checkBlockedIPPolicy(endpoint, ip, allowPrivate); err != nil { - return nil, err - } - return util.OutboundDialContext(ctx, network, addr) - } - // Otherwise resolve, validate every answer, and dial the first IP - // that passes the deny list. Using a literal-IP target prevents the - // kernel resolver in net.Dialer from looking the name up a second - // time inside Dial and getting a different answer. - addrs, lookupErr := lookupIPAddrFunc(ctx, host) - if lookupErr != nil { - return nil, fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr) - } - var firstBlockErr error - for _, a := range addrs { - if err := checkBlockedIPPolicy(endpoint, a.IP, allowPrivate); err != nil { - if firstBlockErr == nil { - firstBlockErr = err - } - continue - } - return util.OutboundDialContext(ctx, network, net.JoinHostPort(a.IP.String(), port)) - } - if firstBlockErr != nil { - return nil, firstBlockErr - } - return nil, fmt.Errorf("resolve remote endpoint host %q: no addresses", host) - } + return netguard.DialContext(endpoint, netguard.Public) } // guardedGrpcDialOption returns a grpc.DialOption that re-applies the replica @@ -283,7 +144,7 @@ func (vs *VolumeServer) guardedGrpcDialOption(endpoint string) grpc.DialOption { if vs.AllowUntrustedRemoteEndpoints { return nil } - dial := guardedDialerPolicy(endpoint, true) + dial := netguard.DialContext(endpoint, netguard.Private) return grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { return dial(ctx, "tcp", addr) }) @@ -294,7 +155,7 @@ func (vs *VolumeServer) guardedGrpcDialOption(endpoint string) grpc.DialOption { // one remote configuration (BuildGuardedRemoteStorageClient caches it per // configuration); never share it across remote configs. func newGuardedHTTPClient(endpoint string) *http.Client { - client := newGuardedHTTPClientPolicy(endpoint, false) + client := newGuardedHTTPClientPolicy(endpoint, netguard.Public) if t, ok := client.Transport.(*http.Transport); ok { tuneSharedTransport(t) } @@ -427,10 +288,9 @@ func awsSharedFile(env, name string) string { return "" } -// newGuardedHTTPClientPolicy is newGuardedHTTPClient with the allowPrivate knob -// for the replica upload path, whose targets are cluster peers on private -// networks. -func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client { +// newGuardedHTTPClientPolicy is newGuardedHTTPClient with an address policy, +// so the replica upload path can reach cluster peers on private networks. +func newGuardedHTTPClientPolicy(endpoint string, policy netguard.Policy) *http.Client { return &http.Client{ Transport: &http.Transport{ // No proxy: guardedDialer must see the real target address. Through @@ -439,7 +299,7 @@ func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client // dialer exists to close. Operators that need a proxy can opt out // with -volume.allowUntrustedRemoteEndpoints. Proxy: nil, - DialContext: guardedDialerPolicy(endpoint, allowPrivate), + DialContext: netguard.DialContext(endpoint, policy), ForceAttemptHTTP2: true, MaxIdleConns: 16, IdleConnTimeout: 60 * time.Second, @@ -456,7 +316,7 @@ func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client // data and auth headers to plaintext. func newGuardedPeerHTTPClient(endpoint string) *http.Client { globalClient := util_http.GetGlobalHttpClient() - client := newGuardedHTTPClientPolicy(endpoint, true) + client := newGuardedHTTPClientPolicy(endpoint, netguard.Private) client.Transport.(*http.Transport).TLSClientConfig = globalClient.GetClientTransport().TLSClientConfig client.CheckRedirect = globalClient.Client.CheckRedirect @@ -655,7 +515,7 @@ func validateRemoteEndpointForLoad(endpoint string) error { if host == "" { return fmt.Errorf("remote endpoint %q has no host", endpoint) } - if _, ok := blockedIMDSHosts[strings.ToLower(host)]; ok { + if netguard.IsMetadataHost(host) { return fmt.Errorf("remote endpoint %q targets instance metadata service", endpoint) } if ip := net.ParseIP(host); ip != nil { diff --git a/weed/server/volume_grpc_remote_test.go b/weed/server/volume_grpc_remote_test.go index 38a8dfa752..c3f36181fe 100644 --- a/weed/server/volume_grpc_remote_test.go +++ b/weed/server/volume_grpc_remote_test.go @@ -28,6 +28,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/remote_storage" s3remote "github.com/seaweedfs/seaweedfs/weed/remote_storage/s3" util_http "github.com/seaweedfs/seaweedfs/weed/util/http" + "github.com/seaweedfs/seaweedfs/weed/util/netguard" ) // stubLookup returns a resolver func that maps the supplied hostnames to @@ -48,10 +49,10 @@ func stubLookup(t *testing.T, mapping map[string][]net.IP) func(ctx context.Cont } func TestValidateRemoteEndpoint(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) - lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{ + netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{ "s3.us-east-1.amazonaws.com": {net.ParseIP("52.216.10.10")}, "internal.example.com": {net.ParseIP("127.0.0.1")}, "linklocal.example.com": {net.ParseIP("169.254.10.20")}, @@ -269,11 +270,11 @@ func TestValidateRemoteEndpoint(t *testing.T) { } func TestValidateRemoteEndpointResolverFailure(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) resolveErr := errors.New("simulated DNS failure") - lookupIPAddrFunc = func(_ context.Context, _ string) ([]net.IPAddr, error) { + netguard.LookupIPAddr = func(_ context.Context, _ string) ([]net.IPAddr, error) { return nil, resolveErr } @@ -292,14 +293,14 @@ func TestValidateRemoteEndpointResolverFailure(t *testing.T) { // dial time). The dial path must refuse the loopback answer instead of // connecting to it. func TestGuardedDialerRebind(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) const host = "rebind.example.com" endpoint := "https://" + host + "/" var calls atomic.Int32 - lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) { + netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) { if name != host { return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} } @@ -399,10 +400,10 @@ func TestRemoteEndpointGuardCoversAzure(t *testing.T) { // host:port, since a scheme, path or query would move the upload to a different // URL through the format string. func TestValidateReplicaTarget(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) - lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{ + netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{ "peer.example.com": {net.ParseIP("10.0.0.7")}, "loop.example.com": {net.ParseIP("127.0.0.1")}, "linklocal.example.com": {net.ParseIP("169.254.169.254")}, @@ -497,9 +498,9 @@ func TestGuardedRemoteClientAzureBuildsGuardedClient(t *testing.T) { // inline gcs credentials is the endpoint the guard validates, so a loopback // token_uri is refused while the Google default passes. func TestGuardedRemoteClientGuardsGcsTokenURL(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) - lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{ + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) + netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{ "oauth2.googleapis.com": {net.ParseIP("142.250.72.10")}, }) @@ -568,9 +569,9 @@ func TestCheckGcsCredentials(t *testing.T) { // TestGuardedDialerLiteralBlocked confirms that a literal blocked IP target // is refused without any DNS lookup. func TestGuardedDialerLiteralBlocked(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) - lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) { + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) + netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) { t.Fatalf("resolver should not be called for IP literal target, got lookup of %q", name) return nil, nil } @@ -588,14 +589,14 @@ func TestGuardedDialerLiteralBlocked(t *testing.T) { // TestGuardedReplicaDialerRebind confirms the replica upload's dial-time guard // refuses a hostname that rebinds to loopback after validateReplicaTarget, yet -// keeps letting private peers through (allowPrivate). +// keeps letting private peers through (netguard.Private). func TestGuardedReplicaDialerRebind(t *testing.T) { - originalLookup := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = originalLookup }) + originalLookup := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = originalLookup }) const host = "replica.example.com" var calls atomic.Int32 - lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) { + netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) { if name != host { return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} } @@ -610,7 +611,7 @@ func TestGuardedReplicaDialerRebind(t *testing.T) { t.Fatalf("public replica target should validate, got %v", err) } // The dial then re-resolves to loopback and must refuse it. - dial := guardedDialerPolicy(host+":8080", true) + dial := netguard.DialContext(host+":8080", netguard.Private) conn, err := dial(context.Background(), "tcp", host+":8080") if conn != nil { conn.Close() @@ -624,7 +625,7 @@ func TestGuardedReplicaDialerRebind(t *testing.T) { // fails on the already-cancelled context) rather than blocked as private. ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, perr := guardedDialerPolicy("10.0.0.5:80", true)(ctx, "tcp", "10.0.0.5:80"); perr != nil && strings.Contains(perr.Error(), "private") { + if _, perr := netguard.DialContext("10.0.0.5:80", netguard.Private)(ctx, "tcp", "10.0.0.5:80"); perr != nil && strings.Contains(perr.Error(), "private") { t.Fatalf("private peer must be allowed by the replica dialer, got %v", perr) } } @@ -998,11 +999,11 @@ func guardedCacheTest(t *testing.T, ips map[string][]net.IP) *atomic.Int64 { t.Helper() remote_storage.ResetRemoteStorageClients() t.Cleanup(remote_storage.ResetRemoteStorageClients) - original := lookupIPAddrFunc - t.Cleanup(func() { lookupIPAddrFunc = original }) + original := netguard.LookupIPAddr + t.Cleanup(func() { netguard.LookupIPAddr = original }) var lookups atomic.Int64 stub := stubLookup(t, ips) - lookupIPAddrFunc = func(ctx context.Context, host string) ([]net.IPAddr, error) { + netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) { lookups.Add(1) return stub(ctx, host) } diff --git a/weed/stats/metrics.go b/weed/stats/metrics.go index 449451850f..40e663e451 100644 --- a/weed/stats/metrics.go +++ b/weed/stats/metrics.go @@ -930,6 +930,46 @@ var ( Buckets: prometheus.ExponentialBuckets(0.001, 2, 12), }) + S3NotificationDeliveredCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "notification_delivered_records_total", + Help: "Bucket event records a forwarder delivered to its target.", + }, []string{"target"}) + + S3NotificationSendRetriesCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "notification_send_retries_total", + Help: "Sends to a target that failed and are retried.", + }, []string{"target"}) + + S3NotificationRetentionGapCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "notification_retention_gap_records_total", + Help: "Bucket event records retention removed from a target's topic before they were delivered.", + }, []string{"target"}) + + S3NotificationSkippedCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "notification_skipped_records_total", + Help: "Bucket event records a forwarder skipped because they cannot be decoded or rendered.", + }, []string{"target", "reason"}) + + S3NotificationLagGauge = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "notification_lag_records", + Help: "Undelivered bucket event records the gateway forwarding a target can see: current ranges, ranges held back behind an older generation, and sealed retired ranges; an old range still being sealed after a repartition is not counted.", + }, []string{"target"}) + S3BucketSizeBytesGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: Namespace, @@ -1296,6 +1336,11 @@ func init() { Gather.MustRegister(S3NotificationRecordsLateCounter) Gather.MustRegister(S3NotificationQueueDepthGauge) Gather.MustRegister(S3NotificationPublishWaitHistogram) + Gather.MustRegister(S3NotificationDeliveredCounter) + Gather.MustRegister(S3NotificationSendRetriesCounter) + Gather.MustRegister(S3NotificationRetentionGapCounter) + Gather.MustRegister(S3NotificationSkippedCounter) + Gather.MustRegister(S3NotificationLagGauge) Gather.MustRegister(S3BucketSizeBytesGauge) Gather.MustRegister(S3BucketPhysicalSizeBytesGauge) Gather.MustRegister(S3BucketObjectCountGauge) diff --git a/weed/util/netguard/netguard.go b/weed/util/netguard/netguard.go new file mode 100644 index 0000000000..ee7c7d3454 --- /dev/null +++ b/weed/util/netguard/netguard.go @@ -0,0 +1,176 @@ +// Package netguard refuses outbound connections to addresses a server with +// cluster-internal reach must not be steered to, such as the cloud instance +// metadata service. +package netguard + +import ( + "context" + "fmt" + "net" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// LookupIPAddr resolves a host to one or more IP addresses. It is a variable +// so tests can substitute a deterministic resolver. +var LookupIPAddr = net.DefaultResolver.LookupIPAddr + +// Policy is which addresses besides public ones a connection may reach. +// Metadata-service, link-local, unspecified and interface-local addresses are +// refused under every policy. +type Policy int + +const ( + // Public allows only public addresses. + Public Policy = iota + // Private also allows RFC 1918 and CGNAT addresses, where cluster peers + // legitimately sit. + Private + // Local also allows loopback, for endpoints an operator configured, which + // may be a sidecar on the same host. + Local +) + +// blockedIMDSHosts lists hostnames that target cloud instance metadata +// services (IMDS). These are blocked regardless of how they happen to +// resolve, because some environments alias the IMDS address under a name. +var blockedIMDSHosts = map[string]struct{}{ + "metadata.google.internal": {}, + "metadata": {}, +} + +// IsMetadataHost reports whether host names a cloud instance metadata service. +func IsMetadataHost(host string) bool { + _, ok := blockedIMDSHosts[strings.ToLower(host)] + return ok +} + +// metadataIPs are instance metadata service addresses. 169.254.169.254 is +// link-local and already refused, but is named so the log is unambiguous. +// AWS's IPv6 fd00:ec2::254 is unique-local and Alibaba's 100.100.100.200 is in +// the CGNAT range, so the Private and Local policies would otherwise allow them. +var metadataIPs = []net.IP{ + net.ParseIP("169.254.169.254"), + net.ParseIP("fd00:ec2::254"), + net.ParseIP("100.100.100.200"), +} + +// cgnatNet is the RFC 6598 carrier-grade NAT range (100.64.0.0/10). The +// stdlib's IsPrivate covers RFC 1918 but not CGNAT, so check it explicitly. +var cgnatNet = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} + +// CheckIP rejects an address that policy does not let endpoint reach. +func CheckIP(endpoint string, ip net.IP, policy Policy) error { + if ip == nil { + return nil + } + for _, metadataIP := range metadataIPs { + if ip.Equal(metadataIP) { + return fmt.Errorf("remote endpoint %q targets instance metadata service %s", endpoint, ip) + } + } + switch { + case ip.IsLoopback() && policy != Local: + return fmt.Errorf("remote endpoint %q resolves to loopback address %s", endpoint, ip) + case ip.IsUnspecified(): + return fmt.Errorf("remote endpoint %q resolves to unspecified address %s", endpoint, ip) + case ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(): + return fmt.Errorf("remote endpoint %q resolves to link-local address %s", endpoint, ip) + case ip.IsInterfaceLocalMulticast(): + return fmt.Errorf("remote endpoint %q resolves to interface-local address %s", endpoint, ip) + } + if policy == Public { + switch { + case ip.IsPrivate(): + return fmt.Errorf("remote endpoint %q resolves to private address %s", endpoint, ip) + case cgnatNet.Contains(ip): + return fmt.Errorf("remote endpoint %q resolves to CGNAT address %s", endpoint, ip) + } + } + // IPv6 transition addresses embed an IPv4 destination that routes to the + // same host wherever the matching relay exists (common in IPv6-only cloud). + // net.IP only normalizes ::ffff: mapped addresses, so pull the embedded + // IPv4 out of the other forms and re-check it against the deny list. + if embedded := embeddedTransitionIPv4(ip); embedded != nil { + return CheckIP(endpoint, embedded, policy) + } + return nil +} + +// embeddedTransitionIPv4 returns the IPv4 address carried by an IPv6 transition +// address -- NAT64 64:ff9b::/96 (RFC 6052), 6to4 2002::/16 (RFC 3056), Teredo +// 2001:0000::/32 (RFC 4380), and the deprecated IPv4-compatible ::/96 (RFC +// 4291) -- or nil when ip is not one of those. IPv4-mapped ::ffff:0:0/96 is +// excluded because net.IP already normalizes it via To4. +func embeddedTransitionIPv4(ip net.IP) net.IP { + v6 := ip.To16() + if v6 == nil || ip.To4() != nil { + return nil + } + switch { + case v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && allZero(v6[4:12]): + return net.IPv4(v6[12], v6[13], v6[14], v6[15]) + case v6[0] == 0x20 && v6[1] == 0x02: + return net.IPv4(v6[2], v6[3], v6[4], v6[5]) + case v6[0] == 0x20 && v6[1] == 0x01 && v6[2] == 0x00 && v6[3] == 0x00: + // Teredo obfuscates the client IPv4 as its ones' complement. + return net.IPv4(v6[12]^0xff, v6[13]^0xff, v6[14]^0xff, v6[15]^0xff) + case allZero(v6[:12]): + // IPv4-compatible ::a.b.c.d; :: and ::1 are already handled above. + return net.IPv4(v6[12], v6[13], v6[14], v6[15]) + } + return nil +} + +func allZero(b []byte) bool { + for _, c := range b { + if c != 0 { + return false + } + } + return true +} + +// DialContext returns a DialContext that resolves the host itself and applies +// CheckIP to every resolved address immediately before dialing. This closes +// the DNS-rebinding window between an up-front check of endpoint and the +// actual TCP connect: even if its DNS flips to a blocked address afterwards, +// the dial is refused. +func DialContext(endpoint string, policy Policy) func(ctx context.Context, network, addr string) (net.Conn, error) { + return func(ctx context.Context, network, addr string) (net.Conn, error) { + host, port, splitErr := net.SplitHostPort(addr) + if splitErr != nil { + return nil, splitErr + } + // If the host is already a literal IP just validate and dial it. + if ip := net.ParseIP(host); ip != nil { + if err := CheckIP(endpoint, ip, policy); err != nil { + return nil, err + } + return util.OutboundDialContext(ctx, network, addr) + } + // Otherwise resolve, validate every answer, and dial the first IP + // that passes the deny list. Using a literal-IP target prevents the + // kernel resolver in net.Dialer from looking the name up a second + // time inside Dial and getting a different answer. + addrs, lookupErr := LookupIPAddr(ctx, host) + if lookupErr != nil { + return nil, fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr) + } + var firstBlockErr error + for _, a := range addrs { + if err := CheckIP(endpoint, a.IP, policy); err != nil { + if firstBlockErr == nil { + firstBlockErr = err + } + continue + } + return util.OutboundDialContext(ctx, network, net.JoinHostPort(a.IP.String(), port)) + } + if firstBlockErr != nil { + return nil, firstBlockErr + } + return nil, fmt.Errorf("resolve remote endpoint host %q: no addresses", host) + } +} diff --git a/weed/util/netguard/netguard_test.go b/weed/util/netguard/netguard_test.go new file mode 100644 index 0000000000..6b7b7e928d --- /dev/null +++ b/weed/util/netguard/netguard_test.go @@ -0,0 +1,36 @@ +package netguard + +import ( + "net" + "testing" +) + +func TestCheckIPByPolicy(t *testing.T) { + cases := []struct { + ip string + public, private, local bool + }{ + {"8.8.8.8", true, true, true}, + {"10.1.2.3", false, true, true}, + {"100.64.0.1", false, true, true}, + {"127.0.0.1", false, false, true}, + {"::1", false, false, true}, + {"169.254.169.254", false, false, false}, + {"169.254.1.1", false, false, false}, + {"fe80::1", false, false, false}, + {"0.0.0.0", false, false, false}, + {"64:ff9b::a9fe:a9fe", false, false, false}, + {"fd00:ec2::254", false, false, false}, + {"fd00::1", false, true, true}, + {"100.100.100.200", false, false, false}, + {"64:ff9b::6464:64c8", false, false, false}, + } + for _, c := range cases { + ip := net.ParseIP(c.ip) + for policy, want := range map[Policy]bool{Public: c.public, Private: c.private, Local: c.local} { + if got := CheckIP("e", ip, policy) == nil; got != want { + t.Errorf("%s under policy %d: allowed %v, want %v", c.ip, policy, got, want) + } + } + } +}