// Copyright 2026 PingCAP, Inc. Licensed under Apache-2.0. package snapshot import ( "context" "encoding/json" "os" "path/filepath" "sync" "time" "github.com/google/uuid" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/pkg/common" appcontext "github.com/pingcap/ticdc/pkg/common/context" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/messaging" "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/node" "github.com/pingcap/ticdc/pkg/snapshot/bootstrap" "github.com/pingcap/ticdc/pkg/snapshot/protocol" "github.com/pingcap/ticdc/pkg/writelease" "github.com/pingcap/tidb/pkg/kv" ) const ( ServiceName = "snapshot" controlTopic = "snapshot-control" ) type ( Nodes interface{ GetAliveNodes() map[node.ID]*node.Info } Repository interface { bootstrap.Repository Bind(context.Context, common.ChangeFeedID, uint64, *protocol.State, string) error } ) // StorageGetter borrows server-owned storage; snapshot execution must never close it. type ( StorageGetter func(context.Context, string) (kv.Storage, error) request struct { Config *config.ChangefeedConfig Keyspace uint32 } ) type response struct { Done bool Error string } type execution struct { epoch uint64 cancel context.CancelFunc done chan struct{} err error seen time.Time } // Service is CDC-owned: MessageCenter only transports start/status heartbeats. // Data and task pages stay on the executor; no external management process runs. type Service struct { ctx context.Context self *node.Info nodes Nodes repo Repository mc messaging.MessageCenter storage StorageGetter mu sync.Mutex jobs map[common.ChangeFeedID]*execution waiters map[string]chan response } func NewService(ctx context.Context, self *node.Info, nodes Nodes, repo Repository, mc messaging.MessageCenter, storage StorageGetter) *Service { s := &Service{ctx: ctx, self: self, nodes: nodes, repo: repo, mc: mc, storage: storage, jobs: make(map[common.ChangeFeedID]*execution), waiters: make(map[string]chan response)} mc.RegisterHandler(controlTopic, s.handle) return s } func (s *Service) Name() string { return ServiceName } func (s *Service) Run(ctx context.Context) error { <-ctx.Done(); return nil } func (s *Service) Close(context.Context) error { s.mc.DeRegisterHandler(controlTopic) s.mu.Lock() jobs := make([]*execution, 0, len(s.jobs)) for _, j := range s.jobs { j.cancel() jobs = append(jobs, j) } s.mu.Unlock() for _, j := range jobs { <-j.done } return nil } // Run is the only maintainer entry point. It waits for the original executor // through node-manager's grace period and only then rebinds to this CDC. func (s *Service) Bootstrap(ctx context.Context, cfg *config.ChangefeedConfig, keyspace uint32) error { if err := Validate(cfg); err != nil { return err } var placement Placement ticker := time.NewTicker(time.Second) defer ticker.Stop() for { state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) if err != nil { return err } if state != nil && state.Phase == "SNAPSHOT_COMMITTED" { return nil } if state == nil { id := uuid.NewString() state = &protocol.State{Generation: id, SnapshotID: id, SnapshotTS: cfg.StartTS, Phase: "PREPARING"} } target, bind := placement.Select(time.Now(), state.Executor, s.self, s.nodes.GetAliveNodes()) if target != nil { if bind { old := state.Executor state.Executor = target.AdvertiseAddr // Local receipts cannot be read on another node. Re-export the same frozen // snapshot there, allowing duplicates, with no dependency on the lost disk. if old != "" && old != state.Executor { state.SpecRef = protocol.ObjectRef{} state.PlanRef = protocol.ObjectRef{} state.Cursor = "" state.Applied = 0 state.Total = 0 state.Phase = "PREPARING" } if err = s.repo.Bind(ctx, cfg.ChangefeedID, cfg.Epoch, state, old); err != nil { return err } } res, err := s.poll(ctx, target.ID, request{cfg, keyspace}) if err == nil { if res.Error != "" { return protocol.Invalid("%s", res.Error) } if res.Done { return nil } } // A transient transport failure doesn't change executor ownership. If the // node disappears, NodeManager starts the 60-second relocation timer. } select { case <-ctx.Done(): return protocol.Wrap(ctx.Err()) case <-ticker.C: } } } func (s *Service) poll(ctx context.Context, target node.ID, req request) (response, error) { if target == s.self.ID { return s.status(req), nil } id := uuid.NewString() ch := make(chan response, 1) s.mu.Lock() s.waiters[id] = ch s.mu.Unlock() defer func() { s.mu.Lock(); delete(s.waiters, id); s.mu.Unlock() }() payload, err := json.Marshal(req) if err != nil { return response{}, protocol.Wrap(err) } if err = s.mc.SendCommand(messaging.NewSingleTargetMessage(target, controlTopic, &protocol.Message{RequestID: id, Payload: payload})); err != nil { return response{}, err } timer := time.NewTimer(time.Second) defer timer.Stop() select { case r := <-ch: return r, nil case <-ctx.Done(): return response{}, protocol.Wrap(ctx.Err()) case <-timer.C: return response{}, protocol.Invalid("snapshot status timeout") } } func (s *Service) handle(_ context.Context, msg *messaging.TargetMessage) error { m := msg.Message[0].(*protocol.Message) if m.Response { var r response if err := json.Unmarshal(m.Payload, &r); err != nil { return protocol.Wrap(err) } s.mu.Lock() if ch := s.waiters[m.RequestID]; ch != nil { select { case ch <- r: default: } } s.mu.Unlock() return nil } var req request if err := json.Unmarshal(m.Payload, &req); err != nil { return protocol.Wrap(err) } if req.Config == nil { return protocol.Invalid("missing snapshot configuration") } r := s.status(req) b, err := json.Marshal(r) if err != nil { return protocol.Wrap(err) } return s.mc.SendCommand(messaging.NewSingleTargetMessage(msg.From, controlTopic, &protocol.Message{RequestID: m.RequestID, Response: true, Payload: b})) } func (s *Service) status(req request) response { s.mu.Lock() defer s.mu.Unlock() cfg := req.Config j := s.jobs[cfg.ChangefeedID] if j != nil && j.epoch != cfg.Epoch { if j.epoch > cfg.Epoch { return response{Error: "stale snapshot owner"} } j.cancel() select { case <-j.done: delete(s.jobs, cfg.ChangefeedID) j = nil default: return response{} } } if j == nil { ctx, cancel := context.WithCancel(s.ctx) j = &execution{epoch: cfg.Epoch, cancel: cancel, done: make(chan struct{}), seen: time.Now()} s.jobs[cfg.ChangefeedID] = j go func() { defer close(j.done); j.err = s.execute(ctx, req) }() go s.watch(ctx, cfg, j) } j.seen = time.Now() select { case <-j.done: if j.err != nil { return response{Error: j.err.Error()} } return response{Done: true} default: return response{} } } func (s *Service) watch(ctx context.Context, cfg *config.ChangefeedConfig, j *execution) { ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-j.done: return case <-ticker.C: s.mu.Lock() expired := time.Since(j.seen) > 15*time.Second s.mu.Unlock() state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) if expired || err != nil || state == nil || state.Executor != s.self.AdvertiseAddr { j.cancel() return } } } } func (s *Service) execute(ctx context.Context, req request) error { ctx, cancel := context.WithCancel(ctx) defer cancel() cfg := req.Config if err := Validate(cfg); err != nil { return err } state, err := s.repo.LoadSnapshot(ctx, cfg.ChangefeedID, cfg.Epoch) if err != nil { return err } if state != nil && state.Phase == "SNAPSHOT_COMMITTED" { return nil } if state == nil || state.Executor != s.self.AdvertiseAddr { return protocol.Invalid("snapshot executor fenced") } server := config.GetGlobalServerConfig() dir := filepath.Join(server.DataDir, "snapshot", cfg.ChangefeedID.ID().String()) if err = os.MkdirAll(dir, 0o700); err != nil { return protocol.Wrap(err) } bundle, spans, err := s.freezeSchema(ctx, cfg) if err != nil { return err } destination, err := json.Marshal(struct { URI string Sink *config.SinkConfig TimeZone string CaseSensitive bool }{cfg.SinkURI, cfg.SinkConfig, cfg.TimeZone, cfg.CaseSensitive}) if err != nil { return protocol.Wrap(err) } sk, err := sink.New(ctx, cfg, cfg.ChangefeedID, req.Keyspace) if err != nil { return err } if gate, ok := appcontext.TryGetService[*writelease.Gate](appcontext.CaptureWriteGate); ok { sk.SetWriteGate(gate) } statistics := metrics.NewSnapshotStatistics(cfg.ChangefeedID.Keyspace(), cfg.ChangefeedID.Name()) statistics.Start("overall") statistics.Set("inflight_bytes", 0) statistics.Set("write_memory_quota_bytes", float64(cfg.Snapshot.InflightLimit())) statistics.Set("disk_quota_bytes", float64(cfg.Snapshot.DiskLimit())) writer := NewWriter(ctx, sk, cfg.Snapshot, cfg.Epoch, statistics) defer writer.Close() go func() { select { case <-ctx.Done(): case <-writer.sinkStopped: if writer.sinkErr != nil { cancel() } } }() ctl := bootstrap.Controller{Statistics: statistics, DestinationDigest: protocol.Digest(destination), ID: cfg.ChangefeedID, Epoch: cfg.Epoch, TS: cfg.StartTS, Keyspace: req.Keyspace, Config: cfg.Snapshot, ArtifactDir: dir, CSEBinary: server.SnapshotCSEBinary, MinFreeBytes: server.SnapshotMinFreeBytes, Repository: s.repo, Capture: writer, Freeze: func() (bootstrap.SchemaBundle, []protocol.Span, error) { return bundle, spans, nil }} err = ctl.Run(ctx) if err == nil { statistics.Finish("apply") statistics.Finish("overall") } else { statistics.Error("overall") } select { case <-writer.sinkStopped: if writer.sinkErr != nil { return writer.sinkErr } default: } return err } func (s *Service) freezeSchema(ctx context.Context, cfg *config.ChangefeedConfig) (bootstrap.SchemaBundle, []protocol.Span, error) { storage, err := s.storage(ctx, cfg.ChangefeedID.Keyspace()) if err != nil { return bootstrap.SchemaBundle{}, nil, err } // TiDB's driver caches clients across OpenWithOptions calls. Their lifetime // belongs to KeyspaceManager, including after this snapshot has completed. return FreezeSchema(ctx, storage, cfg.StartTS, cfg) }