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" "github.com/seaweedfs/seaweedfs/weed/s3api/s3notification" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" "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 // notificationPublisher is what the gateway needs from s3notification.Publisher. type notificationPublisher interface { Sync(reg *s3notification.Registry) Publish(ctx context.Context, messages []s3notification.Message) bool Close() } // newNotificationPublisher returns nil, leaving notifications off, when the // grpc.msg_broker client TLS config is unusable: the gateway keeps serving, // and never talks to a broker without the TLS it was configured to use. func (s3a *S3ApiServer) newNotificationPublisher() notificationPublisher { dialOption, err := security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker") if err != nil { glog.Errorf("bucket notifications are off: %v", err) return nil } 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 { var brokers []string seen := map[string]bool{} add := func(address string) { if address != "" && !seen[address] { seen[address] = true brokers = append(brokers, address) } } add(string(s3a.option.MqBroker)) if s3a.masterClient == nil { return brokers } ctx, cancel := context.WithTimeout(context.Background(), notificationBrokerListTimeout) defer cancel() err := s3a.masterClient.WithClient(ctx, false, func(client master_pb.SeaweedClient) error { resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{ ClientType: cluster.BrokerType, FilerGroup: s3a.option.FilerGroup, }) if err != nil { return err } for _, node := range resp.ClusterNodes { add(node.Address) } return nil }) if err != nil { glog.V(1).Infof("list message queue brokers: %v", err) } return brokers } // sendNotificationTestEvents publishes s3:TestEvent to the topic of every // target config names and returns the destinations whose target did not ack // it within the publisher's wait. func (s3a *S3ApiServer) sendNotificationTestEvents(r *http.Request, bucket string, config *s3notification.Configuration) []string { destinations := map[string][]string{} for _, rule := range config.Rules { destinations[rule.Target] = append(destinations[rule.Target], rule.Destination) } if len(destinations) == 0 { return nil } value := s3notification.TestEventRecord(bucket, request_id.GetFromRequest(r), time.Now().UnixNano()) var mu sync.Mutex var failed []string var wg sync.WaitGroup for target, arns := range destinations { wg.Add(1) go func() { defer wg.Done() message := s3notification.Message{Target: target, Key: s3notification.MessageKey(bucket, ""), Value: value} if s3a.notificationPublisher != nil && s3a.notificationPublisher.Publish(r.Context(), []s3notification.Message{message}) { return } mu.Lock() failed = append(failed, arns...) mu.Unlock() }() } wg.Wait() slices.Sort(failed) return slices.Compact(failed) } // objectCommit is what a request committed to the filer, noted where the // commit happens, which can be far below the handler that publishes the event. type objectCommit struct { mu sync.Mutex wrote bool logTsNs int64 size int64 } type objectCommitKey struct{} // withObjectCommit gives r somewhere for noteObjectCommit to record into. func withObjectCommit(r *http.Request) (*http.Request, *objectCommit) { commit := &objectCommit{} return r.WithContext(context.WithValue(r.Context(), objectCommitKey{}, commit)), commit } // noteObjectCommit records a commit's filer stamp, 0 when the write path did // not return one, and the size of the object it committed. func noteObjectCommit(ctx context.Context, logTsNs, size int64) { commit, _ := ctx.Value(objectCommitKey{}).(*objectCommit) if commit == nil { return } commit.mu.Lock() defer commit.mu.Unlock() commit.wrote = true commit.logTsNs = max(commit.logTsNs, logTsNs) commit.size = size } // committed reports whether the request committed anything; a retried // request answered from an earlier commit did not. func (c *objectCommit) committed() bool { c.mu.Lock() defer c.mu.Unlock() return c.wrote } func (c *objectCommit) noted() (logTsNs, size int64) { c.mu.Lock() defer c.mu.Unlock() return c.logTsNs, c.size } // publishObjectEvent publishes each event once per rule of its bucket's // configuration that matches it, and waits for all the acks within the // publisher's bound. It never fails the request: what is not acked stays // queued or is counted as dropped. func (s3a *S3ApiServer) publishObjectEvent(r *http.Request, events ...s3notification.Event) { if s3a.notificationPublisher == nil { return } var messages []s3notification.Message for _, event := range events { config, errCode := s3a.getBucketConfig(event.Bucket) if errCode != s3err.ErrNone || config.Notification == nil { continue } matches := config.Notification.Match(event.Name, event.Key) if len(matches) == 0 { continue } event.Region = s3tables.DefaultRegion event.BucketOwner = config.Owner event.Principal = notificationPrincipal(r) event.SourceIP = s3err.RemoteIP(r) event.RequestID = request_id.GetFromRequest(r) if event.LogTsNs == 0 { // Write paths that do not return the filer's stamp take the gateway's // clock, which orders one key's events only on this gateway. event.LogTsNs = time.Now().UnixNano() } registry := s3a.notificationTargetRegistry() for _, match := range matches { if _, ok := registry.Resolve(match.Target, event.Bucket); !ok { glog.V(1).Infof("bucket %s notification rule %s: target %s no longer resolves", event.Bucket, match.ID, match.Target) continue } messages = append(messages, s3notification.Message{ Target: match.Target, Key: s3notification.MessageKey(event.Bucket, event.Key), Value: event.RecordValue(match.ID), }) } } s3a.notificationPublisher.Publish(r.Context(), messages) } // notificationPrincipal is the authenticated identity, never a request // header: with auth off, s3-account-id comes straight from the client. func notificationPrincipal(r *http.Request) string { if name := s3_constants.GetIdentityNameFromContext(r); name != "" { return name } return s3_constants.AccountAnonymousId } // 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) } }