package iceberg import ( "context" "errors" "fmt" "math" "path" "strings" "time" "github.com/seaweedfs/seaweedfs/weed/cluster" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/mq/topictable" "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/plugin_pb" pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" "github.com/seaweedfs/seaweedfs/weed/security" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" ) const ( topicTableJobType = "mq_topic_table" // a table-backed topic is due once a partition has this much sealed and not yet copied topicTableDueBytes = 128 << 20 // or once its oldest such file is this old topicTableDueAge = 5 * time.Minute topicTableLockTTL = 30 * time.Second topicTableLockWait = time.Minute ) func init() { pluginworker.RegisterHandler(pluginworker.HandlerFactory{ JobType: topicTableJobType, Category: pluginworker.CategoryHeavy, Aliases: []string{"mq-topic-table", "topic_table"}, Build: func(opts pluginworker.HandlerBuildOptions) (pluginworker.JobHandler, error) { return NewTopicTableHandler(opts.GrpcDialOption), nil }, }) } // TopicTableHandler copies the sealed log data of MQ topics that name an // Iceberg table into that table, exactly once per offset. type TopicTableHandler struct { maintenance *Handler } func NewTopicTableHandler(grpcDialOption grpc.DialOption) *TopicTableHandler { return &TopicTableHandler{maintenance: NewHandler(grpcDialOption)} } func (h *TopicTableHandler) Capability() *plugin_pb.JobTypeCapability { return &plugin_pb.JobTypeCapability{ JobType: topicTableJobType, CanDetect: true, CanExecute: true, MaxDetectionConcurrency: 1, MaxExecutionConcurrency: 4, DisplayName: "MQ Topic Tables", Description: "Copies the sealed messages of topics that name an Iceberg table into that table", Weight: 50, } } func (h *TopicTableHandler) Descriptor() *plugin_pb.JobTypeDescriptor { return &plugin_pb.JobTypeDescriptor{ JobType: topicTableJobType, DisplayName: "MQ Topic Tables", Description: "Appends each table-backed topic's sealed log data to its Iceberg table once a partition has 128 MiB of it or its oldest file is 5 minutes old, recording the copied offsets in the snapshot summary.", Icon: "fas fa-table", DescriptorVersion: 1, AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{ Enabled: true, DetectionIntervalMinutes: 1, DetectionTimeoutSeconds: 120, MaxJobsPerDetection: 100, GlobalExecutionConcurrency: 4, PerWorkerExecutionConcurrency: 2, RetryLimit: 1, RetryBackoffSeconds: 60, JobTypeMaxRuntimeSeconds: 3600, ExecutionTimeoutSeconds: 3600, }, WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{}, } } func (h *TopicTableHandler) Detect(ctx context.Context, request *plugin_pb.RunDetectionRequest, sender pluginworker.DetectionSender) error { if request == nil || sender == nil { return fmt.Errorf("detect: nil request or sender") } if request.JobType != "" && request.JobType != topicTableJobType { return fmt.Errorf("job type %q is not handled by the topic table handler", request.JobType) } filers := pluginworker.ClusterFilerAddresses(request.GetClusterContext()) if len(filers) == 0 { _ = sender.SendActivity(pluginworker.BuildDetectorActivity("skipped", "no filer addresses in cluster context", nil)) return sender.SendComplete(&plugin_pb.DetectionComplete{JobType: topicTableJobType, Success: true}) } addresses := make([]string, len(filers)) for i, filerAddress := range filers { addresses[i] = filerAddress.ToGrpcAddress() } grpcAddress, conn, err := h.maintenance.connectToFiler(ctx, addresses) if err != nil { return fmt.Errorf("connect to filer: %w", err) } defer conn.Close() filerAddress := filers[0] for _, candidate := range filers { if candidate.ToGrpcAddress() == grpcAddress { filerAddress = candidate } } client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)) due, scanErrors := scanTopicTables(ctx, client, time.Now()) for _, scanErr := range scanErrors { _ = sender.SendActivity(pluginworker.BuildDetectorActivity("scan_error", scanErr, nil)) } maxResults := int(request.MaxResults) hasMore := maxResults > 0 && len(due) > maxResults if hasMore { due = due[:maxResults] } proposals := make([]*plugin_pb.JobProposal, 0, len(due)) for _, d := range due { proposals = append(proposals, &plugin_pb.JobProposal{ JobType: topicTableJobType, ProposalId: fmt.Sprintf("mq-topic-table-%s-%s-%d", d.topic.Namespace, d.topic.Name, time.Now().UnixNano()), DedupeKey: fmt.Sprintf("%s:%s/%s", topicTableJobType, d.topic.Namespace, d.topic.Name), Priority: plugin_pb.JobPriority_JOB_PRIORITY_NORMAL, Summary: fmt.Sprintf("Copy topic %s to table %s.%s: %s", d.topic, d.table.Namespace, d.table.Name, d.reason), Parameters: map[string]*plugin_pb.ConfigValue{ "topic_namespace": stringValue(d.topic.Namespace), "topic_name": stringValue(d.topic.Name), "table_bucket_arn": stringValue(d.table.TableBucketArn), "table_namespace": stringValue(d.table.Namespace), "table_name": stringValue(d.table.Name), "filer_address": stringValue(string(filerAddress)), }, }) } if err := sender.SendProposals(&plugin_pb.DetectionProposals{JobType: topicTableJobType, Proposals: proposals, HasMore: hasMore}); err != nil { return err } return sender.SendComplete(&plugin_pb.DetectionComplete{ JobType: topicTableJobType, Success: len(scanErrors) == 0, ErrorMessage: strings.Join(scanErrors, "; "), TotalProposals: int32(len(proposals)), }) } func stringValue(s string) *plugin_pb.ConfigValue { return &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_StringValue{StringValue: s}} } type topicTableDue struct { topic topic.Topic table *mq_pb.TopicTable reason string } // scanTopicTables finds every topic naming a table that has a partition due // for a copy. A topic that cannot be read is reported and passed over. func scanTopicTables(ctx context.Context, client filer_pb.SeaweedFilerClient, now time.Time) (due []topicTableDue, scanErrors []string) { namespaces, err := listDirNames(ctx, client, filer.TopicsDir) if err != nil { return nil, []string{fmt.Sprintf("list %s: %v", filer.TopicsDir, err)} } for _, namespace := range namespaces { names, err := listDirNames(ctx, client, path.Join(filer.TopicsDir, namespace)) if err != nil { scanErrors = append(scanErrors, fmt.Sprintf("list namespace %s: %v", namespace, err)) continue } for _, name := range names { t := topic.NewTopic(namespace, name) conf, _, err := t.ReadConfFileWithMetadata(ctx, client) if errors.Is(err, filer_pb.ErrNotFound) { continue } if err != nil { scanErrors = append(scanErrors, fmt.Sprintf("topic %s: %v", t, err)) continue } if conf.Table == nil { continue } reason, err := topicTableDueReason(ctx, client, t, conf.Table, now) if err != nil { scanErrors = append(scanErrors, fmt.Sprintf("topic %s: %v", t, err)) continue } if reason != "" { due = append(due, topicTableDue{topic: t, table: conf.Table, reason: reason}) } } } return due, scanErrors } // topicTableDueReason says why t is due for a copy, or "" when no partition // has topicTableDueBytes sealed past the table's offsets or a sealed file // older than topicTableDueAge. func topicTableDueReason(ctx context.Context, client filer_pb.SeaweedFilerClient, t topic.Topic, tt *mq_pb.TopicTable, now time.Time) (string, error) { bucket, err := s3tables.ParseBucketNameFromARN(tt.TableBucketArn) if err != nil { return "", err } state, err := loadCurrentMetadata(ctx, client, bucket, path.Join(tt.Namespace, tt.Name)) if err != nil { return "", err } if err := checkTopicTableOwner(state.Metadata, t, tt); err != nil { return "", err } committed, err := topictable.CommittedOffsets(state.Metadata) if err != nil { return "", err } partitions, err := topictable.Partitions(ctx, singleFilerClient{client}, t) if err != nil { return "", err } for _, p := range partitions { sealed, err := topictable.ReadSealed(ctx, client, t, p) if err != nil { return "", err } bytes, oldest := sealed.Pending(committed[sealed.Name]) if bytes >= topicTableDueBytes { return fmt.Sprintf("%s has %d sealed bytes", sealed.Name, bytes), nil } if !oldest.IsZero() && now.Sub(oldest) >= topicTableDueAge { return fmt.Sprintf("%s has a sealed file from %s", sealed.Name, oldest.UTC().Format(time.RFC3339)), nil } } return "", nil } func listDirNames(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string) ([]string, error) { var names []string err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error { if entry.IsDirectory { names = append(names, entry.Name) } return nil }, "", false, math.MaxInt32) if errors.Is(err, filer_pb.ErrNotFound) { err = nil } return names, err } func (h *TopicTableHandler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error { if request == nil || request.Job == nil || sender == nil { return fmt.Errorf("execute: nil request/job/sender") } if request.Job.JobType != "" && request.Job.JobType != topicTableJobType { return fmt.Errorf("job type %q is not handled by the topic table handler", request.Job.JobType) } params := request.Job.Parameters t := topic.NewTopic(readStringConfig(params, "topic_namespace", ""), readStringConfig(params, "topic_name", "")) want := &mq_pb.TopicTable{ TableBucketArn: readStringConfig(params, "table_bucket_arn", ""), Namespace: readStringConfig(params, "table_namespace", ""), Name: readStringConfig(params, "table_name", ""), } filerAddress := pb.ServerAddress(readStringConfig(params, "filer_address", "")) if t.Namespace == "" || t.Name == "" || want.TableBucketArn == "" || filerAddress == "" { return fmt.Errorf("missing parameters: topic %q table %q filer %q", t, want.TableBucketArn, filerAddress) } for _, name := range []string{t.Namespace, t.Name} { if strings.Contains(name, "..") || strings.ContainsAny(name, "/\\") { return fmt.Errorf("invalid topic name %q", name) } } _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{ JobId: request.Job.JobId, JobType: topicTableJobType, State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "locking", Message: fmt.Sprintf("topic %s", t), }) conn, err := h.maintenance.dialFiler(ctx, filerAddress.ToGrpcAddress()) if err != nil { return fmt.Errorf("connect to filer %s: %w", filerAddress, err) } defer conn.Close() client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, security.FilerAdminToken)) lockClient := cluster.NewLockClient(h.maintenance.grpcDialOption, filerAddress) lockClient.TokenSource = security.FilerAdminToken key := topictable.LockKey(t) lock, err := lockClient.NewBlockingLongLivedLockWithin(key, "mq_topic_table-"+request.Job.JobId, topicTableLockTTL, topicTableLockWait) if err != nil { return fmt.Errorf("lock %s: %w", key, err) } defer func() { if err := lock.Stop(); err != nil { glog.Warningf("release lock %s: %v", key, err) } }() result, err := h.maintenance.copyTopicTable(ctx, client, t, want, lock.IsLocked) var summary string outputs := map[string]*plugin_pb.ConfigValue{} switch { case errors.Is(err, errTopicTableDetached): // the topic left the table or the table left the topic: nothing to copy, and no failure summary, err = fmt.Sprintf("topic %s: stopped, %v", t, err), nil case err != nil: summary = fmt.Sprintf("topic %s: %v", t, err) case result.committed: summary = fmt.Sprintf("topic %s: appended %d rows in %d files to %s.%s, offsets %s", t, result.rows, result.files, want.Namespace, want.Name, topictable.EncodeOffsets(result.offsets)) outputs["files_written"] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: result.files}} outputs["rows_written"] = &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: result.rows}} default: summary = fmt.Sprintf("topic %s: %s", t, result.message) } completed := &plugin_pb.JobCompleted{ JobId: request.Job.JobId, JobType: topicTableJobType, Success: err == nil, Result: &plugin_pb.JobResult{Summary: summary, OutputValues: outputs}, Activities: []*plugin_pb.ActivityEvent{pluginworker.BuildExecutorActivity("completed", summary)}, CompletedAt: timestamppb.Now(), } if err != nil { completed.ErrorMessage = err.Error() } return sender.SendCompleted(completed) } var _ pluginworker.JobHandler = (*TopicTableHandler)(nil)