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
10 changes: 9 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@ connection to the primary is lost, and - because the announcement is delivered o
notices when the node last named as primary is still connected but now reports itself as a replica (a failover where nothing disconnected,
such as a primary demoted in place). In that last case the client re-asks sentinel for the current primary and follows its answer, even to
a node at an address it has never seen; while sentinel still names the demoted node (sentinel itself has not yet failed over), the client
keeps asking without tearing down or reconfiguring the healthy connections.
keeps asking without tearing down or reconfiguring the healthy connections. A command answered with `READONLY` is the same signal: the node
is marked as a replica at once, rather than at the next role check (`ConfigCheckSeconds`), and the client asks sentinel on its next heartbeat.
Sentinel is queried asynchronously: waiting on a slow or unreachable sentinel holds no thread-pool thread, and a sentinel query waits up to
`AsyncTimeout`, also when the connection is made with the synchronous `Connect`. A sentinel whose `SENTINEL MASTER` reply holds the primary
down (`s_down`/`o_down`) is passed over for one that does not. When every sentinel that answers holds it down, the client connects to
the address `get-master-addr-by-name` gives (during a failover, the replica being promoted) rather than to any endpoint of its own
configuration, and moves on once a sentinel names a healthy primary. A sentinel without a usable `SENTINEL MASTER` reply - the subcommand is
unknown or refused, such as to an ACL user allowed only `get-master-addr-by-name`, or the reply has no flags - is asked with
`get-master-addr-by-name` instead.

An overview of mapping between the `string` and `ConfigurationOptions` representation is shown below, but you can switch between them trivially:

Expand Down
739 changes: 467 additions & 272 deletions src/StackExchange.Redis/ConnectionMultiplexer.Sentinel.cs

Large diffs are not rendered by default.

34 changes: 25 additions & 9 deletions src/StackExchange.Redis/ConnectionMultiplexer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ public sealed partial class ConnectionMultiplexer : IInternalConnectionMultiplex

private readonly bool _isSentinel;

/// <summary>Whether this multiplexer was made to talk to sentinels, rather than to the data nodes they manage.</summary>
internal bool IsSentinel => _isSentinel;

internal CommandMap CommandMap { get; }
internal EndPointCollection EndPoints { get; }
internal ConfigurationOptions RawConfig { get; }
Expand Down Expand Up @@ -692,23 +695,34 @@ static async Task<ConnectionMultiplexer> ApplyAfterConnectAsync(Task<ConnectionM
}
}

private static async Task<ConnectionMultiplexer> ConnectImplAsync(ConfigurationOptions configuration, TextWriter? writer = null, ServerType? serverType = null, Availability.CircuitBreaker? groupCircuitBreaker = null, bool isGroupMember = false, Caching.CacheOptions? groupClientCache = null)
private static async Task<ConnectionMultiplexer> ConnectImplAsync(ConfigurationOptions configuration, TextWriter? writer = null, ServerType? serverType = null, Availability.CircuitBreaker? groupCircuitBreaker = null, bool isGroupMember = false, Caching.CacheOptions? groupClientCache = null, EndPointCollection? endpoints = null, bool synchronousConnect = false)
{
IDisposable? killMe = null;
ConnectionMultiplexer? killMe = null;
EventHandler<ConnectionFailedEventArgs>? connectHandler = null;
ConnectionMultiplexer? muxer = null;
var configLogger = configuration.LoggerFactory?.CreateLogger<ConnectionMultiplexer>();
var log = configLogger.With(writer);
try
{
var sw = ValueStopwatch.StartNew();
log?.LogInformationConnectingAsync(RuntimeInformation.FrameworkDescription, Utils.GetLibVersion());
if (synchronousConnect) log?.LogInformationConnectingSync(RuntimeInformation.FrameworkDescription, Utils.GetLibVersion());
else log?.LogInformationConnectingAsync(RuntimeInformation.FrameworkDescription, Utils.GetLibVersion());

muxer = CreateMultiplexer(configuration, log, serverType, out connectHandler, groupCircuitBreaker: groupCircuitBreaker, isGroupMember: isGroupMember, groupClientCache: groupClientCache);
muxer = CreateMultiplexer(configuration, log, serverType, out connectHandler, endpoints: endpoints, groupCircuitBreaker: groupCircuitBreaker, isGroupMember: isGroupMember, groupClientCache: groupClientCache);
killMe = muxer;
Interlocked.Increment(ref muxer._connectAttemptCount);
bool configured = await muxer.ReconfigureAsync(first: true, reconfigureAll: false, log, null, "connect").ObserveErrors().ForAwait();
if (!configured)
var configure = muxer.ReconfigureAsync(first: true, reconfigureAll: false, log, null, "connect").ObserveErrors();
if (synchronousConnect && !configure.IsCompleted
&& !await configure.TimeoutAfter(muxer.SyncConnectTimeout(true)).ForAwait())
{
// The public sync Sentinel boundary retains ConnectImpl's soft timeout, without blocking a
// worker inside the shared async core. Reconfigure keeps running on the returned multiplexer.
var ex = ExceptionFactory.UnableToConnect(muxer, "ConnectTimeout");
if (configuration.AbortOnConnectFail) throw ex;
muxer.LastException = ex;
muxer.Logger?.LogErrorSyncConnectTimeout(ex, ex.Message);
}
else if (!await configure.ForAwait())
{
throw ExceptionFactory.UnableToConnect(muxer, muxer.failureMessage);
}
Expand All @@ -724,7 +738,9 @@ private static async Task<ConnectionMultiplexer> ConnectImplAsync(ConfigurationO
muxer.InitializeSentinel(log);
}

await configuration.AfterConnectAsync(muxer, s => log?.LogInformationAfterConnect(s)).ForAwait();
var afterConnect = configuration.AfterConnectAsync(muxer, s => log?.LogInformationAfterConnect(s)).ObserveErrors();
if (synchronousConnect) await afterConnect.TimeoutAfter(muxer.SyncConnectTimeout(true)).ForAwait();
else await afterConnect.ForAwait();

log?.LogInformationTotalConnectTime(sw.ElapsedMilliseconds);

Expand All @@ -733,7 +749,7 @@ private static async Task<ConnectionMultiplexer> ConnectImplAsync(ConfigurationO
finally
{
if (connectHandler != null && muxer != null) muxer.ConnectionFailed -= connectHandler;
if (killMe != null) try { killMe.Dispose(); } catch { }
if (killMe != null) try { await killMe.DisposeAsync().ForAwait(); } catch { }
if (log is TextWriterLogger twLogger) twLogger.Release();
}
}
Expand Down Expand Up @@ -1859,7 +1875,7 @@ internal static void ActivateServer(ServerEndPoint server, ILogger? log)

/// <summary>
/// Claims the reconfigure gate without running a reconfigure, so that work that must not interleave with
/// one (such as <see cref="SwitchPrimary"/> rewriting the endpoint list) can make its pre-checks and its
/// one (such as <see cref="SwitchPrimaryAsync"/> rewriting the endpoint list) can make its pre-checks and its
/// side effects atomic with respect to competing reconfigures. A successful claim MUST be handed to
/// <see cref="ReconfigureAsync(bool, bool, ILogger, EndPoint, string, bool, CommandFlags, bool)"/> with
/// <c>claimed: true</c> (which releases it however it exits), or released via
Expand Down
9 changes: 9 additions & 0 deletions src/StackExchange.Redis/Contexts/RespClientConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,15 @@ protected override bool TryHandOff(ReadOnlySpan<byte> frame, IRespMessage messag
exec.Profile?.SetResponseReceived();
}

// A sentinel-managed write can reveal a demotion before the role check does. Only mark the local
// role here; the sentinel owner's heartbeat resolves the primary, and no reconfigure starts on the
// read loop. Standalone and cluster keep their existing error behaviour.
if (frame.Length > 1 && (RespPrefix)frame[0] == RespPrefix.SimpleError && frame.Slice(1).StartsWith("READONLY"u8)
&& Server is { IsReplica: false } demoted && demoted.Multiplexer.IsSentinelManaged)
{
demoted.MarkAsReplicaWithoutReconfigure();
}

// one byte of work for every reply that is not an error, which is nearly all of them
if (!RespRedirect.TryParse(frame, out var redirect)) return false;
if (message is not RespPayloadOperation operation) return false;
Expand Down
18 changes: 14 additions & 4 deletions src/StackExchange.Redis/Contexts/RespConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,12 @@ internal RespConnectionManager(ConnectionMultiplexer multiplexer)
_topology = new RespTopology(SeedTopology(multiplexer))
{
// only worth an INFO REPLICATION per connection when there is something to prefer a
// replica OVER; a cluster learns the same thing from a reply it reads anyway
WantsRoles = multiplexer.RawConfig.EndPoints.Count > 1,
// replica OVER; a cluster learns the same thing from a reply it reads anyway. The endpoints the
// multiplexer was given, not the configured ones: a sentinel-managed connection is configured
// with the sentinel and handed the primary and replicas sentinel names - and its primary can
// move under it, which only a role read notices.
WantsRoles = multiplexer.EndPoints.Count > 1
|| (multiplexer.RawConfig.ServiceName is not null && !multiplexer.IsSentinel),

// and whatever it learns goes straight back out: IsReplica is what refuses a write
// client-side, so a role this core knows and the selector does not is a write that never
Expand Down Expand Up @@ -907,7 +911,7 @@ private RespEndpointExecutor Endpoint(EndPoint endpoint)
(command, commandAndKey) => ExceptionFactory.NoConnectionAvailable(
_multiplexer,
null,
_multiplexer.GetServerEndPoint(endpoint, ServerProvenance.Configured, activate: false),
ModelledServer(endpoint),
default,
command,
commandAndKey),
Expand All @@ -928,9 +932,15 @@ private RespEndpointExecutor Endpoint(EndPoint endpoint)
/// server already read. While both cores existed that record was what kept them agreeing; a second
/// copy here would let two parts of the client disagree about the same server, which is the failure
/// mode design notes section 9 set out to remove rather than reproduce.
/// <para>
/// <b>Looked up, never created.</b> These callbacks can outlive the server: a heartbeat role read that
/// captured an executor just before its endpoint was retired fails with "no connection", and describing
/// that failure through <c>GetServerEndPoint</c> re-created the retired server - back in the snapshot,
/// reconnecting to a node sentinel had told the client to leave.
/// </para>
/// </remarks>
private ServerEndPoint? ModelledServer(EndPoint endpoint)
=> _multiplexer.GetServerEndPoint(endpoint, ServerProvenance.Configured, activate: false);
=> _multiplexer.TryResolveServerEndPoint(endpoint);

/// <summary>Announce that an endpoint's circuit breaker has judged it unhealthy.</summary>
/// <param name="endpoint">The endpoint whose breaker tripped.</param>
Expand Down
6 changes: 6 additions & 0 deletions src/StackExchange.Redis/ServerEndPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ public bool IsReplica
}
}

internal void MarkAsReplicaWithoutReconfigure()
{
Volatile.Write(ref isReplica, true);
ClearMemoized();
}

public bool ReplicaReadOnly
{
get => replicaReadOnly;
Expand Down
Loading
Loading