|
| 1 | +package verifier |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/10gen/migration-verifier/internal/util" |
| 9 | + "github.com/10gen/migration-verifier/option" |
| 10 | + "github.com/pkg/errors" |
| 11 | + "github.com/samber/lo" |
| 12 | + "go.mongodb.org/mongo-driver/mongo" |
| 13 | +) |
| 14 | + |
| 15 | +// This is the Field for a VerificationResult for shard key mismatches. |
| 16 | +const ShardKeyField = "Shard Key" |
| 17 | + |
| 18 | +func (verifier *Verifier) verifyShardingIfNeeded( |
| 19 | + ctx context.Context, |
| 20 | + srcColl, dstColl *mongo.Collection, |
| 21 | +) ([]VerificationResult, error) { |
| 22 | + |
| 23 | + // We only need to compare if both clusters are sharded |
| 24 | + srcSharded := verifier.srcClusterInfo.Topology == util.TopologySharded |
| 25 | + dstSharded := verifier.dstClusterInfo.Topology == util.TopologySharded |
| 26 | + |
| 27 | + if !srcSharded || !dstSharded { |
| 28 | + return nil, nil |
| 29 | + } |
| 30 | + |
| 31 | + srcShardOpt, err := util.GetShardKey(ctx, srcColl) |
| 32 | + if err != nil { |
| 33 | + return nil, errors.Wrapf( |
| 34 | + err, |
| 35 | + "failed to fetch %#q's shard key on source", |
| 36 | + FullName(srcColl), |
| 37 | + ) |
| 38 | + } |
| 39 | + |
| 40 | + dstShardOpt, err := util.GetShardKey(ctx, dstColl) |
| 41 | + if err != nil { |
| 42 | + return nil, errors.Wrapf( |
| 43 | + err, |
| 44 | + "failed to fetch %#q's shard key on destination", |
| 45 | + FullName(dstColl), |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + srcKey, srcIsSharded := srcShardOpt.Get() |
| 50 | + dstKey, dstIsSharded := dstShardOpt.Get() |
| 51 | + |
| 52 | + if !srcIsSharded && !dstIsSharded { |
| 53 | + return nil, nil |
| 54 | + } |
| 55 | + |
| 56 | + if srcIsSharded != dstIsSharded { |
| 57 | + return []VerificationResult{{ |
| 58 | + Field: ShardKeyField, |
| 59 | + Cluster: lo.Ternary(srcIsSharded, ClusterTarget, ClusterSource), |
| 60 | + Details: Missing, |
| 61 | + NameSpace: FullName(srcColl), |
| 62 | + }}, nil |
| 63 | + } |
| 64 | + |
| 65 | + if bytes.Equal(srcKey, dstKey) { |
| 66 | + return nil, nil |
| 67 | + } |
| 68 | + |
| 69 | + areEqual, err := util.ServerThinksTheseMatch( |
| 70 | + ctx, |
| 71 | + verifier.metaClient, |
| 72 | + srcKey, dstKey, |
| 73 | + option.None[mongo.Pipeline](), |
| 74 | + ) |
| 75 | + if err != nil { |
| 76 | + return nil, errors.Wrapf( |
| 77 | + err, |
| 78 | + "failed to ask server if shard keys (src %v; dst: %v) match", |
| 79 | + srcKey, |
| 80 | + dstKey, |
| 81 | + ) |
| 82 | + } |
| 83 | + |
| 84 | + if !areEqual { |
| 85 | + return []VerificationResult{{ |
| 86 | + Field: ShardKeyField, |
| 87 | + Details: fmt.Sprintf("%s: src=%v; dst=%v", Mismatch, srcKey, dstKey), |
| 88 | + NameSpace: FullName(srcColl), |
| 89 | + }}, nil |
| 90 | + } |
| 91 | + |
| 92 | + return nil, nil |
| 93 | +} |
0 commit comments