package s3notification import ( "encoding/json" "errors" "fmt" "net/url" "strings" "time" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" ) const ( EventObjectCreatedPut = "s3:ObjectCreated:Put" EventObjectCreatedPost = "s3:ObjectCreated:Post" EventObjectCreatedCopy = "s3:ObjectCreated:Copy" EventObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload" EventObjectRemovedDelete = "s3:ObjectRemoved:Delete" EventObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated" EventTest = "s3:TestEvent" recordEventVersion = "2.7" recordEventSource = "aws:s3" recordSchema = "1.0" eventTimeLayout = "2006-01-02T15:04:05.000Z" ) // Columns of a notification topic's records. const ( ColumnEventVersion = "event_version" ColumnEventSource = "event_source" ColumnAwsRegion = "aws_region" ColumnEventTime = "event_time" ColumnEventName = "event_name" ColumnPrincipalID = "principal_id" ColumnSourceIP = "source_ip" ColumnRequestID = "request_id" ColumnHostID = "host_id" ColumnConfigurationID = "configuration_id" ColumnBucketName = "bucket_name" ColumnBucketOwner = "bucket_owner" ColumnBucketARN = "bucket_arn" ColumnObjectKey = "object_key" ColumnObjectSize = "object_size" ColumnObjectETag = "object_etag" ColumnObjectVersionID = "object_version_id" ColumnSequencer = "sequencer" ColumnUploadID = "upload_id" ColumnPartNumber = "part_number" ColumnPartSize = "part_size" ColumnPartETag = "part_etag" ) // EventKeyColumns are the record type's key columns: one object's events. var EventKeyColumns = []string{ColumnBucketName, ColumnObjectKey} // EventRecordType is the record type of every notification topic. Changes // must be additive: append columns, never rename, retype or reorder them. func EventRecordType() *schema_pb.RecordType { columns := []struct { name string kind schema_pb.ScalarType required bool }{ {ColumnEventVersion, schema_pb.ScalarType_STRING, false}, {ColumnEventSource, schema_pb.ScalarType_STRING, false}, {ColumnAwsRegion, schema_pb.ScalarType_STRING, false}, {ColumnEventTime, schema_pb.ScalarType_TIMESTAMP, true}, {ColumnEventName, schema_pb.ScalarType_STRING, true}, {ColumnPrincipalID, schema_pb.ScalarType_STRING, false}, {ColumnSourceIP, schema_pb.ScalarType_STRING, false}, {ColumnRequestID, schema_pb.ScalarType_STRING, false}, {ColumnHostID, schema_pb.ScalarType_STRING, false}, {ColumnConfigurationID, schema_pb.ScalarType_STRING, false}, {ColumnBucketName, schema_pb.ScalarType_STRING, true}, {ColumnBucketOwner, schema_pb.ScalarType_STRING, false}, {ColumnBucketARN, schema_pb.ScalarType_STRING, false}, {ColumnObjectKey, schema_pb.ScalarType_STRING, false}, {ColumnObjectSize, schema_pb.ScalarType_INT64, false}, {ColumnObjectETag, schema_pb.ScalarType_STRING, false}, {ColumnObjectVersionID, schema_pb.ScalarType_STRING, false}, {ColumnSequencer, schema_pb.ScalarType_INT64, false}, {ColumnUploadID, schema_pb.ScalarType_STRING, false}, {ColumnPartNumber, schema_pb.ScalarType_INT32, false}, {ColumnPartSize, schema_pb.ScalarType_INT64, false}, {ColumnPartETag, schema_pb.ScalarType_STRING, false}, } recordType := &schema_pb.RecordType{Fields: make([]*schema_pb.Field, len(columns))} for i, c := range columns { recordType.Fields[i] = &schema_pb.Field{ Name: c.name, FieldIndex: int32(i), Type: &schema_pb.Type{Kind: &schema_pb.Type_ScalarType{ScalarType: c.kind}}, IsRequired: c.required, } } return recordType } // Event is what one S3 operation did to one object, the input to its records. type Event struct { Name string // with the s3: prefix, as configurations list it Region string Bucket string BucketOwner string Key string Size int64 ETag string VersionID string Principal string SourceIP string RequestID string // LogTsNs is the filer's stamp of the commit; it orders one key's events. LogTsNs int64 } // RecordValue is the event's record for the rule configurationID. Unknown // values are left out, so they read as null. func (e *Event) RecordValue(configurationID string) *schema_pb.RecordValue { r := &schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{}} setString(r, ColumnEventVersion, recordEventVersion) setString(r, ColumnEventSource, recordEventSource) setString(r, ColumnAwsRegion, e.Region) setTime(r, e.LogTsNs) setString(r, ColumnEventName, strings.TrimPrefix(e.Name, "s3:")) setString(r, ColumnPrincipalID, e.Principal) setString(r, ColumnSourceIP, e.SourceIP) setString(r, ColumnRequestID, e.RequestID) setString(r, ColumnConfigurationID, configurationID) setString(r, ColumnBucketName, e.Bucket) setString(r, ColumnBucketOwner, e.BucketOwner) setString(r, ColumnBucketARN, "arn:aws:s3:::"+e.Bucket) setString(r, ColumnObjectKey, e.Key) if !strings.HasPrefix(e.Name, "s3:ObjectRemoved:") { r.Fields[ColumnObjectSize] = &schema_pb.Value{Kind: &schema_pb.Value_Int64Value{Int64Value: e.Size}} setString(r, ColumnObjectETag, strings.Trim(e.ETag, `"`)) } setString(r, ColumnObjectVersionID, e.VersionID) r.Fields[ColumnSequencer] = &schema_pb.Value{Kind: &schema_pb.Value_Int64Value{Int64Value: e.LogTsNs}} return r } // TestEventRecord is the s3:TestEvent a destination receives when a // configuration naming it is stored. func TestEventRecord(bucket, requestID string, tsNs int64) *schema_pb.RecordValue { r := &schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{}} setTime(r, tsNs) setString(r, ColumnEventName, EventTest) setString(r, ColumnBucketName, bucket) setString(r, ColumnRequestID, requestID) return r } // MessageKey keys an object's records so its events share one partition. func MessageKey(bucket, key string) []byte { return []byte(bucket + "/" + key) } func setString(r *schema_pb.RecordValue, column, value string) { if value != "" { r.Fields[column] = &schema_pb.Value{Kind: &schema_pb.Value_StringValue{StringValue: value}} } } func setTime(r *schema_pb.RecordValue, tsNs int64) { r.Fields[ColumnEventTime] = &schema_pb.Value{Kind: &schema_pb.Value_TimestampValue{ TimestampValue: &schema_pb.TimestampValue{TimestampMicros: tsNs / int64(time.Microsecond), IsUtc: true}, }} } // The rendering below is the AWS JSON a destination receives. type Identity struct { PrincipalID string `json:"principalId"` } type Record struct { EventVersion string `json:"eventVersion"` EventSource string `json:"eventSource"` AwsRegion string `json:"awsRegion"` EventTime string `json:"eventTime"` EventName string `json:"eventName"` UserIdentity Identity `json:"userIdentity"` RequestParameters map[string]string `json:"requestParameters"` ResponseElements map[string]string `json:"responseElements"` S3 RecordS3 `json:"s3"` } type RecordS3 struct { SchemaVersion string `json:"s3SchemaVersion"` ConfigurationID string `json:"configurationId"` Bucket RecordBucket `json:"bucket"` Object RecordObject `json:"object"` } type RecordBucket struct { Name string `json:"name"` OwnerIdentity Identity `json:"ownerIdentity"` ARN string `json:"arn"` } type RecordObject struct { Key string `json:"key"` Size *int64 `json:"size,omitempty"` ETag string `json:"eTag,omitempty"` VersionID string `json:"versionId,omitempty"` Sequencer string `json:"sequencer"` } // Records is the envelope AWS delivers records in. type Records struct { Records []Record `json:"Records"` } type TestEvent struct { Service string `json:"Service"` Event string `json:"Event"` Time string `json:"Time"` Bucket string `json:"Bucket"` RequestID string `json:"RequestId"` HostID string `json:"HostId"` } var errTestEventInBatch = errors.New("an s3:TestEvent renders alone") // IsTestEvent reports whether a record is an s3:TestEvent. func IsTestEvent(r *schema_pb.RecordValue) bool { return stringField(r, ColumnEventName) == EventTest } // Render turns records into the JSON body a destination receives: the // {"Records":[...]} envelope, or the test event message for a single // s3:TestEvent, which never shares a body with other records. func Render(records ...*schema_pb.RecordValue) ([]byte, error) { if len(records) == 1 && IsTestEvent(records[0]) { r := records[0] return json.Marshal(TestEvent{ Service: "Amazon S3", Event: EventTest, Time: eventTime(r), Bucket: stringField(r, ColumnBucketName), RequestID: stringField(r, ColumnRequestID), HostID: stringField(r, ColumnHostID), }) } body := Records{Records: make([]Record, 0, len(records))} for _, r := range records { if IsTestEvent(r) { return nil, errTestEventInBatch } body.Records = append(body.Records, renderRecord(r)) } return json.Marshal(body) } func renderRecord(r *schema_pb.RecordValue) Record { object := RecordObject{ Key: EncodeKey(stringField(r, ColumnObjectKey)), ETag: stringField(r, ColumnObjectETag), VersionID: stringField(r, ColumnObjectVersionID), Sequencer: Sequencer(r.Fields[ColumnSequencer].GetInt64Value()), } if size, ok := r.Fields[ColumnObjectSize]; ok { v := size.GetInt64Value() object.Size = &v } responseElements := map[string]string{} if id := stringField(r, ColumnRequestID); id != "" { responseElements["x-amz-request-id"] = id } if id := stringField(r, ColumnHostID); id != "" { responseElements["x-amz-id-2"] = id } return Record{ EventVersion: stringField(r, ColumnEventVersion), EventSource: stringField(r, ColumnEventSource), AwsRegion: stringField(r, ColumnAwsRegion), EventTime: eventTime(r), EventName: stringField(r, ColumnEventName), UserIdentity: Identity{PrincipalID: stringField(r, ColumnPrincipalID)}, RequestParameters: map[string]string{"sourceIPAddress": stringField(r, ColumnSourceIP)}, ResponseElements: responseElements, S3: RecordS3{ SchemaVersion: recordSchema, ConfigurationID: stringField(r, ColumnConfigurationID), Bucket: RecordBucket{ Name: stringField(r, ColumnBucketName), OwnerIdentity: Identity{PrincipalID: stringField(r, ColumnBucketOwner)}, ARN: stringField(r, ColumnBucketARN), }, Object: object, }, } } func stringField(r *schema_pb.RecordValue, column string) string { return r.GetFields()[column].GetStringValue() } func eventTime(r *schema_pb.RecordValue) string { micros := r.GetFields()[ColumnEventTime].GetTimestampValue().GetTimestampMicros() return time.UnixMicro(micros).UTC().Format(eventTimeLayout) } // Sequencer renders a commit stamp as fixed-width hex, so sequencers compare as strings. func Sequencer(tsNs int64) string { return fmt.Sprintf("%016X", uint64(tsNs)) } // EncodeKey form-encodes each path segment of an object key, as AWS records // carry it: a space becomes '+', the '/' separators stay. func EncodeKey(key string) string { segments := strings.Split(key, "/") for i, segment := range segments { segments[i] = url.QueryEscape(segment) } return strings.Join(segments, "/") }