Skip to content
Closed
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 @@ -25,6 +25,7 @@ public static class MongoDBReplicaSetBuilderExtensions
private const int MaxVotingMembers = 7;
private const string ReplicaSetAlreadyInitializedCodeName = "AlreadyInitialized";
private const string ReplicaSetNotYetInitializedCodeName = "NotYetInitialized";
private const string ReplicaSetInterruptedDueToReplStateChangeCodeName = "InterruptedDueToReplStateChange";
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);
Expand Down Expand Up @@ -214,6 +215,14 @@ await member.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false)
// Keep probing. A newly inserted member can be uninitialized while another declared member
// still holds the persisted replica set configuration that must be preserved.
}
catch (MongoCommandException ex) when (IsTransientReplicaSetConfigurationError(ex.CodeName))
{
// A member can interrupt config reads while transitioning during initialization. Its persisted
// configuration is unknown, so retry before deciding whether the set needs to be initialized.
allMembersUninitialized = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line has no test protecting it. The replSetGetConfig / 11602 scenario in VerifyReplicaSetConfigurationHandlesCommandErrors only runs against a fresh set. If this assignment were removed, the failure would be swallowed and replSetInitiate would still succeed on mongo1, with the same failure count and member IDs, so the test would still pass. (Worked out from the code, not run.)

The case it guards: a persisted member returns 11602 while a newly prepended empty member returns NotYetInitialized. Without this line, Aspire runs replSetInitiate on the empty member, creating a new set instead of extending the persisted one. The current code handles this correctly; nothing stops it regressing.

Suggested fix: add a case based on VerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsages(MemberPrepended) that sets the fail point on the persisted member, then asserts that its data and member IDs survive.

lastConfigurationError = ex;
logger.LogInformation("MongoDB replica set member '{MemberName}' is recovering", memberConnection.Resource.Name);
}
}

if (newest is { } existing)
Expand Down Expand Up @@ -271,7 +280,7 @@ await admin.RunCommandAsync<BsonDocument>(
configured = true;
break;
}
catch (MongoCommandException ex) when (ex.CodeName is NewReplicaSetConfigurationIncompatibleCodeName or ConfigurationInProgressCodeName)
catch (MongoCommandException ex) when (ex.CodeName is NewReplicaSetConfigurationIncompatibleCodeName or ConfigurationInProgressCodeName || IsTransientReplicaSetConfigurationError(ex.CodeName))
{
// NOTE: `ConfigurationInProgress` is always transient. `NewReplicaSetConfigurationIncompatible`
// is returned both for a version that another update has already moved past, which a retry
Expand Down Expand Up @@ -324,9 +333,10 @@ await admin.RunCommandAsync<BsonDocument>(new BsonDocument
configured = true;
break;
}
catch (MongoCommandException initiateEx) when (initiateEx.CodeName is ReplicaSetAlreadyInitializedCodeName or NewReplicaSetConfigurationIncompatibleCodeName or ConfigurationInProgressCodeName)
catch (MongoCommandException initiateEx) when (initiateEx.CodeName is ReplicaSetAlreadyInitializedCodeName or NewReplicaSetConfigurationIncompatibleCodeName or ConfigurationInProgressCodeName || IsTransientReplicaSetConfigurationError(initiateEx.CodeName))
{
// NOTE: Happens when in race with another concurrent process trying to initialize the replica set; so we retry the whole operation
// Re-probe after a recovery interruption, including when initiation succeeded but the
// following reconfiguration failed, so the persisted configuration is preserved.
lastConfigurationError = initiateEx;
logger.LogInformation("Initiating the replica set failed: {Reason}", initiateEx.Message);
}
Expand Down Expand Up @@ -662,6 +672,14 @@ internal static BsonArray BuildMembersConfiguration(IReadOnlyList<MemberHosts> m
return result;
}

/// <summary>
/// Identifies recovery interruptions that can be retried while configuring a replica set.
/// </summary>
internal static bool IsTransientReplicaSetConfigurationError(string? codeName)
{
return codeName is ReplicaSetInterruptedDueToReplStateChangeCodeName;
}

/// <summary>
/// The addresses a replica set member is reachable at, from within the container network (<paramref name="Internal"/>)
/// and from outside of it (<paramref name="External"/>).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ namespace Aspire.Hosting.MongoDB.Tests;

public class AddMongoDBReplicaSetTests(ITestOutputHelper testOutputHelper)
{
[Fact]
public void InterruptedDueToReplStateChangeIsTransientDuringReplicaSetConfiguration()
{
Assert.True(MongoDBReplicaSetBuilderExtensions.IsTransientReplicaSetConfigurationError("InterruptedDueToReplStateChange"));
}

[Theory]
[InlineData("NotYetInitialized")]
[InlineData("Unauthorized")]
[InlineData(null)]
public void OtherCommandErrorsAreNotTransientDuringReplicaSetConfiguration(string? codeName)
{
Assert.False(MongoDBReplicaSetBuilderExtensions.IsTransientReplicaSetConfigurationError(codeName));
}

[Fact]
public void AddMongoDBReplicaSetAddsHealthCheckAnnotationToResource()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,93 @@ await pipeline.ExecuteAsync(async token =>
await app.StopAsync();
}

[Theory]
[InlineData("replSetGetConfig", 11602, true, 1)]
[InlineData("replSetInitiate", 11602, true, 1)]
[InlineData("replSetReconfig", 11602, true, 1)]
[InlineData("replSetGetConfig", 13, false, 1)]
[InlineData("replSetInitiate", 13, false, 1)]
[InlineData("replSetReconfig", 13, false, 1)]
[InlineData("replSetReconfig", 11602, false, 10)]
[RequiresFeature(TestFeature.Docker)]
[RequiresFeature(TestFeature.DevCert)]
public async Task VerifyReplicaSetConfigurationHandlesCommandErrors(string command, int errorCode, bool shouldRecover, int expectedFailures)
{
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper);

var mongo = builder.AddMongoDB("mongo1")
.WithArgs("--setParameter", "enableTestCommands=1");
var secondMember = builder.AddMongoDB("mongo2");
long initialFailureCount = 0;
var rs = builder.AddMongoDBReplicaSet("rs0")
.WithMember(mongo)
.WithMember(secondMember)
.OnBeforeResourceStarted(async (_, evt, ct) =>
{
await evt.Services.GetRequiredService<ResourceNotificationService>()
.WaitForResourceHealthyAsync(mongo.Resource.Name, ct);

var connectionString = await mongo.Resource.ConnectionStringExpression.GetValueAsync(ct);
using var client = new MongoClient(connectionString);
var admin = client.GetDatabase("admin");

// Inject the server response before Aspire configures the set, rather than racing an election.
// MongoDB's failCommand shape is documented by its own regression tests:
// https://github.com/mongodb/mongo/blob/v9.0/jstests/core/testing/failcommand_failpoint.js
var result = await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["configureFailPoint"] = "failCommand",
["mode"] = shouldRecover ? new BsonDocument("times", 1) : new BsonString("alwaysOn"),
["data"] = new BsonDocument
{
["failCommands"] = new BsonArray { command },
["errorCode"] = errorCode,
},
}, readPreference: ReadPreference.Nearest, cancellationToken: ct);
initialFailureCount = result["count"].ToInt64();
});

using var app = builder.Build();
await app.StartAsync(cts.Token);

if (shouldRecover)
{
await app.ResourceNotifications.WaitForResourceHealthyAsync(rs.Resource.Name, cts.Token);
}
else
{
await app.ResourceNotifications.WaitForResourceAsync(rs.Resource.Name, KnownResourceStates.FailedToStart, cts.Token);
}

using var memberClient = new MongoClient(await mongo.Resource.ConnectionStringExpression.GetValueAsync(cts.Token));
var admin = memberClient.GetDatabase("admin");
var disabled = await admin.RunCommandAsync<BsonDocument>(new BsonDocument
{
["configureFailPoint"] = "failCommand",
["mode"] = "off",
}, readPreference: ReadPreference.Nearest, cancellationToken: cts.Token);
Assert.Equal(expectedFailures, disabled["count"].ToInt64() - initialFailureCount);

if (shouldRecover)
{
var connectionString = await rs.Resource.ConnectionStringExpression.GetValueAsync(cts.Token);
using var client = new MongoClient(connectionString);
var memberIds = await GetMemberIdsByHostAsync(client, cts.Token);
Assert.Equal(2, memberIds.Count);
Assert.Equal(0, memberIds["mongo1:27017"]);
Assert.Equal(1, memberIds["mongo2:27017"]);

var db = client.GetDatabase(DbName);
var pipeline = new ResiliencePipelineBuilder()
.AddRetry(new() { MaxRetryAttempts = 10, Delay = TimeSpan.FromSeconds(1) })
.Build();
await pipeline.ExecuteAsync(async token => await CreateTestDataWithReplicaSetFeaturesAsync(db, token), cts.Token);
}

await app.StopAsync(cts.Token);
}

[Fact]
[RequiresFeature(TestFeature.Docker)]
[RequiresFeature(TestFeature.DevCert)]
Expand Down
Loading