/
ConnectionMultiplexer.cs
2097 lines (1896 loc) · 92.3 KB
/
ConnectionMultiplexer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Pipelines.Sockets.Unofficial;
using StackExchange.Redis.Profiling;
namespace StackExchange.Redis
{
/// <summary>
/// Represents an inter-related group of connections to redis servers.
/// A reference to this should be held and re-used.
/// </summary>
/// <remarks><seealso href="https://stackexchange.github.io/StackExchange.Redis/PipelinesMultiplexers"/></remarks>
public sealed partial class ConnectionMultiplexer : IInternalConnectionMultiplexer // implies : IConnectionMultiplexer and : IDisposable
{
internal const int MillisecondsPerHeartbeat = 1000;
// This gets accessed for every received event; let's make sure we can process it "raw"
internal readonly byte[]? ConfigurationChangedChannel;
// Unique identifier used when tracing
internal readonly byte[] UniqueId = Guid.NewGuid().ToByteArray();
/// <summary>
/// Tracks overall connection multiplexer counts.
/// </summary>
internal int _connectAttemptCount = 0, _connectCompletedCount = 0, _connectionCloseCount = 0;
private long syncTimeouts, fireAndForgets, asyncTimeouts;
private string? failureMessage, activeConfigCause;
private IDisposable? pulse;
private readonly Hashtable servers = new Hashtable();
private volatile ServerSnapshot _serverSnapshot = ServerSnapshot.Empty;
private volatile bool _isDisposed;
internal bool IsDisposed => _isDisposed;
internal CommandMap CommandMap { get; }
internal EndPointCollection EndPoints { get; }
internal ConfigurationOptions RawConfig { get; }
internal ServerSelectionStrategy ServerSelectionStrategy { get; }
internal Exception? LastException { get; set; }
ConfigurationOptions IInternalConnectionMultiplexer.RawConfig => RawConfig;
private int _activeHeartbeatErrors, lastHeartbeatTicks;
internal long LastHeartbeatSecondsAgo =>
pulse is null
? -1
: unchecked(Environment.TickCount - Thread.VolatileRead(ref lastHeartbeatTicks)) / 1000;
private static int lastGlobalHeartbeatTicks = Environment.TickCount;
internal static long LastGlobalHeartbeatSecondsAgo =>
unchecked(Environment.TickCount - Thread.VolatileRead(ref lastGlobalHeartbeatTicks)) / 1000;
/// <summary>
/// Should exceptions include identifiable details? (key names, additional .Data annotations)
/// </summary>
[Obsolete($"Please use {nameof(ConfigurationOptions)}.{nameof(ConfigurationOptions.IncludeDetailInExceptions)} instead - this will be removed in 3.0.")]
public bool IncludeDetailInExceptions
{
get => RawConfig.IncludeDetailInExceptions;
set => RawConfig.IncludeDetailInExceptions = value;
}
/// <summary>
/// Should exceptions include performance counter details?
/// </summary>
/// <remarks>
/// CPU usage, etc - note that this can be problematic on some platforms.
/// </remarks>
[Obsolete($"Please use {nameof(ConfigurationOptions)}.{nameof(ConfigurationOptions.IncludePerformanceCountersInExceptions)} instead - this will be removed in 3.0.")]
public bool IncludePerformanceCountersInExceptions
{
get => RawConfig.IncludePerformanceCountersInExceptions;
set => RawConfig.IncludePerformanceCountersInExceptions = value;
}
/// <summary>
/// Gets the synchronous timeout associated with the connections.
/// </summary>
public int TimeoutMilliseconds => RawConfig.SyncTimeout;
/// <summary>
/// Gets the asynchronous timeout associated with the connections.
/// </summary>
internal int AsyncTimeoutMilliseconds => RawConfig.AsyncTimeout;
/// <summary>
/// Gets the client-name that will be used on all new connections.
/// </summary>
/// <remarks>
/// We null coalesce here instead of in Options so that we don't populate it everywhere (e.g. .ToString()), given it's a default.
/// </remarks>
public string ClientName => RawConfig.ClientName ?? RawConfig.Defaults.ClientName;
/// <summary>
/// Gets the configuration of the connection.
/// </summary>
public string Configuration => RawConfig.ToString();
/// <summary>
/// Indicates whether any servers are connected.
/// </summary>
public bool IsConnected
{
get
{
var tmp = GetServerSnapshot();
for (int i = 0; i < tmp.Length; i++)
if (tmp[i].IsConnected) return true;
return false;
}
}
/// <summary>
/// Indicates whether any servers are currently trying to connect.
/// </summary>
public bool IsConnecting
{
get
{
var tmp = GetServerSnapshot();
for (int i = 0; i < tmp.Length; i++)
if (tmp[i].IsConnecting) return true;
return false;
}
}
static ConnectionMultiplexer()
{
SetAutodetectFeatureFlags();
}
private ConnectionMultiplexer(ConfigurationOptions configuration, ServerType? serverType = null)
{
RawConfig = configuration ?? throw new ArgumentNullException(nameof(configuration));
EndPoints = RawConfig.EndPoints.Clone();
EndPoints.SetDefaultPorts(serverType, ssl: RawConfig.Ssl);
var map = CommandMap = configuration.GetCommandMap(serverType);
if (!string.IsNullOrWhiteSpace(configuration.Password))
{
map.AssertAvailable(RedisCommand.AUTH);
}
if (!map.IsAvailable(RedisCommand.ECHO) && !map.IsAvailable(RedisCommand.PING) && !map.IsAvailable(RedisCommand.TIME))
{
// I mean really, give me a CHANCE! I need *something* to check the server is available to me...
// see also: SendTracer (matching logic)
map.AssertAvailable(RedisCommand.EXISTS);
}
OnCreateReaderWriter(configuration);
ServerSelectionStrategy = new ServerSelectionStrategy(this);
var configChannel = configuration.ConfigurationChannel;
if (!string.IsNullOrWhiteSpace(configChannel))
{
ConfigurationChangedChannel = Encoding.UTF8.GetBytes(configChannel);
}
lastHeartbeatTicks = Environment.TickCount;
}
private static ConnectionMultiplexer CreateMultiplexer(ConfigurationOptions configuration, LogProxy? log, ServerType? serverType, out EventHandler<ConnectionFailedEventArgs>? connectHandler)
{
var muxer = new ConnectionMultiplexer(configuration, serverType);
connectHandler = null;
if (log is not null)
{
// Create a detachable event-handler to log detailed errors if something happens during connect/handshake
connectHandler = (_, a) =>
{
try
{
lock (log.SyncLock) // Keep the outer and any inner errors contiguous
{
var ex = a.Exception;
log?.WriteLine($"Connection failed: {Format.ToString(a.EndPoint)} ({a.ConnectionType}, {a.FailureType}): {ex?.Message ?? "(unknown)"}");
while ((ex = ex?.InnerException) != null)
{
log?.WriteLine($"> {ex.Message}");
}
}
}
catch { }
};
muxer.ConnectionFailed += connectHandler;
}
return muxer;
}
/// <summary>
/// Get summary statistics associated with all servers in this multiplexer.
/// </summary>
public ServerCounters GetCounters()
{
var counters = new ServerCounters(null);
var snapshot = GetServerSnapshot();
for (int i = 0; i < snapshot.Length; i++)
{
counters.Add(snapshot[i].GetCounters());
}
return counters;
}
internal async Task MakePrimaryAsync(ServerEndPoint server, ReplicationChangeOptions options, LogProxy? log)
{
_ = server ?? throw new ArgumentNullException(nameof(server));
var cmd = server.GetFeatures().ReplicaCommands ? RedisCommand.REPLICAOF : RedisCommand.SLAVEOF;
CommandMap.AssertAvailable(cmd);
if (!RawConfig.AllowAdmin)
{
throw ExceptionFactory.AdminModeNotEnabled(RawConfig.IncludeDetailInExceptions, cmd, null, server);
}
var srv = new RedisServer(this, server, null);
if (!srv.IsConnected)
{
throw ExceptionFactory.NoConnectionAvailable(this, null, server, GetServerSnapshot(), command: cmd);
}
const CommandFlags flags = CommandFlags.NoRedirect;
Message msg;
log?.WriteLine($"Checking {Format.ToString(srv.EndPoint)} is available...");
try
{
await srv.PingAsync(flags); // if it isn't happy, we're not happy
}
catch (Exception ex)
{
log?.WriteLine($"Operation failed on {Format.ToString(srv.EndPoint)}, aborting: {ex.Message}");
throw;
}
var nodes = GetServerSnapshot().ToArray(); // Have to array because async/await
RedisValue newPrimary = Format.ToString(server.EndPoint);
// try and write this everywhere; don't worry if some folks reject our advances
if (RawConfig.TryGetTieBreaker(out var tieBreakerKey)
&& options.HasFlag(ReplicationChangeOptions.SetTiebreaker)
&& CommandMap.IsAvailable(RedisCommand.SET))
{
foreach (var node in nodes)
{
if (!node.IsConnected || node.IsReplica) continue;
log?.WriteLine($"Attempting to set tie-breaker on {Format.ToString(node.EndPoint)}...");
msg = Message.Create(0, flags | CommandFlags.FireAndForget, RedisCommand.SET, tieBreakerKey, newPrimary);
try
{
await node.WriteDirectAsync(msg, ResultProcessor.DemandOK);
}
catch { }
}
}
// stop replicating, promote to a standalone primary
log?.WriteLine($"Making {Format.ToString(srv.EndPoint)} a primary...");
try
{
await srv.ReplicaOfAsync(null, flags);
}
catch (Exception ex)
{
log?.WriteLine($"Operation failed on {Format.ToString(srv.EndPoint)}, aborting: {ex.Message}");
throw;
}
// also, in case it was a replica a moment ago, and hasn't got the tie-breaker yet, we re-send the tie-breaker to this one
if (!tieBreakerKey.IsNull && !server.IsReplica)
{
log?.WriteLine($"Resending tie-breaker to {Format.ToString(server.EndPoint)}...");
msg = Message.Create(0, flags | CommandFlags.FireAndForget, RedisCommand.SET, tieBreakerKey, newPrimary);
try
{
await server.WriteDirectAsync(msg, ResultProcessor.DemandOK);
}
catch { }
}
// There's an inherent race here in zero-latency environments (e.g. when Redis is on localhost) when a broadcast is specified
// The broadcast can get back from redis and trigger a reconfigure before we get a chance to get to ReconfigureAsync() below
// This results in running an outdated reconfiguration and the .CompareExchange() (due to already running a reconfiguration)
// failing...making our needed reconfiguration a no-op.
// If we don't block *that* run, then *our* run (at low latency) gets blocked. Then we're waiting on the
// ConfigurationOptions.ConfigCheckSeconds interval to identify the current (created by this method call) topology correctly.
var blockingReconfig = Interlocked.CompareExchange(ref activeConfigCause, "Block: Pending Primary Reconfig", null) == null;
// Try and broadcast the fact a change happened to all members
// We want everyone possible to pick it up.
// We broadcast before *and after* the change to remote members, so that they don't go without detecting a change happened.
// This eliminates the race of pub/sub *then* re-slaving happening, since a method both precedes and follows.
async Task BroadcastAsync(ServerEndPoint[] serverNodes)
{
if (options.HasFlag(ReplicationChangeOptions.Broadcast)
&& ConfigurationChangedChannel != null
&& CommandMap.IsAvailable(RedisCommand.PUBLISH))
{
RedisValue channel = ConfigurationChangedChannel;
foreach (var node in serverNodes)
{
if (!node.IsConnected) continue;
log?.WriteLine($"Broadcasting via {Format.ToString(node.EndPoint)}...");
msg = Message.Create(-1, flags | CommandFlags.FireAndForget, RedisCommand.PUBLISH, channel, newPrimary);
await node.WriteDirectAsync(msg, ResultProcessor.Int64);
}
}
}
// Send a message before it happens - because afterwards a new replica may be unresponsive
await BroadcastAsync(nodes);
if (options.HasFlag(ReplicationChangeOptions.ReplicateToOtherEndpoints))
{
foreach (var node in nodes)
{
if (node == server || node.ServerType != ServerType.Standalone) continue;
log?.WriteLine($"Replicating to {Format.ToString(node.EndPoint)}...");
msg = RedisServer.CreateReplicaOfMessage(node, server.EndPoint, flags);
await node.WriteDirectAsync(msg, ResultProcessor.DemandOK);
}
}
// ...and send one after it happens - because the first broadcast may have landed on a secondary client
// and it can reconfigure before any topology change actually happened. This is most likely to happen
// in low-latency environments.
await BroadcastAsync(nodes);
// and reconfigure the muxer
log?.WriteLine("Reconfiguring all endpoints...");
// Yes, there is a tiny latency race possible between this code and the next call, but it's far more minute than before.
// The effective gap between 0 and > 0 (likely off-box) latency is something that may never get hit here by anyone.
if (blockingReconfig)
{
Interlocked.Exchange(ref activeConfigCause, null);
}
if (!await ReconfigureAsync(first: false, reconfigureAll: true, log, srv.EndPoint, cause: nameof(MakePrimaryAsync)))
{
log?.WriteLine("Verifying the configuration was incomplete; please verify");
}
}
internal void CheckMessage(Message message)
{
if (!RawConfig.AllowAdmin && message.IsAdmin)
{
throw ExceptionFactory.AdminModeNotEnabled(RawConfig.IncludeDetailInExceptions, message.Command, message, null);
}
if (message.Command != RedisCommand.UNKNOWN)
{
CommandMap.AssertAvailable(message.Command);
}
// using >= here because we will be adding 1 for the command itself (which is an argument for the purposes of the multi-bulk protocol)
if (message.ArgCount >= PhysicalConnection.REDIS_MAX_ARGS)
{
throw ExceptionFactory.TooManyArgs(message.CommandAndKey, message.ArgCount);
}
}
internal bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool isMoved) =>
ServerSelectionStrategy.TryResend(hashSlot, message, endpoint, isMoved);
/// <summary>
/// Wait for a given asynchronous operation to complete (or timeout).
/// </summary>
/// <param name="task">The task to wait on.</param>
public void Wait(Task task)
{
_ = task ?? throw new ArgumentNullException(nameof(task));
try
{
if (!task.Wait(TimeoutMilliseconds))
{
throw new TimeoutException();
}
}
catch (AggregateException aex) when (IsSingle(aex))
{
throw aex.InnerExceptions[0];
}
}
/// <summary>
/// Wait for a given asynchronous operation to complete (or timeout).
/// </summary>
/// <typeparam name="T">The type contains in the task to wait on.</typeparam>
/// <param name="task">The task to wait on.</param>
public T Wait<T>(Task<T> task)
{
_ = task ?? throw new ArgumentNullException(nameof(task));
try
{
if (!task.Wait(TimeoutMilliseconds))
{
throw new TimeoutException();
}
}
catch (AggregateException aex) when (IsSingle(aex))
{
throw aex.InnerExceptions[0];
}
return task.Result;
}
private static bool IsSingle(AggregateException aex)
{
try
{
return aex?.InnerExceptions.Count == 1;
}
catch
{
return false;
}
}
/// <summary>
/// Wait for the given asynchronous operations to complete (or timeout).
/// </summary>
/// <param name="tasks">The tasks to wait on.</param>
public void WaitAll(params Task[] tasks)
{
_ = tasks ?? throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return;
if (!Task.WaitAll(tasks, TimeoutMilliseconds))
{
throw new TimeoutException();
}
}
private bool WaitAllIgnoreErrors(Task[] tasks)
{
_ = tasks ?? throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return true;
var watch = ValueStopwatch.StartNew();
try
{
// If no error, great
if (Task.WaitAll(tasks, TimeoutMilliseconds)) return true;
}
catch
{ }
// If we get problems, need to give the non-failing ones time to be fair and reasonable
for (int i = 0; i < tasks.Length; i++)
{
var task = tasks[i];
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted)
{
var remaining = TimeoutMilliseconds - watch.ElapsedMilliseconds;
if (remaining <= 0) return false;
try
{
task.Wait(remaining);
}
catch
{ }
}
}
return false;
}
private static async Task<bool> WaitAllIgnoreErrorsAsync(string name, Task[] tasks, int timeoutMilliseconds, LogProxy? log, [CallerMemberName] string? caller = null, [CallerLineNumber] int callerLineNumber = 0)
{
_ = tasks ?? throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
{
log?.WriteLine("No tasks to await");
return true;
}
if (AllComplete(tasks))
{
log?.WriteLine("All tasks are already complete");
return true;
}
static void LogWithThreadPoolStats(LogProxy? log, string message, out int busyWorkerCount)
{
busyWorkerCount = 0;
if (log is not null)
{
var sb = new StringBuilder();
sb.Append(message);
busyWorkerCount = PerfCounterHelper.GetThreadPoolStats(out string iocp, out string worker, out string? workItems);
sb.Append(", IOCP: ").Append(iocp).Append(", WORKER: ").Append(worker);
if (workItems is not null)
{
sb.Append(", POOL: ").Append(workItems);
}
log?.WriteLine(sb.ToString());
}
}
var watch = ValueStopwatch.StartNew();
LogWithThreadPoolStats(log, $"Awaiting {tasks.Length} {name} task completion(s) for {timeoutMilliseconds}ms", out _);
try
{
// if none error, great
var remaining = timeoutMilliseconds - watch.ElapsedMilliseconds;
if (remaining <= 0)
{
LogWithThreadPoolStats(log, "Timeout before awaiting for tasks", out _);
return false;
}
var allTasks = Task.WhenAll(tasks).ObserveErrors();
bool all = await allTasks.TimeoutAfter(timeoutMs: remaining).ObserveErrors().ForAwait();
LogWithThreadPoolStats(log, all ? $"All {tasks.Length} {name} tasks completed cleanly" : $"Not all {name} tasks completed cleanly (from {caller}#{callerLineNumber}, timeout {timeoutMilliseconds}ms)", out _);
return all;
}
catch
{ }
// if we get problems, need to give the non-failing ones time to finish
// to be fair and reasonable
for (int i = 0; i < tasks.Length; i++)
{
var task = tasks[i];
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted)
{
var remaining = timeoutMilliseconds - watch.ElapsedMilliseconds;
if (remaining <= 0)
{
LogWithThreadPoolStats(log, "Timeout awaiting tasks", out _);
return false;
}
try
{
await Task.WhenAny(task, Task.Delay(remaining)).ObserveErrors().ForAwait();
}
catch
{ }
}
}
LogWithThreadPoolStats(log, "Finished awaiting tasks", out _);
return false;
}
private static bool AllComplete(Task[] tasks)
{
for (int i = 0; i < tasks.Length; i++)
{
var task = tasks[i];
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted)
return false;
}
return true;
}
internal bool AuthSuspect { get; private set; }
internal void SetAuthSuspect() => AuthSuspect = true;
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The string configuration to use for this multiplexer.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
public static Task<ConnectionMultiplexer> ConnectAsync(string configuration, TextWriter? log = null) =>
ConnectAsync(ConfigurationOptions.Parse(configuration), log);
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The string configuration to use for this multiplexer.</param>
/// <param name="configure">Action to further modify the parsed configuration options.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
public static Task<ConnectionMultiplexer> ConnectAsync(string configuration, Action<ConfigurationOptions> configure, TextWriter? log = null) =>
ConnectAsync(ConfigurationOptions.Parse(configuration).Apply(configure), log);
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The configuration options to use for this multiplexer.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
/// <remarks>Note: For Sentinel, do <b>not</b> specify a <see cref="ConfigurationOptions.CommandMap"/> - this is handled automatically.</remarks>
public static Task<ConnectionMultiplexer> ConnectAsync(ConfigurationOptions configuration, TextWriter? log = null)
{
SocketConnection.AssertDependencies();
Validate(configuration);
return configuration.IsSentinel
? SentinelPrimaryConnectAsync(configuration, log)
: ConnectImplAsync(configuration, log);
}
private static async Task<ConnectionMultiplexer> ConnectImplAsync(ConfigurationOptions configuration, TextWriter? log = null, ServerType? serverType = null)
{
IDisposable? killMe = null;
EventHandler<ConnectionFailedEventArgs>? connectHandler = null;
ConnectionMultiplexer? muxer = null;
using var logProxy = LogProxy.TryCreate(log);
try
{
var sw = ValueStopwatch.StartNew();
logProxy?.WriteLine($"Connecting (async) on {RuntimeInformation.FrameworkDescription} (StackExchange.Redis: v{Utils.GetLibVersion()})");
muxer = CreateMultiplexer(configuration, logProxy, serverType, out connectHandler);
killMe = muxer;
Interlocked.Increment(ref muxer._connectAttemptCount);
bool configured = await muxer.ReconfigureAsync(first: true, reconfigureAll: false, logProxy, null, "connect").ObserveErrors().ForAwait();
if (!configured)
{
throw ExceptionFactory.UnableToConnect(muxer, muxer.failureMessage);
}
killMe = null;
Interlocked.Increment(ref muxer._connectCompletedCount);
if (muxer.ServerSelectionStrategy.ServerType == ServerType.Sentinel)
{
// Initialize the Sentinel handlers
muxer.InitializeSentinel(logProxy);
}
await configuration.AfterConnectAsync(muxer, logProxy != null ? logProxy.WriteLine : LogProxy.NullWriter).ForAwait();
logProxy?.WriteLine($"Total connect time: {sw.ElapsedMilliseconds:n0} ms");
return muxer;
}
finally
{
if (connectHandler != null && muxer != null) muxer.ConnectionFailed -= connectHandler;
if (killMe != null) try { killMe.Dispose(); } catch { }
}
}
private static void Validate([NotNull] ConfigurationOptions? config)
{
if (config is null)
{
throw new ArgumentNullException(nameof(config));
}
if (config.EndPoints.Count == 0)
{
throw new ArgumentException("No endpoints specified", nameof(config));
}
}
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The string configuration to use for this multiplexer.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
public static ConnectionMultiplexer Connect(string configuration, TextWriter? log = null) =>
Connect(ConfigurationOptions.Parse(configuration), log);
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The string configuration to use for this multiplexer.</param>
/// <param name="configure">Action to further modify the parsed configuration options.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
public static ConnectionMultiplexer Connect(string configuration, Action<ConfigurationOptions> configure, TextWriter? log = null) =>
Connect(ConfigurationOptions.Parse(configuration).Apply(configure), log);
/// <summary>
/// Creates a new <see cref="ConnectionMultiplexer"/> instance.
/// </summary>
/// <param name="configuration">The configuration options to use for this multiplexer.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
/// <remarks>Note: For Sentinel, do <b>not</b> specify a <see cref="ConfigurationOptions.CommandMap"/> - this is handled automatically.</remarks>
public static ConnectionMultiplexer Connect(ConfigurationOptions configuration, TextWriter? log = null)
{
SocketConnection.AssertDependencies();
Validate(configuration);
return configuration.IsSentinel
? SentinelPrimaryConnect(configuration, log)
: ConnectImpl(configuration, log);
}
private static ConnectionMultiplexer ConnectImpl(ConfigurationOptions configuration, TextWriter? log, ServerType? serverType = null)
{
IDisposable? killMe = null;
EventHandler<ConnectionFailedEventArgs>? connectHandler = null;
ConnectionMultiplexer? muxer = null;
using var logProxy = LogProxy.TryCreate(log);
try
{
var sw = ValueStopwatch.StartNew();
logProxy?.WriteLine($"Connecting (sync) on {RuntimeInformation.FrameworkDescription} (StackExchange.Redis: v{Utils.GetLibVersion()})");
muxer = CreateMultiplexer(configuration, logProxy, serverType, out connectHandler);
killMe = muxer;
Interlocked.Increment(ref muxer._connectAttemptCount);
// note that task has timeouts internally, so it might take *just over* the regular timeout
var task = muxer.ReconfigureAsync(first: true, reconfigureAll: false, logProxy, null, "connect");
if (!task.Wait(muxer.SyncConnectTimeout(true)))
{
task.ObserveErrors();
if (muxer.RawConfig.AbortOnConnectFail)
{
throw ExceptionFactory.UnableToConnect(muxer, "ConnectTimeout");
}
else
{
muxer.LastException = ExceptionFactory.UnableToConnect(muxer, "ConnectTimeout");
}
}
if (!task.Result) throw ExceptionFactory.UnableToConnect(muxer, muxer.failureMessage);
killMe = null;
Interlocked.Increment(ref muxer._connectCompletedCount);
if (muxer.ServerSelectionStrategy.ServerType == ServerType.Sentinel)
{
// Initialize the Sentinel handlers
muxer.InitializeSentinel(logProxy);
}
configuration.AfterConnectAsync(muxer, logProxy != null ? logProxy.WriteLine : LogProxy.NullWriter).Wait(muxer.SyncConnectTimeout(true));
logProxy?.WriteLine($"Total connect time: {sw.ElapsedMilliseconds:n0} ms");
return muxer;
}
finally
{
if (connectHandler != null && muxer != null) muxer.ConnectionFailed -= connectHandler;
if (killMe != null) try { killMe.Dispose(); } catch { }
}
}
ReadOnlySpan<ServerEndPoint> IInternalConnectionMultiplexer.GetServerSnapshot() => GetServerSnapshot();
internal ReadOnlySpan<ServerEndPoint> GetServerSnapshot() => _serverSnapshot.Span;
private sealed class ServerSnapshot
{
public static ServerSnapshot Empty { get; } = new ServerSnapshot(Array.Empty<ServerEndPoint>(), 0);
private ServerSnapshot(ServerEndPoint[] arr, int count)
{
_arr = arr;
_count = count;
}
private readonly ServerEndPoint[] _arr;
private readonly int _count;
public ReadOnlySpan<ServerEndPoint> Span => new ReadOnlySpan<ServerEndPoint>(_arr, 0, _count);
internal ServerSnapshot Add(ServerEndPoint value)
{
if (value == null)
{
return this;
}
ServerEndPoint[] arr;
if (_arr.Length > _count)
{
arr = _arr;
}
else
{
// no more room; need a new array
int newLen = _arr.Length << 1;
if (newLen == 0) newLen = 4;
arr = new ServerEndPoint[newLen];
_arr.CopyTo(arr, 0);
}
arr[_count] = value;
return new ServerSnapshot(arr, _count + 1);
}
internal EndPoint[] GetEndPoints()
{
if (_count == 0) return Array.Empty<EndPoint>();
var arr = new EndPoint[_count];
for (int i = 0; i < _count; i++)
{
arr[i] = _arr[i].EndPoint;
}
return arr;
}
}
[return: NotNullIfNotNull("endpoint")]
internal ServerEndPoint? GetServerEndPoint(EndPoint? endpoint, LogProxy? log = null, bool activate = true)
{
if (endpoint == null) return null;
var server = (ServerEndPoint?)servers[endpoint];
if (server == null)
{
bool isNew = false;
lock (servers)
{
server = (ServerEndPoint?)servers[endpoint];
if (server == null)
{
if (_isDisposed) throw new ObjectDisposedException(ToString());
server = new ServerEndPoint(this, endpoint);
servers.Add(endpoint, server);
isNew = true;
_serverSnapshot = _serverSnapshot.Add(server);
}
}
// spin up the connection if this is new
if (isNew && activate) server.Activate(ConnectionType.Interactive, log);
}
return server;
}
private sealed class TimerToken
{
public TimerToken(ConnectionMultiplexer muxer)
{
_ref = new WeakReference(muxer);
}
private Timer? _timer;
public void SetTimer(Timer timer) => _timer = timer;
private readonly WeakReference _ref;
private static readonly TimerCallback Heartbeat = state =>
{
var token = (TimerToken)state!;
var muxer = (ConnectionMultiplexer?)(token._ref?.Target);
if (muxer != null)
{
muxer.OnHeartbeat();
}
else
{
// the muxer got disposed from out of us; kill the timer
var tmp = token._timer;
token._timer = null;
if (tmp != null) try { tmp.Dispose(); } catch { }
}
};
internal static IDisposable Create(ConnectionMultiplexer connection)
{
var token = new TimerToken(connection);
var timer = new Timer(Heartbeat, token, MillisecondsPerHeartbeat, MillisecondsPerHeartbeat);
token.SetTimer(timer);
return timer;
}
}
private void OnHeartbeat()
{
try
{
int now = Environment.TickCount;
Interlocked.Exchange(ref lastHeartbeatTicks, now);
Interlocked.Exchange(ref lastGlobalHeartbeatTicks, now);
Trace("heartbeat");
var tmp = GetServerSnapshot();
for (int i = 0; i < tmp.Length; i++)
tmp[i].OnHeartbeat();
}
catch (Exception ex)
{
if (Interlocked.CompareExchange(ref _activeHeartbeatErrors, 1, 0) == 0)
{
try
{
OnInternalError(ex);
}
finally
{
Interlocked.Exchange(ref _activeHeartbeatErrors, 0);
}
}
}
}
/// <summary>
/// Obtain a pub/sub subscriber connection to the specified server.
/// </summary>
/// <param name="asyncState">The async state object to pass to the created <see cref="RedisSubscriber"/>.</param>
public ISubscriber GetSubscriber(object? asyncState = null)
{
if (!RawConfig.Proxy.SupportsPubSub())
{
throw new NotSupportedException($"The pub/sub API is not available via {RawConfig.Proxy}");
}
return new RedisSubscriber(this, asyncState);
}
/// <summary>
/// Applies common DB number defaults and rules.
/// </summary>
internal int ApplyDefaultDatabase(int db)
{
if (db == -1)
{
db = RawConfig.DefaultDatabase.GetValueOrDefault();
}
else if (db < 0)
{
throw new ArgumentOutOfRangeException(nameof(db));
}
if (db != 0 && !RawConfig.Proxy.SupportsDatabases())
{
throw new NotSupportedException($"{RawConfig.Proxy} only supports database 0");
}
return db;
}
/// <summary>
/// Obtain an interactive connection to a database inside redis.
/// </summary>
/// <param name="db">The ID to get a database for.</param>
/// <param name="asyncState">The async state to pass into the resulting <see cref="RedisDatabase"/>.</param>
public IDatabase GetDatabase(int db = -1, object? asyncState = null)
{
db = ApplyDefaultDatabase(db);
// if there's no async-state, and the DB is suitable, we can hand out a re-used instance
return (asyncState == null && db <= MaxCachedDatabaseInstance)
? GetCachedDatabaseInstance(db) : new RedisDatabase(this, db, asyncState);
}
// DB zero is stored separately, since 0-only is a massively common use-case
private const int MaxCachedDatabaseInstance = 16; // 17 items - [0,16]
// Side note: "databases 16" is the default in redis.conf; happy to store one extra to get nice alignment etc
private IDatabase? dbCacheZero;
private IDatabase[]? dbCacheLow;
private IDatabase GetCachedDatabaseInstance(int db) // note that we already trust db here; only caller checks range
{
// Note: we don't need to worry about *always* returning the same instance.
// If two threads ask for db 3 at the same time, it is OK for them to get
// different instances, one of which (arbitrarily) ends up cached for later use.
if (db == 0)
{
return dbCacheZero ??= new RedisDatabase(this, 0, null);
}
var arr = dbCacheLow ??= new IDatabase[MaxCachedDatabaseInstance];
return arr[db - 1] ??= new RedisDatabase(this, db, null);
}
/// <summary>
/// Compute the hash-slot of a specified key.
/// </summary>
/// <param name="key">The key to get a hash slot ID for.</param>
public int HashSlot(RedisKey key) => ServerSelectionStrategy.HashSlot(key);
internal ServerEndPoint? AnyServer(ServerType serverType, uint startOffset, RedisCommand command, CommandFlags flags, bool allowDisconnected)
{
var tmp = GetServerSnapshot();
int len = tmp.Length;
ServerEndPoint? fallback = null;
for (int i = 0; i < len; i++)
{
var server = tmp[(int)(((uint)i + startOffset) % len)];
if (server != null && server.ServerType == serverType && server.IsSelectable(command, allowDisconnected))
{
if (server.IsReplica)
{
switch (flags)
{
case CommandFlags.DemandReplica:
case CommandFlags.PreferReplica:
return server;
case CommandFlags.PreferMaster:
fallback = server;
break;
}
}
else
{
switch (flags)
{
case CommandFlags.DemandMaster:
case CommandFlags.PreferMaster:
return server;
case CommandFlags.PreferReplica:
fallback = server;
break;
}
}
}
}
return fallback;
}
/// <summary>
/// Obtain a configuration API for an individual server.
/// </summary>
/// <param name="host">The host to get a server for.</param>
/// <param name="port">The port for <paramref name="host"/> to get a server for.</param>
/// <param name="asyncState">The async state to pass into the resulting <see cref="RedisServer"/>.</param>
public IServer GetServer(string host, int port, object? asyncState = null) =>
GetServer(Format.ParseEndPoint(host, port), asyncState);
/// <summary>
/// Obtain a configuration API for an individual server.