Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public static class MongoDBReplicaSetBuilderExtensions
private const string NewReplicaSetConfigurationIncompatibleCodeName = "NewReplicaSetConfigurationIncompatible";
private const string ConfigurationInProgressCodeName = "ConfigurationInProgress"; // NOTE: Represents the error `Cannot run replSetReconfig because the node is currently updating its configuration.` that can be returned by `replSetReconfig` when a preceding `replSetInitiate` (or `replSetReconfig`, for that matter) command is still being processed in the background.
private static readonly TimeSpan s_rsInitiationRetryWaitInterval = TimeSpan.FromSeconds(1);
private static readonly TimeSpan s_primaryElectionPollInterval = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan s_primaryElectionTimeout = TimeSpan.FromSeconds(30);

/// <summary>
/// Adds a MongoDB replica set resource to the application model.
Expand Down Expand Up @@ -299,28 +301,7 @@ await admin.RunCommandAsync<BsonDocument>(
// NOTE: There is no existing configuration to preserve member ids from, so all of them are freshly allocated.
var membersBsonArray = BuildMembersConfiguration(memberHosts, currentMembers: null);

// NOTE: The initialization is performed in two steps, first with a single member and then with the full configuration. `replSetInitiate` runs a quorum check against every host in the configuration it is handed and only returns once an election has succeeded, so initiating with the full member list makes success depend on every other member already being reachable. Initiating with only the initial primary elects it immediately, and the remaining members are then added by a reconfiguration, which does not have to wait on them.
await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["replSetInitiate"] = new BsonDocument
{
["_id"] = rsResource.Name,
["members"] = new BsonArray([membersBsonArray[0]]),
},
// NOTE: A member has no primary until this very command has run, so selecting one is
// the one thing that cannot be asked for here.
}, readPreference: ReadPreference.Nearest, cancellationToken: ct).ConfigureAwait(false);

await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["replSetReconfig"] = new BsonDocument
{
["_id"] = rsResource.Name,
["version"] = 2,
["members"] = membersBsonArray,
},
["force"] = true,
}, readPreference: ReadPreference.Nearest, cancellationToken: ct).ConfigureAwait(false);
await InitiateReplicaSetAsync(admin, rsResource.Name, membersBsonArray, ct).ConfigureAwait(false);
configured = true;
break;
}
Expand Down Expand Up @@ -551,6 +532,76 @@ await evt.Services.GetRequiredService<ResourceNotificationService>()
.WithRelationship(member, "replica set member");
}

/// <summary>
/// Initiates a brand new replica set on the initial primary and then extends it to every declared member.
/// </summary>
/// <remarks>
/// The initialization is performed in two steps, first with a single member and then with the full configuration.
/// <c>replSetInitiate</c> runs a quorum check against every host in the configuration it is handed, so initiating
/// with the full member list makes success depend on every other member already being reachable. Initiating with
/// only the initial primary does not, and the remaining members are then added by a reconfiguration.
/// </remarks>
internal static async Task InitiateReplicaSetAsync(IMongoDatabase admin, string replicaSetName, BsonArray members, CancellationToken cancellationToken)
{
await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["replSetInitiate"] = new BsonDocument
{
["_id"] = replicaSetName,
["members"] = new BsonArray([members[0]]),
},
// NOTE: A member has no primary until this very command has run, so selecting one is
// the one thing that cannot be asked for here.
}, readPreference: ReadPreference.Nearest, cancellationToken: cancellationToken).ConfigureAwait(false);

// NOTE: `replSetInitiate` returns as soon as the configuration is installed, while the member is still going
// through its own election. A reconfiguration sent straight away races that election: it is either rejected with
// `ConfigurationInProgress`, or interrupted with `InterruptedDueToReplStateChange` by the state transition that
// makes the member primary. Waiting for the member to report itself as a writable primary closes that window.
await WaitForWritablePrimaryAsync(admin, cancellationToken).ConfigureAwait(false);

await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["replSetReconfig"] = new BsonDocument
{
["_id"] = replicaSetName,
["version"] = 2,
["members"] = members,
},
["force"] = true,
}, readPreference: ReadPreference.Nearest, cancellationToken: cancellationToken).ConfigureAwait(false);
}

private static async Task WaitForWritablePrimaryAsync(IMongoDatabase admin, CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(s_primaryElectionTimeout);

try
{
while (true)
{
// NOTE: `hello` is answered in every replica set state, and `isWritablePrimary` only turns true once the
// member has finished stepping up, which is the transition that would otherwise interrupt the next command.
var hello = await admin.RunCommandAsync<BsonDocument>(
new BsonDocument("hello", 1),
readPreference: ReadPreference.Nearest,
cancellationToken: timeout.Token).ConfigureAwait(false);

if (hello.TryGetValue("isWritablePrimary", out var isWritablePrimary) && isWritablePrimary.ToBoolean())
{
return;
}

await Task.Delay(s_primaryElectionPollInterval, timeout.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
throw new DistributedApplicationException($"The initial MongoDB replica set member did not become a writable primary within {s_primaryElectionTimeout.TotalSeconds} seconds of being initiated.");
}
}

/// <summary>
/// Whether a replica set's current <c>members</c> array already says what <paramref name="desired"/> says, so that a
/// reconfiguration would change nothing.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net;
using System.Reflection;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Servers;

#pragma warning disable ASPIREMONGODB001

namespace Aspire.Hosting.MongoDB.Tests;

public class MongoDBReplicaSetInitiationTests
{
private static readonly BsonArray s_members =
[
new BsonDocument { ["_id"] = 0, ["host"] = "mongo1:27017" },
new BsonDocument { ["_id"] = 1, ["host"] = "mongo2:27017" },
new BsonDocument { ["_id"] = 2, ["host"] = "mongo3:27017" },
];

[Fact]
public async Task InitiationWaitsForTheInitialMemberToBecomeWritablePrimaryBeforeReconfiguring()
{
// The initiated member keeps reporting that it is not yet a writable primary for a few probes, and interrupts a
// reconfiguration sent before then with `InterruptedDueToReplStateChange`, like a real `mongod` stepping up does.
var admin = SteppingUpMember.Create(probesBeforePrimary: 3);

await MongoDBReplicaSetBuilderExtensions.InitiateReplicaSetAsync(admin, "rs0", s_members, CancellationToken.None);

var member = (SteppingUpMember)(object)admin;
Assert.Equal(["replSetInitiate", "hello", "hello", "hello", "replSetReconfig"], member.Commands.Select(c => c.GetElement(0).Name));

var initiate = member.Commands[0]["replSetInitiate"].AsBsonDocument;
Assert.Equal("rs0", initiate["_id"].AsString);
Assert.Equal(new BsonArray([s_members[0]]), initiate["members"].AsBsonArray);

var reconfig = member.Commands[^1];
Assert.True(reconfig["force"].AsBoolean);
Assert.Equal(2, reconfig["replSetReconfig"]["version"].AsInt32);
Assert.Equal(s_members, reconfig["replSetReconfig"]["members"].AsBsonArray);
}

[Fact]
public async Task InitiationStopsWaitingForPrimaryWhenCancelled()
{
using var cancellation = new CancellationTokenSource();
var admin = SteppingUpMember.Create(probesBeforePrimary: int.MaxValue, onProbe: probe =>
{
if (probe == 2)
{
cancellation.Cancel();
}
});

await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
MongoDBReplicaSetBuilderExtensions.InitiateReplicaSetAsync(admin, "rs0", s_members, cancellation.Token));

var member = (SteppingUpMember)(object)admin;
Assert.DoesNotContain(member.Commands, c => c.GetElement(0).Name == "replSetReconfig");
}

public class SteppingUpMember : DispatchProxy
{
private int _probesBeforePrimary;
private int _probes;
private bool _initiated;
private Action<int>? _onProbe;

public List<BsonDocument> Commands { get; } = [];

public static IMongoDatabase Create(int probesBeforePrimary, Action<int>? onProbe = null)
{
var admin = Create<IMongoDatabase, SteppingUpMember>();
var member = (SteppingUpMember)(object)admin;
member._probesBeforePrimary = probesBeforePrimary;
member._onProbe = onProbe;
return admin;
}

private bool IsWritablePrimary => _initiated && _probes >= _probesBeforePrimary;

protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
{
if (targetMethod is not { Name: nameof(IMongoDatabase.RunCommandAsync) } || args is not [BsonDocumentCommand<BsonDocument> command, _, CancellationToken cancellationToken])
{
throw new NotSupportedException($"Unexpected call to '{targetMethod?.Name}'.");
}

cancellationToken.ThrowIfCancellationRequested();
Commands.Add(command.Document);

switch (command.Document.GetElement(0).Name)
{
case "replSetInitiate":
_initiated = true;
return Task.FromResult(new BsonDocument("ok", 1));

case "hello":
_probes++;
_onProbe?.Invoke(_probes);
return Task.FromResult(new BsonDocument { ["isWritablePrimary"] = IsWritablePrimary, ["ok"] = 1 });

case "replSetReconfig" when !IsWritablePrimary:
var result = new BsonDocument { ["ok"] = 0, ["code"] = 11602, ["codeName"] = "InterruptedDueToReplStateChange" };
var connectionId = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("mongo1", 27017)));
return Task.FromException<BsonDocument>(new MongoNodeIsRecoveringException(connectionId, command.Document, result));

case "replSetReconfig":
return Task.FromResult(new BsonDocument("ok", 1));

default:
throw new NotSupportedException($"Unexpected command '{command.Document}'.");
}
}
}
}
Loading