/
ConnectionMultiplexer.cs
2193 lines (1980 loc) · 95 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;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.IO.Compression;
using System.Runtime.CompilerServices;
namespace StackExchange.Redis
{
/// <summary>
/// Represents an inter-related group of connections to redis servers
/// </summary>
public sealed partial class ConnectionMultiplexer : IConnectionMultiplexer, IDisposable
{
private const string timeoutHelpLink = "https://stackexchange.github.io/StackExchange.Redis/Timeouts";
private static TaskFactory _factory = null;
/// <summary>
/// Provides a way of overriding the default Task Factory. If not set, it will use the default Task.Factory.
/// Useful when top level code sets it's own factory which may interfere with Redis queries.
/// </summary>
public static TaskFactory Factory
{
get => _factory ?? Task.Factory;
set => _factory = value;
}
/// <summary>
/// Get summary statistics associates with this server
/// </summary>
public ServerCounters GetCounters()
{
var snapshot = serverSnapshot;
var counters = new ServerCounters(null);
for (int i = 0; i < snapshot.Length; i++)
{
counters.Add(snapshot[i].GetCounters());
}
UnprocessableCompletionManager.GetCounters(counters.Other);
return counters;
}
/// <summary>
/// Gets the client-name that will be used on all new connections
/// </summary>
public string ClientName => configuration.ClientName ?? GetDefaultClientName();
private static string defaultClientName;
private static string GetDefaultClientName()
{
return defaultClientName ?? (defaultClientName = TryGetAzureRoleInstanceIdNoThrow()
?? Environment.MachineName
?? Environment.GetEnvironmentVariable("ComputerName")
?? "StackExchange.Redis");
}
/// <summary>
/// Tries to get the Roleinstance Id if Microsoft.WindowsAzure.ServiceRuntime is loaded.
/// In case of any failure, swallows the exception and returns null
/// </summary>
internal static string TryGetAzureRoleInstanceIdNoThrow()
{
string roleInstanceId = null;
// TODO: CoreCLR port pending https://github.com/dotnet/coreclr/issues/919
try
{
Assembly asm = null;
foreach (var asmb in AppDomain.CurrentDomain.GetAssemblies())
{
if (asmb.GetName().Name.Equals("Microsoft.WindowsAzure.ServiceRuntime"))
{
asm = asmb;
break;
}
}
if (asm == null)
return null;
var type = asm.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment");
// https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.serviceruntime.roleenvironment.isavailable.aspx
if (!(bool)type.GetProperty("IsAvailable").GetValue(null, null))
return null;
var currentRoleInstanceProp = type.GetProperty("CurrentRoleInstance");
var currentRoleInstanceId = currentRoleInstanceProp.GetValue(null, null);
roleInstanceId = currentRoleInstanceId.GetType().GetProperty("Id").GetValue(currentRoleInstanceId, null).ToString();
if (string.IsNullOrEmpty(roleInstanceId))
{
roleInstanceId = null;
}
}
catch (Exception)
{
//silently ignores the exception
roleInstanceId = null;
}
return roleInstanceId;
}
/// <summary>
/// Gets the configuration of the connection
/// </summary>
public string Configuration => configuration.ToString();
internal void OnConnectionFailed(EndPoint endpoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception, bool reconfigure)
{
if (isDisposed) return;
var handler = ConnectionFailed;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new ConnectionFailedEventArgs(handler, this, endpoint, connectionType, failureType, exception)
);
}
if (reconfigure)
{
ReconfigureIfNeeded(endpoint, false, "connection failed");
}
}
internal void OnInternalError(Exception exception, EndPoint endpoint = null, ConnectionType connectionType = ConnectionType.None, [CallerMemberName] string origin = null)
{
try
{
Trace("Internal error: " + origin + ", " + exception == null ? "unknown" : exception.Message);
if (isDisposed) return;
var handler = InternalError;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new InternalErrorEventArgs(handler, this, endpoint, connectionType, exception, origin)
);
}
}
catch
{ // our internal error event failed; whatcha gonna do, exactly?
}
}
internal void OnConnectionRestored(EndPoint endpoint, ConnectionType connectionType)
{
if (isDisposed) return;
var handler = ConnectionRestored;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new ConnectionFailedEventArgs(handler, this, endpoint, connectionType, ConnectionFailureType.None, null)
);
}
ReconfigureIfNeeded(endpoint, false, "connection restored");
}
private void OnEndpointChanged(EndPoint endpoint, EventHandler<EndPointEventArgs> handler)
{
if (isDisposed) return;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new EndPointEventArgs(handler, this, endpoint)
);
}
}
internal void OnConfigurationChanged(EndPoint endpoint) => OnEndpointChanged(endpoint, ConfigurationChanged);
internal void OnConfigurationChangedBroadcast(EndPoint endpoint) => OnEndpointChanged(endpoint, ConfigurationChangedBroadcast);
/// <summary>
/// A server replied with an error message;
/// </summary>
public event EventHandler<RedisErrorEventArgs> ErrorMessage;
internal void OnErrorMessage(EndPoint endpoint, string message)
{
if (isDisposed) return;
var handler = ErrorMessage;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new RedisErrorEventArgs(handler, this, endpoint, message)
);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
private static void Write<T>(ZipArchive zip, string name, Task task, Action<T, StreamWriter> callback)
{
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
using (var stream = entry.Open())
using (var writer = new StreamWriter(stream))
{
TaskStatus status = task.Status;
switch (status)
{
case TaskStatus.RanToCompletion:
T val = ((Task<T>)task).Result;
callback(val, writer);
break;
case TaskStatus.Faulted:
writer.WriteLine(string.Join(", ", task.Exception.InnerExceptions.Select(x => x.Message)));
break;
default:
writer.WriteLine(status.ToString());
break;
}
}
}
/// <summary>
/// Write the configuration of all servers to an output stream
/// </summary>
/// <param name="destination">The destination stream to write the export to.</param>
/// <param name="options">The options to use for this export.</param>
public void ExportConfiguration(Stream destination, ExportOptions options = ExportOptions.All)
{
if (destination == null) throw new ArgumentNullException(nameof(destination));
// what is possible, given the command map?
ExportOptions mask = 0;
if (CommandMap.IsAvailable(RedisCommand.INFO)) mask |= ExportOptions.Info;
if (CommandMap.IsAvailable(RedisCommand.CONFIG)) mask |= ExportOptions.Config;
if (CommandMap.IsAvailable(RedisCommand.CLIENT)) mask |= ExportOptions.Client;
if (CommandMap.IsAvailable(RedisCommand.CLUSTER)) mask |= ExportOptions.Cluster;
options &= mask;
using (var zip = new ZipArchive(destination, ZipArchiveMode.Create, true))
{
var arr = serverSnapshot;
foreach (var server in arr)
{
const CommandFlags flags = CommandFlags.None;
if (!server.IsConnected) continue;
var api = GetServer(server.EndPoint);
List<Task> tasks = new List<Task>();
if ((options & ExportOptions.Info) != 0)
{
tasks.Add(api.InfoRawAsync(flags: flags));
}
if ((options & ExportOptions.Config) != 0)
{
tasks.Add(api.ConfigGetAsync(flags: flags));
}
if ((options & ExportOptions.Client) != 0)
{
tasks.Add(api.ClientListAsync(flags: flags));
}
if ((options & ExportOptions.Cluster) != 0)
{
tasks.Add(api.ClusterNodesRawAsync(flags: flags));
}
WaitAllIgnoreErrors(tasks.ToArray());
int index = 0;
var prefix = Format.ToString(server.EndPoint);
if ((options & ExportOptions.Info) != 0)
{
Write<string>(zip, prefix + "/info.txt", tasks[index++], WriteNormalizingLineEndings);
}
if ((options & ExportOptions.Config) != 0)
{
Write<KeyValuePair<string, string>[]>(zip, prefix + "/config.txt", tasks[index++], (settings, writer) =>
{
foreach (var setting in settings)
{
writer.WriteLine("{0}={1}", setting.Key, setting.Value);
}
});
}
if ((options & ExportOptions.Client) != 0)
{
Write<ClientInfo[]>(zip, prefix + "/clients.txt", tasks[index++], (clients, writer) =>
{
foreach (var client in clients)
{
writer.WriteLine(client.Raw);
}
});
}
if ((options & ExportOptions.Cluster) != 0)
{
Write<string>(zip, prefix + "/nodes.txt", tasks[index++], WriteNormalizingLineEndings);
}
}
}
}
internal void MakeMaster(ServerEndPoint server, ReplicationChangeOptions options, TextWriter log)
{
CommandMap.AssertAvailable(RedisCommand.SLAVEOF);
if (!configuration.AllowAdmin) throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, RedisCommand.SLAVEOF, null, server);
if (server == null) throw new ArgumentNullException(nameof(server));
var srv = new RedisServer(this, server, null);
if (!srv.IsConnected) throw ExceptionFactory.NoConnectionAvailable(IncludeDetailInExceptions, IncludePerformanceCountersInExceptions, RedisCommand.SLAVEOF, null, server, GetServerSnapshot());
if (log == null) log = TextWriter.Null;
CommandMap.AssertAvailable(RedisCommand.SLAVEOF);
const CommandFlags flags = CommandFlags.NoRedirect | CommandFlags.HighPriority;
Message msg;
LogLocked(log, "Checking {0} is available...", Format.ToString(srv.EndPoint));
try
{
srv.Ping(flags); // if it isn't happy, we're not happy
}
catch (Exception ex)
{
LogLocked(log, "Operation failed on {0}, aborting: {1}", Format.ToString(srv.EndPoint), ex.Message);
throw;
}
var nodes = serverSnapshot;
RedisValue newMaster = Format.ToString(server.EndPoint);
RedisKey tieBreakerKey = default(RedisKey);
// try and write this everywhere; don't worry if some folks reject our advances
if ((options & ReplicationChangeOptions.SetTiebreaker) != 0 && !string.IsNullOrWhiteSpace(configuration.TieBreaker)
&& CommandMap.IsAvailable(RedisCommand.SET))
{
tieBreakerKey = configuration.TieBreaker;
foreach (var node in nodes)
{
if (!node.IsConnected) continue;
LogLocked(log, "Attempting to set tie-breaker on {0}...", Format.ToString(node.EndPoint));
msg = Message.Create(0, flags, RedisCommand.SET, tieBreakerKey, newMaster);
node.QueueDirectFireAndForget(msg, ResultProcessor.DemandOK);
}
}
// deslave...
LogLocked(log, "Making {0} a master...", Format.ToString(srv.EndPoint));
try
{
srv.SlaveOf(null, flags);
}
catch (Exception ex)
{
LogLocked(log, "Operation failed on {0}, aborting: {1}", Format.ToString(srv.EndPoint), ex.Message);
throw;
}
// also, in case it was a slave a moment ago, and hasn't got the tie-breaker yet, we re-send the tie-breaker to this one
if (!tieBreakerKey.IsNull)
{
LogLocked(log, "Resending tie-breaker to {0}...", Format.ToString(server.EndPoint));
msg = Message.Create(0, flags, RedisCommand.SET, tieBreakerKey, newMaster);
server.QueueDirectFireAndForget(msg, ResultProcessor.DemandOK);
}
// There's an inherent race here in zero-lantency environments (e.g. when Redis is on localhost) when a broadcast is specified
// The broadast 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 reconfig and the .CompareExchange() (due to already running a reconfig) failing...making our needed reconfig 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 Master Reconfig", null) == null;
// try and broadcast this everywhere, to catch the maximum audience
if ((options & ReplicationChangeOptions.Broadcast) != 0 && ConfigurationChangedChannel != null
&& CommandMap.IsAvailable(RedisCommand.PUBLISH))
{
RedisValue channel = ConfigurationChangedChannel;
foreach (var node in nodes)
{
if (!node.IsConnected) continue;
LogLocked(log, "Broadcasting via {0}...", Format.ToString(node.EndPoint));
msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, newMaster);
node.QueueDirectFireAndForget(msg, ResultProcessor.Int64);
}
}
if ((options & ReplicationChangeOptions.EnslaveSubordinates) != 0)
{
foreach (var node in nodes)
{
if (node == server || node.ServerType != ServerType.Standalone) continue;
LogLocked(log, "Enslaving {0}...", Format.ToString(node.EndPoint));
msg = RedisServer.CreateSlaveOfMessage(server.EndPoint, flags);
node.QueueDirectFireAndForget(msg, ResultProcessor.DemandOK);
}
}
// and reconfigure the muxer
LogLocked(log, "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 (!ReconfigureAsync(false, true, log, srv.EndPoint, "make master").ObserveErrors().Wait(5000))
{
LogLocked(log, "Verifying the configuration was incomplete; please verify");
}
}
/// <summary>
/// Used internally to synchronize loggine without depending on locking the log instance
/// </summary>
private object LogSyncLock => UniqueId;
// we know this has strong identity: readonly and unique to us
internal void LogLocked(TextWriter log, string line)
{
if (log != null) lock (LogSyncLock) { log.WriteLine(line); }
}
internal void LogLocked(TextWriter log, string line, object arg)
{
if (log != null) lock (LogSyncLock) { log.WriteLine(line, arg); }
}
internal void LogLocked(TextWriter log, string line, object arg0, object arg1)
{
if (log != null) lock (LogSyncLock) { log.WriteLine(line, arg0, arg1); }
}
internal void LogLocked(TextWriter log, string line, object arg0, object arg1, object arg2)
{
if (log != null) lock (LogSyncLock) { log.WriteLine(line, arg0, arg1, arg2); }
}
internal void LogLocked(TextWriter log, string line, params object[] args)
{
if (log != null) lock (LogSyncLock) { log.WriteLine(line, args); }
}
internal void CheckMessage(Message message)
{
if (!configuration.AllowAdmin && message.IsAdmin)
throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, message.Command, message, null);
CommandMap.AssertAvailable(message.Command);
}
private static void WriteNormalizingLineEndings(string source, StreamWriter writer)
{
using (var reader = new StringReader(source))
{
string line;
while ((line = reader.ReadLine()) != null)
writer.WriteLine(line); // normalize line endings
}
}
/// <summary>
/// Raised whenever a physical connection fails
/// </summary>
public event EventHandler<ConnectionFailedEventArgs> ConnectionFailed;
/// <summary>
/// Raised whenever an internal error occurs (this is primarily for debugging)
/// </summary>
public event EventHandler<InternalErrorEventArgs> InternalError;
/// <summary>
/// Raised whenever a physical connection is established
/// </summary>
public event EventHandler<ConnectionFailedEventArgs> ConnectionRestored;
/// <summary>
/// Raised when configuration changes are detected
/// </summary>
public event EventHandler<EndPointEventArgs> ConfigurationChanged;
/// <summary>
/// Raised when nodes are explicitly requested to reconfigure via broadcast;
/// this usually means master/slave changes
/// </summary>
public event EventHandler<EndPointEventArgs> ConfigurationChangedBroadcast;
/// <summary>
/// Gets the timeout associated with the connections
/// </summary>
public int TimeoutMilliseconds { get; }
/// <summary>
/// Gets all endpoints defined on the server
/// </summary>
/// <param name="configuredOnly">Whether to get only the endpoints specified explicitly in the config.</param>
public EndPoint[] GetEndPoints(bool configuredOnly = false)
{
if (configuredOnly) return configuration.EndPoints.ToArray();
return Array.ConvertAll(serverSnapshot, x => x.EndPoint);
}
private readonly ConfigurationOptions configuration;
internal bool TryResend(int hashSlot, Message message, EndPoint endpoint, bool isMoved)
{
return 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)
{
if (task == null) throw new ArgumentNullException(nameof(task));
if (!task.Wait(TimeoutMilliseconds)) throw new TimeoutException();
}
/// <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)
{
if (task == null) throw new ArgumentNullException(nameof(task));
if (!task.Wait(TimeoutMilliseconds)) throw new TimeoutException();
return task.Result;
}
/// <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)
{
if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return;
if (!Task.WaitAll(tasks, TimeoutMilliseconds)) throw new TimeoutException();
}
private bool WaitAllIgnoreErrors(Task[] tasks) => WaitAllIgnoreErrors(tasks, TimeoutMilliseconds);
private static bool WaitAllIgnoreErrors(Task[] tasks, int timeout)
{
if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0) return true;
var watch = Stopwatch.StartNew();
try
{
// if none error, great
if (Task.WaitAll(tasks, timeout)) return true;
}
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 = timeout - checked((int)watch.ElapsedMilliseconds);
if (remaining <= 0) return false;
try
{
task.Wait(remaining);
}
catch
{ }
}
}
return false;
}
private void LogLockedWithThreadPoolStats(TextWriter log, string message, out int busyWorkerCount)
{
busyWorkerCount = 0;
if (log != null)
{
var sb = new StringBuilder();
sb.Append(message);
busyWorkerCount = GetThreadPoolStats(out string iocp, out string worker);
sb.Append(", IOCP: ").Append(iocp).Append(", WORKER: ").Append(worker);
LogLocked(log, sb.ToString());
}
}
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;
}
private async Task<bool> WaitAllIgnoreErrorsAsync(Task[] tasks, int timeoutMilliseconds, TextWriter log)
{
if (tasks == null) throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
{
LogLocked(log, "No tasks to await");
return true;
}
if (AllComplete(tasks))
{
LogLocked(log, "All tasks are already complete");
return true;
}
var watch = Stopwatch.StartNew();
LogLockedWithThreadPoolStats(log, "Awaiting task completion", out int busyWorkerCount);
try
{
// if none error, great
var remaining = timeoutMilliseconds - checked((int)watch.ElapsedMilliseconds);
if (remaining <= 0)
{
LogLockedWithThreadPoolStats(log, "Timeout before awaiting for tasks", out busyWorkerCount);
return false;
}
var allTasks = Task.WhenAll(tasks).ObserveErrors();
var any = Task.WhenAny(allTasks, Task.Delay(remaining)).ObserveErrors();
bool all = await any.ForAwait() == allTasks;
LogLockedWithThreadPoolStats(log, all ? "All tasks completed cleanly" : "Not all tasks completed cleanly", out busyWorkerCount);
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 - checked((int)watch.ElapsedMilliseconds);
if (remaining <= 0)
{
LogLockedWithThreadPoolStats(log, "Timeout awaiting tasks", out busyWorkerCount);
return false;
}
try
{
await Task.WhenAny(task, Task.Delay(remaining)).ObserveErrors().ForAwait();
}
catch
{ }
}
}
LogLockedWithThreadPoolStats(log, "Finished awaiting tasks", out busyWorkerCount);
return false;
}
/// <summary>
/// Raised when a hash-slot has been relocated
/// </summary>
public event EventHandler<HashSlotMovedEventArgs> HashSlotMoved;
internal void OnHashSlotMoved(int hashSlot, EndPoint old, EndPoint @new)
{
var handler = HashSlotMoved;
if (handler != null)
{
UnprocessableCompletionManager.CompleteSyncOrAsync(
new HashSlotMovedEventArgs(handler, this, hashSlot, old, @new)
);
}
}
/// <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 AnyConnected(ServerType serverType, uint startOffset, RedisCommand command, CommandFlags flags)
{
var tmp = serverSnapshot;
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))
{
if (server.IsSlave)
{
switch (flags)
{
case CommandFlags.DemandSlave:
case CommandFlags.PreferSlave:
return server;
case CommandFlags.PreferMaster:
fallback = server;
break;
}
}
else
{
switch (flags)
{
case CommandFlags.DemandMaster:
case CommandFlags.PreferMaster:
return server;
case CommandFlags.PreferSlave:
fallback = server;
break;
}
}
}
}
return fallback;
}
private volatile bool isDisposed;
internal bool IsDisposed => isDisposed;
/// <summary>
/// Create a new 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 async Task<ConnectionMultiplexer> ConnectAsync(string configuration, TextWriter log = null)
{
IDisposable killMe = null;
try
{
var muxer = CreateMultiplexer(configuration);
killMe = muxer;
bool configured = await muxer.ReconfigureAsync(true, false, log, null, "connect").ObserveErrors().ForAwait();
if (!configured)
{
throw ExceptionFactory.UnableToConnect(muxer.RawConfig.AbortOnConnectFail, muxer.failureMessage);
}
killMe = null;
return muxer;
}
finally
{
if (killMe != null) try { killMe.Dispose(); } catch { }
}
}
/// <summary>
/// Create a new 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>
public static async Task<ConnectionMultiplexer> ConnectAsync(ConfigurationOptions configuration, TextWriter log = null)
{
IDisposable killMe = null;
try
{
var muxer = CreateMultiplexer(configuration);
killMe = muxer;
bool configured = await muxer.ReconfigureAsync(true, false, log, null, "connect").ObserveErrors().ForAwait();
if (!configured)
{
throw ExceptionFactory.UnableToConnect(muxer.RawConfig.AbortOnConnectFail, muxer.failureMessage);
}
killMe = null;
return muxer;
}
finally
{
if (killMe != null) try { killMe.Dispose(); } catch { }
}
}
private static ConnectionMultiplexer CreateMultiplexer(object configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
ConfigurationOptions config;
if (configuration is string)
{
config = ConfigurationOptions.Parse((string)configuration);
}
else if (configuration is ConfigurationOptions)
{
config = ((ConfigurationOptions)configuration).Clone();
}
else
{
throw new ArgumentException("configuration");
}
if (config.EndPoints.Count == 0) throw new ArgumentException("No endpoints specified", nameof(configuration));
config.SetDefaultPorts();
return new ConnectionMultiplexer(config);
}
/// <summary>
/// Create a new 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)
{
return ConnectImpl(() => CreateMultiplexer(configuration), log);
}
/// <summary>
/// Create a new ConnectionMultiplexer instance
/// </summary>
/// <param name="configuration">The configurtion options to use for this multiplexer.</param>
/// <param name="log">The <see cref="TextWriter"/> to log to.</param>
public static ConnectionMultiplexer Connect(ConfigurationOptions configuration, TextWriter log = null)
{
return ConnectImpl(() => CreateMultiplexer(configuration), log);
}
private static ConnectionMultiplexer ConnectImpl(Func<ConnectionMultiplexer> multiplexerFactory, TextWriter log)
{
IDisposable killMe = null;
try
{
var muxer = multiplexerFactory();
killMe = muxer;
// note that task has timeouts internally, so it might take *just over* the regular timeout
var task = muxer.ReconfigureAsync(true, false, log, null, "connect");
if (!task.Wait(muxer.SyncConnectTimeout(true)))
{
task.ObserveErrors();
if (muxer.RawConfig.AbortOnConnectFail)
{
throw ExceptionFactory.UnableToConnect(muxer.RawConfig.AbortOnConnectFail, "ConnectTimeout");
}
else
{
muxer.LastException = ExceptionFactory.UnableToConnect(muxer.RawConfig.AbortOnConnectFail, "ConnectTimeout");
}
}
if (!task.Result) throw ExceptionFactory.UnableToConnect(muxer.RawConfig.AbortOnConnectFail, muxer.failureMessage);
killMe = null;
return muxer;
}
finally
{
if (killMe != null) try { killMe.Dispose(); } catch { }
}
}
private string failureMessage;
private readonly Hashtable servers = new Hashtable();
private volatile ServerEndPoint[] serverSnapshot = NilServers;
private static readonly ServerEndPoint[] NilServers = new ServerEndPoint[0];
internal ServerEndPoint GetServerEndPoint(EndPoint endpoint)
{
if (endpoint == null) return null;
var server = (ServerEndPoint)servers[endpoint];
if (server == null)
{
lock (servers)
{
server = (ServerEndPoint)servers[endpoint];
if (server == null)
{
if (isDisposed) throw new ObjectDisposedException(ToString());
server = new ServerEndPoint(this, endpoint, null);
// ^^ this causes ReconfigureAsync() which calls GetServerEndpoint() which can modify servers, so double check!
if (!servers.ContainsKey(endpoint))
{
servers.Add(endpoint, server);
}
var newSnapshot = serverSnapshot;
Array.Resize(ref newSnapshot, newSnapshot.Length + 1);
newSnapshot[newSnapshot.Length - 1] = server;
serverSnapshot = newSnapshot;
}
}
}
return server;
}
internal readonly CommandMap CommandMap;
private ConnectionMultiplexer(ConfigurationOptions configuration)
{
IncludeDetailInExceptions = true;
IncludePerformanceCountersInExceptions = false;
this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
var map = CommandMap = configuration.CommandMap;
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);
}
PreserveAsyncOrder = configuration.PreserveAsyncOrder;
TimeoutMilliseconds = configuration.SyncTimeout;
OnCreateReaderWriter(configuration);
UnprocessableCompletionManager = new CompletionManager(this, "multiplexer");
ServerSelectionStrategy = new ServerSelectionStrategy(this);
var configChannel = configuration.ConfigurationChannel;
if (!string.IsNullOrWhiteSpace(configChannel))
{
ConfigurationChangedChannel = Encoding.UTF8.GetBytes(configChannel);
}
lastHeartbeatTicks = Environment.TickCount;
}
partial void OnCreateReaderWriter(ConfigurationOptions configuration);
internal const int MillisecondsPerHeartbeat = 1000;
private static readonly TimerCallback heartbeat = state => ((ConnectionMultiplexer)state).OnHeartbeat();
private int _activeHeartbeatErrors;
private void OnHeartbeat()
{
try
{
int now = Environment.TickCount;
Interlocked.Exchange(ref lastHeartbeatTicks, now);
Interlocked.Exchange(ref lastGlobalHeartbeatTicks, now);
Trace("heartbeat");
var tmp = serverSnapshot;
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);
}
}
}
}
private int lastHeartbeatTicks;
private static int lastGlobalHeartbeatTicks = Environment.TickCount;
internal long LastHeartbeatSecondsAgo
{
get
{
if (pulse == null) return -1;
return unchecked(Environment.TickCount - Thread.VolatileRead(ref lastHeartbeatTicks)) / 1000;
}
}
internal Exception LastException { get; set; }
internal static long LastGlobalHeartbeatSecondsAgo => unchecked(Environment.TickCount - Thread.VolatileRead(ref lastGlobalHeartbeatTicks)) / 1000;
internal CompletionManager UnprocessableCompletionManager { get; }
/// <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 == Proxy.Twemproxy) throw new NotSupportedException("The pub/sub API is not available via twemproxy");
return new RedisSubscriber(this, asyncState);
}
/// <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)
{
if (db == -1)
db = configuration.DefaultDatabase ?? 0;
if (db < 0) throw new ArgumentOutOfRangeException(nameof(db));
if (db != 0 && RawConfig.Proxy == Proxy.Twemproxy) throw new NotSupportedException("Twemproxy only supports database 0");
// 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;