| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| package replication |
|
|
| import ( |
| "context" |
| "fmt" |
| "slices" |
| "strings" |
| "sync" |
| "time" |
|
|
| "github.com/weaviate/weaviate/cluster/replication/metrics" |
| "github.com/weaviate/weaviate/cluster/schema" |
| "github.com/weaviate/weaviate/usecases/config/runtime" |
| "github.com/weaviate/weaviate/usecases/sharding" |
|
|
| "github.com/cenkalti/backoff/v4" |
| "github.com/pkg/errors" |
| "github.com/sirupsen/logrus" |
| "github.com/weaviate/weaviate/cluster/proto/api" |
| "github.com/weaviate/weaviate/cluster/replication/types" |
| "github.com/weaviate/weaviate/entities/additional" |
| enterrors "github.com/weaviate/weaviate/entities/errors" |
| "github.com/weaviate/weaviate/entities/models" |
| ) |
|
|
| |
| |
| const ( |
| asyncStatusInterval = 5 * time.Second |
| |
| asyncStatusMaxErrors = 30 |
| |
| |
| asyncStatusMaxRetries = 120 |
| ) |
|
|
| |
| type OpConsumer interface { |
| |
| |
| |
| Consume(ctx context.Context, in <-chan ShardReplicationOpAndStatus) error |
| } |
|
|
| |
| const DELETED = "deleted" |
|
|
| |
| var errOpCancelled = errors.New("operation cancelled") |
|
|
| |
| |
| |
| type CopyOpConsumer struct { |
| |
| |
| logger *logrus.Entry |
|
|
| |
| |
| ongoingOps *OpsCache |
|
|
| |
| |
| opsGateway *OpsGateway |
|
|
| |
| |
| leaderClient types.FSMUpdater |
|
|
| |
| |
| replicaCopier types.ReplicaCopier |
|
|
| |
| schemaReader schema.SchemaReader |
|
|
| |
| |
| backoffPolicy backoff.BackOff |
|
|
| |
| |
| |
| maxWorkers int |
|
|
| |
| |
| opTimeout time.Duration |
|
|
| |
| tokens chan struct{} |
|
|
| |
| nodeId string |
|
|
| |
| |
| engineOpCallbacks *metrics.ReplicationEngineOpsCallbacks |
|
|
| |
| asyncReplicationMinimumWait *runtime.DynamicValue[time.Duration] |
| } |
|
|
| type overrides struct { |
| source additional.AsyncReplicationTargetNodeOverride |
| target additional.AsyncReplicationTargetNodeOverride |
| } |
|
|
| func newOverrides(op ShardReplicationOpAndStatus, upperTimeBound int64) overrides { |
| return overrides{ |
| source: additional.AsyncReplicationTargetNodeOverride{ |
| CollectionID: op.Op.SourceShard.CollectionId, |
| ShardID: op.Op.SourceShard.ShardId, |
| TargetNode: op.Op.TargetShard.NodeId, |
| SourceNode: op.Op.SourceShard.NodeId, |
| UpperTimeBound: upperTimeBound, |
| NoDeletionResolution: true, |
| }, |
| target: additional.AsyncReplicationTargetNodeOverride{ |
| CollectionID: op.Op.SourceShard.CollectionId, |
| ShardID: op.Op.SourceShard.ShardId, |
| TargetNode: op.Op.SourceShard.NodeId, |
| SourceNode: op.Op.TargetShard.NodeId, |
| UpperTimeBound: upperTimeBound, |
| NoDeletionResolution: false, |
| }, |
| } |
| } |
|
|
| |
| |
| |
| |
| func NewCopyOpConsumer( |
| logger *logrus.Logger, |
| leaderClient types.FSMUpdater, |
| replicaCopier types.ReplicaCopier, |
| nodeId string, |
| backoffPolicy backoff.BackOff, |
| ongoingOps *OpsCache, |
| opTimeout time.Duration, |
| maxWorkers int, |
| asyncReplicationMinimumWait *runtime.DynamicValue[time.Duration], |
| engineOpCallbacks *metrics.ReplicationEngineOpsCallbacks, |
| schemaReader schema.SchemaReader, |
| ) *CopyOpConsumer { |
| c := &CopyOpConsumer{ |
| logger: logger.WithFields(logrus.Fields{"component": "replication_consumer", "action": replicationEngineLogAction}), |
| leaderClient: leaderClient, |
| replicaCopier: replicaCopier, |
| backoffPolicy: backoffPolicy, |
| ongoingOps: ongoingOps, |
| opTimeout: opTimeout, |
| maxWorkers: maxWorkers, |
| nodeId: nodeId, |
| tokens: make(chan struct{}, maxWorkers), |
| engineOpCallbacks: engineOpCallbacks, |
| asyncReplicationMinimumWait: asyncReplicationMinimumWait, |
| schemaReader: schemaReader, |
| opsGateway: NewOpsGateway(), |
| } |
| return c |
| } |
|
|
| |
| |
| func (c *CopyOpConsumer) Consume(workerCtx context.Context, in <-chan ShardReplicationOpAndStatus) error { |
| c.logger.WithFields(logrus.Fields{"node": c.nodeId, "max_workers": c.maxWorkers, "op_timeout": c.opTimeout}).Info("starting replication operation consumer") |
|
|
| c.engineOpCallbacks.OnPrepareProcessing(c.nodeId) |
|
|
| var wg sync.WaitGroup |
| for { |
| select { |
| case <-workerCtx.Done(): |
| c.logger.WithError(workerCtx.Err()).Info("worker context canceled, shutting down consumer") |
| |
| wg.Wait() |
| return workerCtx.Err() |
|
|
| case op, ok := <-in: |
| if !ok { |
| c.logger.Info("operation channel closed, shutting down consumer and waiting for ops to finish") |
| c.ongoingOps.CancelAll() |
| wg.Wait() |
| return nil |
| } |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
|
|
| |
| |
| |
| |
| if op.Status.ShouldCancel && !c.ongoingOps.HasBeenCancelled(op.Op.ID) { |
| |
| c.ongoingOps.StoreHasBeenCancelled(op.Op.ID) |
| logger.Debug("cancelled the replication op") |
| if c.ongoingOps.InFlight(op.Op.ID) { |
| |
| |
| c.ongoingOps.Cancel(op.Op.ID) |
| |
| continue |
| } |
| |
| } |
|
|
| if ok, next := c.opsGateway.CanSchedule(op.Op.ID); !ok { |
| logger.WithFields(logrus.Fields{"next": next}).Debug("replication op skipped as not ready to schedule") |
| continue |
| } |
|
|
| c.engineOpCallbacks.OnOpPending(c.nodeId) |
| select { |
| |
| case <-workerCtx.Done(): |
| continue |
| |
| |
| |
| |
| |
| case c.tokens <- struct{}{}: |
| |
| |
| operation := op |
| opLogger := getLoggerForOpAndStatus(c.logger, operation.Op, op.Status) |
| shouldSkip := false |
| opAlreadyInFlight := c.ongoingOps.LoadOrStore(op.Op.ID) |
| if opAlreadyInFlight { |
| |
| |
| |
| c.logger.Debug("replication op skipped as already running") |
| shouldSkip = true |
| } else { |
| |
| |
| |
| state, err := c.leaderClient.ReplicationGetReplicaOpStatus(workerCtx, op.Op.ID) |
| if err != nil { |
| c.logger.Error("error while checking status of replication op") |
| shouldSkip = true |
| } else if state.String() != op.Status.GetCurrent().State.String() { |
| c.logger.Debug("replication op skipped as state has changed") |
| shouldSkip = true |
| } |
| } |
|
|
| if op.Status.GetCurrent().State == "" { |
| c.logger.Debug("replication op skipped as state is empty") |
| shouldSkip = true |
| } |
|
|
| |
| |
| |
|
|
| |
| if shouldSkip { |
| opLogger.Debug("replication op skipped as already running") |
| |
| <-c.tokens |
| c.engineOpCallbacks.OnOpSkipped(c.nodeId) |
| if !opAlreadyInFlight { |
| c.ongoingOps.DeleteInFlight(op.Op.ID) |
| } |
| continue |
| } |
|
|
| |
| |
| opCtx, opCancel := context.WithTimeout(workerCtx, c.opTimeout) |
| c.engineOpCallbacks.OnOpStart(c.nodeId) |
| c.ongoingOps.StoreCancel(op.Op.ID, opCancel) |
| c.opsGateway.ScheduleNow(op.Op.ID) |
| wg.Add(1) |
| enterrors.GoWrapper(func() { |
| defer func() { |
| <-c.tokens |
| |
| c.ongoingOps.DeleteInFlight(op.Op.ID) |
| wg.Done() |
| opCancel() |
| }() |
|
|
| |
| |
| if c.ongoingOps.HasBeenCancelled(op.Op.ID) { |
| c.logger.Info("replication op cancelled, stopping replication operation") |
| c.cancelOp(operation, opLogger) |
| return |
| } |
|
|
| opLogger.Debug("worker processing replication operation") |
| err := c.dispatchReplicationOp(opCtx, operation) |
| if err == nil { |
| opLogger.Debug("worker completed replication operation") |
| c.opsGateway.RegisterFinished(op.Op.ID) |
| c.engineOpCallbacks.OnOpComplete(c.nodeId) |
| return |
| } |
|
|
| c.opsGateway.RegisterFailure(op.Op.ID) |
| if errors.Is(err, context.DeadlineExceeded) { |
| c.engineOpCallbacks.OnOpFailed(c.nodeId) |
| opLogger.WithError(err).Error("replication operation timed out") |
| return |
| } |
| |
| if errors.Is(err, context.Canceled) && c.ongoingOps.HasBeenCancelled(op.Op.ID) { |
| opLogger.WithError(err).Info("replication operation cancelled") |
| c.cancelOp(operation, opLogger) |
| return |
| } |
| if errors.Is(err, errOpCancelled) { |
| opLogger.WithError(err).Info("replication operation cancelled") |
| c.cancelOp(operation, opLogger) |
| return |
| } |
| c.engineOpCallbacks.OnOpFailed(c.nodeId) |
| opLogger.WithError(err).Error("replication operation failed") |
| }, c.logger) |
| } |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| func (c *CopyOpConsumer) dispatchReplicationOp(ctx context.Context, op ShardReplicationOpAndStatus) error { |
| switch op.Status.GetCurrentState() { |
| case api.REGISTERED: |
| return c.processStateAndTransition(ctx, op, c.processRegisteredOp) |
| case api.HYDRATING: |
| return c.processStateAndTransition(ctx, op, c.processHydratingOp) |
| case api.DEHYDRATING: |
| return c.processStateAndTransition(ctx, op, c.processDehydratingOp) |
| case api.FINALIZING: |
| return c.processStateAndTransition(ctx, op, c.processFinalizingOp) |
| case api.READY: |
| return nil |
| case api.CANCELLED: |
| return c.processStateAndTransition(ctx, op, c.processCancelledOp) |
| default: |
| getLoggerForOpAndStatus(c.logger, op.Op, op.Status).Error("unknown replication operation state") |
| return fmt.Errorf("unknown replication operation state: %s", op.Status.GetCurrentState()) |
| } |
| } |
|
|
| |
| type stateFuncHandler func(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) |
|
|
| func (c *CopyOpConsumer) checkCancelled(logger *logrus.Entry, op ShardReplicationOpAndStatus) error { |
| if c.ongoingOps.HasBeenCancelled(op.Op.ID) { |
| logger.WithFields(logrus.Fields{"op": op}).Debug("replication op cancelled, stopping replication operation") |
| return errOpCancelled |
| } |
| return nil |
| } |
|
|
| |
| |
| |
| |
| func (c *CopyOpConsumer) processStateAndTransition(ctx context.Context, op ShardReplicationOpAndStatus, stateFuncHandler stateFuncHandler) error { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| nextState, err := backoff.RetryWithData(func() (api.ShardReplicationState, error) { |
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Error("error while processing replication operation, shutting down") |
| return api.ShardReplicationState(""), backoff.Permanent(ctx.Err()) |
| } |
| if err := c.checkCancelled(logger, op); err != nil { |
| return api.ShardReplicationState(""), backoff.Permanent(fmt.Errorf("error while checking if op is cancelled: %w", err)) |
| } |
|
|
| nextState, err := stateFuncHandler(ctx, op) |
| |
| if err != nil { |
| |
| if errors.Is(err, context.Canceled) { |
| logger.Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), backoff.Permanent(fmt.Errorf("context cancelled: %w", err)) |
| } |
| if err := c.checkCancelled(logger, op); err != nil { |
| return api.ShardReplicationState(""), backoff.Permanent(fmt.Errorf("error while checking if op is cancelled: %w", err)) |
| } |
| logger.WithError(err).Warn("state transition handler failed") |
| |
| if err := c.leaderClient.ReplicationRegisterError(ctx, op.Op.ID, err.Error()); err != nil { |
| logger.WithError(err).Error("failed to register error for replication operation") |
| } |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if err := c.checkCancelled(logger, op); err != nil { |
| return api.ShardReplicationState(""), backoff.Permanent(fmt.Errorf("error while checking if op is cancelled: %w", err)) |
| } |
| |
| if err := c.leaderClient.ReplicationUpdateReplicaOpStatus(ctx, op.Op.ID, nextState); err != nil { |
| logger.WithError(err).Errorf("failed to update replica status to '%s'", nextState) |
| return api.ShardReplicationState(""), fmt.Errorf("failed to update replica status to '%s': %w", nextState, err) |
| } |
| return nextState, nil |
| }, c.backoffPolicy) |
| if err != nil { |
| return err |
| } |
|
|
| if nextState == DELETED { |
| |
| return nil |
| } |
|
|
| op.Status.ChangeState(nextState) |
| if nextState == api.READY { |
| |
| return nil |
| } |
|
|
| if err := c.checkCancelled(logger, op); err != nil { |
| return err |
| } |
| return c.dispatchReplicationOp(ctx, op) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| func (c *CopyOpConsumer) cancelOp(op ShardReplicationOpAndStatus, logger *logrus.Entry) { |
| defer func() { |
| c.ongoingOps.DeleteHasBeenCancelled(op.Op.ID) |
| c.engineOpCallbacks.OnOpCancelled(c.nodeId) |
| }() |
| ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| defer cancel() |
|
|
| overrides := newOverrides(op, time.Now().UnixMilli()) |
| c.stopAsyncReplication(ctx, op, overrides, logger) |
|
|
| |
| |
| if err := c.sync(ctx, op); err != nil { |
| logger.WithError(err). |
| WithField("op", op). |
| Error(fmt.Errorf("failure while syncing replica shard when cancelling the op")) |
| } |
|
|
| |
| if op.Status.OnlyCancellation() { |
| if err := c.leaderClient.ReplicationCancellationComplete(ctx, op.Op.ID); err != nil { |
| logger.WithError(err).Error("failure while completing cancellation of replica operation") |
| } |
| return |
| } |
|
|
| |
| if op.Status.ShouldDelete { |
| if err := c.leaderClient.ReplicationRemoveReplicaOp(ctx, op.Op.ID); err != nil { |
| logger.WithError(err).Error("failure while deleting replica operation") |
| } |
| return |
| } |
| } |
|
|
| func (c *CopyOpConsumer) startAsyncReplication(ctx context.Context, op ShardReplicationOpAndStatus, overrides overrides, logger *logrus.Entry) error { |
| |
| if err := c.replicaCopier.InitAsyncReplicationLocally(ctx, op.Op.SourceShard.CollectionId, op.Op.TargetShard.ShardId); err != nil { |
| logger.WithError(err).Error("failed to initialize async replication on local node") |
| return err |
| } |
| |
| if err := c.replicaCopier.AddAsyncReplicationTargetNode(ctx, overrides.target, op.Status.SchemaVersion); err != nil { |
| logger.WithError(err).Error("failed to add async replication from source node to target node") |
| return err |
| } |
| |
| if err := c.replicaCopier.AddAsyncReplicationTargetNode(ctx, overrides.source, op.Status.SchemaVersion); err != nil { |
| logger.WithError(err).Error("failed to add async replication from target node to source node") |
| return err |
| } |
| return nil |
| } |
|
|
| func (c *CopyOpConsumer) stopAsyncReplication(ctx context.Context, op ShardReplicationOpAndStatus, overrides overrides, logger *logrus.Entry) { |
| if err := c.replicaCopier.RemoveAsyncReplicationTargetNode(ctx, overrides.target); err != nil { |
| logger.WithError(err).Error("failure while removing async replication from source node to target node") |
| } |
| if err := c.replicaCopier.RemoveAsyncReplicationTargetNode(ctx, overrides.source); err != nil { |
| logger.WithError(err).Error("failure while removing async replication from target node to source node") |
| } |
| if err := c.replicaCopier.RevertAsyncReplicationLocally(ctx, op.Op.TargetShard.CollectionId, op.Op.SourceShard.ShardId); err != nil { |
| logger.WithError(err).Error("failure while reverting async replication on local node") |
| } |
| } |
|
|
| func (c *CopyOpConsumer) sync(ctx context.Context, op ShardReplicationOpAndStatus) error { |
| if _, err := c.leaderClient.SyncShard(ctx, op.Op.TargetShard.CollectionId, op.Op.TargetShard.ShardId, op.Op.TargetShard.NodeId); err != nil { |
| return err |
| } |
| if _, err := c.leaderClient.SyncShard(ctx, op.Op.SourceShard.CollectionId, op.Op.SourceShard.ShardId, op.Op.SourceShard.NodeId); err != nil { |
| return err |
| } |
| return nil |
| } |
|
|
| |
| func (c *CopyOpConsumer) processRegisteredOp(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| logger.Info("processing registered replication operation") |
|
|
| return api.HYDRATING, nil |
| } |
|
|
| |
| |
| func (c *CopyOpConsumer) processHydratingOp(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| logger.Info("processing hydrating replication operation") |
|
|
| if c.schemaReader.MultiTenancy(op.Op.TargetShard.CollectionId).Enabled { |
| schemaVersion, err := c.leaderClient.UpdateTenants(ctx, op.Op.TargetShard.CollectionId, &api.UpdateTenantsRequest{ |
| Tenants: []*api.Tenant{ |
| { |
| Name: op.Op.SourceShard.ShardId, |
| Status: models.TenantActivityStatusHOT, |
| }, |
| }, |
| }) |
| if err != nil { |
| logger.WithError(err).Error("failure while updating tenant to active state for hydrating operation") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if err := c.leaderClient.ReplicationStoreSchemaVersion(ctx, op.Op.ID, schemaVersion); err != nil { |
| logger.WithError(err).Error("failure while storing schema version for replication operation") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if err := c.leaderClient.WaitForUpdate(ctx, schemaVersion); err != nil { |
| logger.WithError(err).Error("failure while waiting for schema version to be applied to local node") |
| return api.ShardReplicationState(""), err |
| } |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if err := c.replicaCopier.CopyReplicaFiles(ctx, op.Op.SourceShard.NodeId, op.Op.SourceShard.CollectionId, op.Op.TargetShard.ShardId, op.Status.SchemaVersion); err != nil { |
| logger.WithError(err).Error("failure while copying replica shard") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| return api.FINALIZING, nil |
| } |
|
|
| |
| |
| func (c *CopyOpConsumer) processFinalizingOp(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| logger.Info("processing finalizing replication operation") |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if err := c.leaderClient.WaitForUpdate(ctx, op.Status.SchemaVersion); err != nil { |
| logger.WithError(err).Error("failure while waiting for schema version to be applied to local node") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if err := c.replicaCopier.LoadLocalShard(ctx, op.Op.SourceShard.CollectionId, op.Op.SourceShard.ShardId); err != nil { |
| logger.WithError(err).Error("failure while loading shard") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| |
| |
| nodes, err := c.schemaReader.ShardReplicas(op.Op.TargetShard.CollectionId, op.Op.TargetShard.ShardId) |
| if err != nil { |
| logger.WithError(err).Error("failure while getting shard replicas") |
| return api.ShardReplicationState(""), err |
| } |
| replicaExists := slices.Contains(nodes, op.Op.TargetShard.NodeId) |
|
|
| |
| |
| asyncReplicationUpperTimeBoundUnixMillis := time.Now().Add(time.Second * 5).UnixMilli() |
| overrides := newOverrides(op, asyncReplicationUpperTimeBoundUnixMillis) |
| if err := c.startAsyncReplication(ctx, op, overrides, logger); err != nil { |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("error while processing replication operation, shutting down") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if err := c.waitForAsyncReplication(ctx, op, asyncReplicationUpperTimeBoundUnixMillis, logger); err != nil { |
| logger.WithError(err).Error("failure while waiting for async replication to complete while finalizing") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("error while processing replication operation, shutting down") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if !replicaExists { |
| if _, err := c.leaderClient.ReplicationAddReplicaToShard(ctx, op.Op.TargetShard.CollectionId, op.Op.TargetShard.ShardId, op.Op.TargetShard.NodeId, op.Op.ID); err != nil { |
| if strings.Contains(err.Error(), sharding.ErrReplicaAlreadyExists.Error()) { |
| |
| |
| logger.Debug("replica already exists, skipping") |
| } else { |
| logger.WithError(err).Error("failure while adding replica to shard") |
| return api.ShardReplicationState(""), err |
| } |
| } |
| } |
|
|
| switch op.Op.TransferType { |
| case api.COPY: |
| c.stopAsyncReplication(ctx, op, overrides, logger) |
| |
| |
| if err := c.sync(ctx, op); err != nil { |
| logger.WithError(err).Error("failure while syncing replica shard in finalizing state") |
| return api.ShardReplicationState(""), err |
| } |
| return api.READY, nil |
| case api.MOVE: |
| return api.DEHYDRATING, nil |
| default: |
| return api.ShardReplicationState(""), fmt.Errorf("unknown transfer type: %s", op.Op.TransferType) |
| } |
| } |
|
|
| |
| func (c *CopyOpConsumer) processDehydratingOp(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| logger.Info("processing dehydrating replication operation") |
|
|
| if err := c.leaderClient.WaitForUpdate(ctx, op.Status.SchemaVersion); err != nil { |
| logger.WithError(err).Error("failure while waiting for schema version to be applied to local node") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| nodes, err := c.schemaReader.ShardReplicas(op.Op.SourceShard.CollectionId, op.Op.SourceShard.ShardId) |
| if err != nil { |
| logger.WithError(err).Error("failure while getting shard replicas") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| |
| |
| |
| |
| |
| asyncReplicationUpperTimeBoundUnixMillis := time.Now().Add(c.asyncReplicationMinimumWait.Get()).UnixMilli() |
| overrides := newOverrides(op, asyncReplicationUpperTimeBoundUnixMillis) |
|
|
| if slices.Contains(nodes, op.Op.SourceShard.NodeId) { |
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if err := c.startAsyncReplication(ctx, op, overrides, logger); err != nil { |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("error while processing replication operation, shutting down") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| if err := c.waitForAsyncReplication(ctx, op, asyncReplicationUpperTimeBoundUnixMillis, logger); err != nil { |
| logger.WithError(err).Error("failure while waiting for async replication to complete while dehydrating") |
| return api.ShardReplicationState(""), err |
| } |
|
|
| if ctx.Err() != nil { |
| logger.WithError(ctx.Err()).Debug("context cancelled, stopping replication operation") |
| return api.ShardReplicationState(""), ctx.Err() |
| } |
|
|
| c.stopAsyncReplication(ctx, op, overrides, logger) |
|
|
| |
| if _, err := c.leaderClient.DeleteReplicaFromShard(ctx, op.Op.SourceShard.CollectionId, op.Op.SourceShard.ShardId, op.Op.SourceShard.NodeId); err != nil { |
| logger.WithError(err).Error("failure while deleting replica from shard") |
| return api.ShardReplicationState(""), err |
| } |
| } |
|
|
| |
| |
| if err := c.sync(ctx, op); err != nil { |
| logger.WithError(err).Error("failure while syncing replica shard in dehydrating state") |
| return api.ShardReplicationState(""), err |
| } |
| return api.READY, nil |
| } |
|
|
| func (c *CopyOpConsumer) processCancelledOp(ctx context.Context, op ShardReplicationOpAndStatus) (api.ShardReplicationState, error) { |
| logger := getLoggerForOpAndStatus(c.logger, op.Op, op.Status) |
| logger.Info("processing cancelled replication operation") |
|
|
| if !op.Status.ShouldDelete { |
| return api.ShardReplicationState(""), fmt.Errorf("replication operation with id %v is not in a state to be deleted", op.Op.ID) |
| } |
|
|
| overrides := newOverrides(op, time.Now().UnixMilli()) |
| c.stopAsyncReplication(ctx, op, overrides, logger) |
|
|
| if err := c.leaderClient.ReplicationRemoveReplicaOp(ctx, op.Op.ID); err != nil { |
| logger.WithError(err).Error("failure while removing replica operation") |
| return api.ShardReplicationState(""), err |
| } |
| return DELETED, nil |
| } |
|
|
| func (c *CopyOpConsumer) handleAsyncReplErr( |
| err error, |
| retryNum int, |
| asyncStatusMaxErrors int, |
| remainingErrorsAllowed int, |
| logger *logrus.Entry, |
| ) (int, error) { |
| remainingErrorsAllowed-- |
| if remainingErrorsAllowed < 0 { |
| |
| |
| logger.WithFields(logrus.Fields{"num_errors": asyncStatusMaxErrors, "num_retries": retryNum}).WithError(err).Error("errored on all attempts to get async replication status") |
| return remainingErrorsAllowed, backoff.Permanent(err) |
| } |
| |
| |
| |
| logger.WithFields(logrus.Fields{"num_errors_allowed": asyncStatusMaxErrors, "num_errors_left": remainingErrorsAllowed, "num_retries_so_far": retryNum}).WithError(err).Warn("errored when getting async replication status, hashtrees may still be initializing, retrying") |
| return remainingErrorsAllowed, err |
| } |
|
|
| |
| |
| |
| |
| func (c *CopyOpConsumer) waitForAsyncReplication( |
| ctx context.Context, |
| op ShardReplicationOpAndStatus, |
| asyncReplicationUpperTimeBoundUnixMillis int64, |
| logger *logrus.Entry, |
| ) error { |
| remainingErrorsAllowed := asyncStatusMaxErrors |
| retryNum := -1 |
| return backoff.Retry(func() error { |
| retryNum++ |
| asyncReplStatusSrc, err := c.replicaCopier.AsyncReplicationStatus( |
| ctx, |
| op.Op.SourceShard.NodeId, |
| op.Op.TargetShard.NodeId, |
| op.Op.SourceShard.CollectionId, |
| op.Op.SourceShard.ShardId, |
| ) |
| if err != nil { |
| remainingErrorsAllowed, err = c.handleAsyncReplErr(err, retryNum, asyncStatusMaxErrors, remainingErrorsAllowed, logger) |
| return err |
| } |
| asyncReplIsPastUpperTimeBoundSrc := asyncReplStatusSrc.StartDiffTimeUnixMillis >= asyncReplicationUpperTimeBoundUnixMillis |
|
|
| asyncReplStatusTgt, err := c.replicaCopier.AsyncReplicationStatus( |
| ctx, |
| op.Op.TargetShard.NodeId, |
| op.Op.SourceShard.NodeId, |
| op.Op.TargetShard.CollectionId, |
| op.Op.TargetShard.ShardId, |
| ) |
| if err != nil { |
| remainingErrorsAllowed, err = c.handleAsyncReplErr(err, retryNum, asyncStatusMaxErrors, remainingErrorsAllowed, logger) |
| return err |
| } |
| asyncReplIsPastUpperTimeBoundTgt := asyncReplStatusTgt.StartDiffTimeUnixMillis >= asyncReplicationUpperTimeBoundUnixMillis |
|
|
| objectsPropagated := asyncReplStatusSrc.ObjectsPropagated + asyncReplStatusTgt.ObjectsPropagated |
| asyncReplIsPastUpperTimeBound := asyncReplIsPastUpperTimeBoundSrc && asyncReplIsPastUpperTimeBoundTgt |
| |
| |
| logger.WithFields(logrus.Fields{ |
| "objects_propagated": objectsPropagated, |
| "start_diff_time_unix_millis_src": asyncReplStatusSrc.StartDiffTimeUnixMillis, |
| "start_diff_time_unix_millis_tgt": asyncReplStatusTgt.StartDiffTimeUnixMillis, |
| "upper_time_bound_unix_millis": asyncReplicationUpperTimeBoundUnixMillis, |
| "async_replication_past_upper_time_bound": asyncReplIsPastUpperTimeBound, |
| "num_retries_so_far": retryNum, |
| "remaining_errors_allowed": remainingErrorsAllowed, |
| }).Info("async replication status") |
| if objectsPropagated == 0 && asyncReplIsPastUpperTimeBound { |
| return nil |
| } |
|
|
| |
| |
| currentTimeMillis := time.Now().UnixMilli() |
| if currentTimeMillis < asyncReplicationUpperTimeBoundUnixMillis { |
| waitDuration := time.Duration(asyncReplicationUpperTimeBoundUnixMillis-currentTimeMillis) * time.Millisecond |
| logger.WithFields(logrus.Fields{ |
| "wait_duration_ms": waitDuration.Milliseconds(), |
| "upper_bound_ms": asyncReplicationUpperTimeBoundUnixMillis, |
| }).Info("waiting to reach upper time bound before starting async replication status checks") |
|
|
| select { |
| case <-ctx.Done(): |
| return ctx.Err() |
| case <-time.After(waitDuration): |
| |
| } |
| } |
|
|
| return errors.New("async replication not done") |
| }, backoff.WithContext( |
| backoff.WithMaxRetries(backoff.NewConstantBackOff(asyncStatusInterval), asyncStatusMaxRetries), |
| ctx), |
| ) |
| } |
|
|