-
Notifications
You must be signed in to change notification settings - Fork 243
/
DFS.cs
1699 lines (1470 loc) · 86.6 KB
/
DFS.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
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using NetworkCommsDotNet;
using System.Threading;
using System.Net;
using NetworkCommsDotNet.DPSBase;
using NetworkCommsDotNet.Tools;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using NetworkCommsDotNet.Connections.UDP;
namespace DistributedFileSystem
{
/// <summary>
/// Provides functionality to rapidly distribute large files across a cluster of peers.
/// </summary>
public static class DFS
{
/// <summary>
/// The number of milliseconds after which a chunk request times out.
/// </summary>
public const int ChunkRequestTimeoutMS = 20000;
/// <summary>
/// The minimum size of DFS item chunks
/// </summary>
public const int MinChunkSizeInBytes = 2097152;
/// <summary>
/// The maximum number of concurrent chunk requests to make to the same peer
/// </summary>
public const int MaxConcurrentPeerRequests = 2;
/// <summary>
/// The total number of simultaneous chunk requests for a given item
/// </summary>
public const int MaxTotalItemRequests = 8;
/// <summary>
/// The maximum number of DFS items that can be built concurrently
/// </summary>
public const int MaxConcurrentLocalItemBuild = 3;
/// <summary>
/// The maximum number of times a chunk request can timeout from a peer before it is removed from the swarm
/// </summary>
public const int PeerMaxNumTimeouts = 2;
/// <summary>
/// The time in milliseconds after which a peer busy flag is removed
/// </summary>
public const int PeerBusyTimeoutMS = 1000;
/// <summary>
/// While the peer network load goes above this value it will always reply with a busy response
/// </summary>
public const double PeerBusyNetworkLoadThreshold = 0.94;
/// <summary>
/// The number of seconds to allow per MB when building DFS items
/// </summary>
public const int ItemBuildTimeoutSecsPerMB = 12;
internal static object globalDFSLocker = new object();
/// <summary>
/// Dictionary which contains a cache of the distributed items
/// </summary>
static Dictionary<string, DistributedItem> swarmedItemsDict = new Dictionary<string, DistributedItem>();
static int ChunkCacheDataTimeoutSecs = 300;
static int ChunkCacheDataCleanupIntervalSecs = 310;
static DateTime lastChunkCacheCleanup = DateTime.Now;
static object chunkDataCacheLocker = new object();
/// <summary>
/// Temporary storage for chunk data which is awaiting info.
/// This stores data based on the peer guid and packet identifier
/// </summary>
static Dictionary<ShortGuid, Dictionary<string, ChunkDataWrapper>> chunkDataCache = new Dictionary<ShortGuid, Dictionary<string, ChunkDataWrapper>>();
internal static List<string> allowedPeerIPs = new List<string>();
internal static List<string> disallowedPeerIPs = new List<string>();
internal static ManualResetEvent DFSShutdownEvent { get; private set; }
/// <summary>
/// True if the DFS has been initialised
/// </summary>
public static bool DFSInitialised { get; private set; }
/// <summary>
/// The minimum port number that will be used when initialising the DFS
/// </summary>
public static int MinTargetLocalPort { get; set; }
/// <summary>
/// The maximum port number that will be used when initialising the DFS
/// </summary>
public static int MaxTargetLocalPort { get; set; }
/// <summary>
/// If true ensures all DFS items include chunk MD5 list. Also on build clients will validate the chunk MD5
/// </summary>
public static bool ValidateEachChunkMD5 { get; set; }
/// <summary>
/// Runs a background timer which can be used to decide timeouts for item builds
/// </summary>
static Thread elapsedTimerThread;
/// <summary>
/// The number of seconds since the initialisation of the DFS. Used as an internal timer, rather than DateTime.Now, to
/// ensure builds do not time out when a suspended process is restarted.
/// </summary>
public static long ElapsedExecutionSeconds { get; private set; }
/// <summary>
/// Linking this DFS to others
/// </summary>
static Thread linkWorkerThread;
static string linkTargetIP;
static int linkTargetPort;
/// <summary>
/// We keep a reference to sendReceiveOptions which use no data compression in the DFS
/// </summary>
internal static SendReceiveOptions nullCompressionSRO;
/// <summary>
/// We keep a reference to sendReceiveOptions which use a high Receive priority
/// </summary>
static SendReceiveOptions highPrioReceiveSRO;
/// <summary>
/// True if this DFS is linked with another peer
/// </summary>
public static bool IsLinked { get; private set; }
/// <summary>
/// The link mode being used
/// </summary>
public static DFSLinkMode LinkMode { get; private set; }
static int linkRequestTimeoutSecs = 10;
static int linkRequestIntervalSecs = 5;
/// <summary>
/// The number of link items to build concurrently
/// </summary>
static int concurrentNumLinkItems = 2;
/// <summary>
/// A private task factory for assembling new local DFS items. If we use the NetworkComms.TaskFactory we can end up deadlocking and prevent incoming packets from being handled.
/// </summary>
internal static TaskFactory BuildTaskFactory;
/// <summary>
/// The total number of completed chunk requests across all DFS items
/// </summary>
public static long TotalNumReturnedChunkRequests { get; private set; }
private static object TotalNumReturnedChunkRequestsLocker = new object();
/// <summary>
/// The total number of chunks requests by the local DFS
/// </summary>
public static long TotalNumRequestedChunks { get { return _totalNumRequestedChunks; } }
internal static long _totalNumRequestedChunks;
static DFS()
{
MinTargetLocalPort = 10000;
MaxTargetLocalPort = 10999;
//BuildTaskFactory = new TaskFactory(new LimitedParallelismTaskScheduler(MaxConcurrentLocalItemBuild));
BuildTaskFactory = new TaskFactory();
nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer<ProtobufSerializer>(),
new List<DataProcessor>(),
new Dictionary<string, string>());
highPrioReceiveSRO = (SendReceiveOptions)NetworkComms.DefaultSendReceiveOptions.Clone();
highPrioReceiveSRO.Options.Add("ReceiveHandlePriority", Enum.GetName(typeof(ThreadPriority), ThreadPriority.AboveNormal));
}
/// <summary>
/// Initialises the DFS
/// </summary>
/// <param name="initialPort">The local listen port to use</param>
/// <param name="rangeRandomPortFailover">True if a random port should be select if the initialPort is unavailable</param>
public static void Initialise(int initialPort, bool rangeRandomPortFailover = true)
{
try
{
if (initialPort > MaxTargetLocalPort || initialPort < MinTargetLocalPort)
throw new CommsSetupShutdownException("Provided initial DFS port must be within the MinTargetLocalPort and MaxTargetLocalPort range.");
if (Connection.AllExistingLocalListenEndPoints().Count > 0)
throw new CommsSetupShutdownException("Unable to initialise DFS if already listening for incoming connections.");
DFSShutdownEvent = new ManualResetEvent(false);
elapsedTimerThread = new Thread(ElapsedTimerWorker);
elapsedTimerThread.Name = "DFSElapsedTimerThread";
elapsedTimerThread.IsBackground = true;
elapsedTimerThread.Start();
//Load the allowed IP addresses
LoadAllowedDisallowedPeerIPs();
NetworkComms.IgnoreUnknownPacketTypes = true;
#region Add Packet Handlers
//TCP
NetworkComms.AppendGlobalIncomingPacketHandler<ItemAssemblyConfig>("DFS_IncomingLocalItemBuild", IncomingLocalItemBuild);
NetworkComms.AppendGlobalIncomingPacketHandler<string[]>("DFS_RequestLocalItemBuild", RequestLocalItemBuilds);
//UDP
//DO NOT MAKE THIS METHOD USE highPriority. If this method blocks it prevents other data coming in
NetworkComms.AppendGlobalIncomingPacketHandler<ChunkAvailabilityRequest>("DFS_ChunkAvailabilityInterestRequest", IncomingChunkInterestRequest);
NetworkComms.AppendGlobalIncomingPacketHandler<byte[]>("DFS_ChunkAvailabilityInterestReplyData", IncomingChunkInterestReplyData);
//UDP & TCP
NetworkComms.AppendGlobalIncomingPacketHandler<ChunkAvailabilityReply>("DFS_ChunkAvailabilityInterestReplyInfo", IncomingChunkInterestReplyInfo);
//UDP
NetworkComms.AppendGlobalIncomingPacketHandler<string>("DFS_ChunkAvailabilityRequest", IncomingChunkAvailabilityRequest, highPrioReceiveSRO);
//UDP
NetworkComms.AppendGlobalIncomingPacketHandler<PeerChunkAvailabilityUpdate>("DFS_PeerChunkAvailabilityUpdate", IncomingPeerChunkAvailabilityUpdate, highPrioReceiveSRO);
//UDP
NetworkComms.AppendGlobalIncomingPacketHandler<ItemRemovalUpdate>("DFS_ItemRemovalUpdate", IncomingItemRemovalUpdate, highPrioReceiveSRO);
//UDP
NetworkComms.AppendGlobalIncomingPacketHandler<KnownPeerEndPoints>("DFS_KnownPeersUpdate", KnownPeersUpdate, highPrioReceiveSRO);
NetworkComms.AppendGlobalIncomingPacketHandler<string>("DFS_KnownPeersRequest", KnownPeersRequest, highPrioReceiveSRO);
//TCP
NetworkComms.AppendGlobalIncomingPacketHandler<DFSLinkRequest>("DFS_ItemLinkRequest", IncomingRemoteItemLinkRequest);
NetworkComms.AppendGlobalConnectionCloseHandler(DFSConnectionShutdown);
#endregion
if (DFS.loggingEnabled)
{
DFS.Logger.Info("Starting DFS listeners.");
DFS.Logger.Info("Comms IP filters - " + HostInfo.IP.RestrictLocalAddressRanges.Select((range) => range.ToString()).Aggregate((left,right) => left.ToString() + ", " + right.ToString()).ToString());
DFS.Logger.Info("Detected addresses - " + HostInfo.IP.FilteredLocalAddresses().Select((address) => address.ToString()).Aggregate((left, right) => left.ToString() + ", " + right.ToString()).ToString());
}
#region OpenIncomingPorts
try
{
Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, initialPort));
Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, initialPort));
}
catch (Exception)
{
//If an exception occurred first reset NetworkComms.Net
NetworkComms.Shutdown();
if (rangeRandomPortFailover)
{
//Keep trying to listen on an ever increasing port number
for (int tryPort = MinTargetLocalPort; tryPort <= MaxTargetLocalPort; tryPort++)
{
try
{
Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, tryPort));
Connection.StartListening(ConnectionType.UDP, new IPEndPoint(IPAddress.Any, tryPort));
//Once we are successfully listening we can break
break;
}
catch (Exception) { NetworkComms.Shutdown(); }
if (tryPort == MaxTargetLocalPort)
throw new CommsSetupShutdownException("Failed to find local available listen port while trying to initialise DFS.");
}
}
else
throw;
}
//Do some validation
if (Connection.ExistingLocalListenEndPoints(ConnectionType.TCP).Except(Connection.ExistingLocalListenEndPoints(ConnectionType.UDP)).Count() > 0)
throw new CommsSetupShutdownException("Port mismatch when comparing TCP and UDP local listen end points.");
if ((from current in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)
where ((IPEndPoint)current).Port > MaxTargetLocalPort || ((IPEndPoint)current).Port < MinTargetLocalPort
select current).Count() > 0)
throw new CommsSetupShutdownException("Local port selected that is not within the valid range.");
#endregion
if (DFS.loggingEnabled) DFS._DFSLogger.Info("Initialised DFS");
}
catch (Exception e)
{
LogTools.LogException(e, "Error_DFSIntialise");
}
DFSInitialised = true;
}
/// <summary>
/// Initialises this DFS peer to repeat all items available on the linkTargetIP
/// </summary>
/// <param name="linkTargetIP">The IPAddress corresponding with the link seed</param>
/// <param name="linkTargetPort">The port corresponding with the link seed</param>
/// <param name="linkMode">The link mode to be used</param>
public static void InitialiseDFSLink(string linkTargetIP, int linkTargetPort, DFSLinkMode linkMode)
{
if (!DFSInitialised)
throw new Exception("Attempted to initialise DFS link before DFS had been initialised.");
if (linkTargetIP == HostInfo.IP.FilteredLocalAddresses()[0].ToString() &&
Connection.ExistingLocalListenEndPoints(ConnectionType.TCP, new IPEndPoint(HostInfo.IP.FilteredLocalAddresses()[0], linkTargetPort)).Count() > 0)
throw new Exception("Attempted to initialise DFS link with local peer.");
lock (globalDFSLocker)
{
if (IsLinked) throw new Exception("Attempted to initialise DFS link once already initialised.");
DFS.linkTargetIP = linkTargetIP;
DFS.linkTargetPort = linkTargetPort;
DFS.LinkMode = linkMode;
linkWorkerThread = new Thread(LinkModeWorker);
linkWorkerThread.Name = "DFSLinkWorkerThread";
linkWorkerThread.IsBackground = true;
linkWorkerThread.Start();
IsLinked = true;
}
}
/// <summary>
/// Background worker thread which maintains the link depending on the selected link mode
/// </summary>
private static void LinkModeWorker()
{
do
{
try
{
//This links any existing local items and retrieves a list of all remote items
TCPConnection primaryServer = TCPConnection.GetConnection(new ConnectionInfo(linkTargetIP, linkTargetPort));
DFSLinkRequest availableLinkTargetItems = primaryServer.SendReceiveObject<DFSLinkRequest, DFSLinkRequest>("DFS_ItemLinkRequest", "DFS_ItemLinkReply", linkRequestTimeoutSecs * 1000, new DFSLinkRequest(AllLocalDFSItemsWithBuildTime(), false));
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("LinkModeWorker could link " + availableLinkTargetItems.AvailableItems.Count+ " items from target.");
if (LinkMode == DFSLinkMode.LinkAndRepeat)
{
//We get a list of items we don't have
string[] allLocalItems = AllLocalDFSItemKeys(false);
//We only begin a new link cycle if all local items are complete
if (allLocalItems.Length == AllLocalDFSItemKeys(true).Length)
{
//Pull out the items we want to request
//We order the items by item creation time starting with the newest
string[] itemsToRequest = (from current in availableLinkTargetItems.AvailableItems
where !allLocalItems.Contains(current.Key)
orderby current.Value descending
select current.Key).ToArray();
//Make the request for items we do not have
if (itemsToRequest.Length > 0)
{
primaryServer.SendObject("DFS_RequestLocalItemBuild", itemsToRequest.Take(concurrentNumLinkItems).ToArray(), nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("LinkModeWorker made a request to link " + itemsToRequest.Take(concurrentNumLinkItems).Count() + " items.");
}
}
}
}
catch (CommsException)
{
//We were unable to talk with our link peer, just keep trying until they hopefully respond
}
catch (Exception e)
{
LogTools.LogException(e, "RepeaterWorkerError");
}
if (DFSShutdownEvent.WaitOne(linkRequestIntervalSecs * 1000))
break;
} while (true);
IsLinked = false;
}
private static void LoadAllowedDisallowedPeerIPs()
{
string allowedFileName = "DFSAllowedPeerIPs.txt";
string disallowedFilename = "DFSDisallowedPeerIPs.txt";
//DFSAllowedPeerIPs.txt
//Allowed takes precedence
//We have to check a directory up as well incase this is running in the win client manager
if (File.Exists(allowedFileName) || File.Exists("..\\" + allowedFileName))
{
string[] lines;
if (File.Exists(allowedFileName))
lines = File.ReadAllLines(allowedFileName);
else
lines = File.ReadAllLines("..\\" + allowedFileName);
lines = (from current in lines
where !current.StartsWith("#") && current != ""
select current).ToArray();
for (int i = 0; i < lines.Length; i++)
allowedPeerIPs.Add(lines[i]);
}
else if (File.Exists(disallowedFilename) || File.Exists("..\\" + disallowedFilename))
{
string[] lines;
if (File.Exists(disallowedFilename))
lines = File.ReadAllLines(disallowedFilename);
else
lines = File.ReadAllLines("..\\" + disallowedFilename);
lines = (from current in lines
where !current.StartsWith("#") && current != ""
select current).ToArray();
for (int i = 0; i < lines.Length; i++)
disallowedPeerIPs.Add(lines[i]);
}
if (disallowedPeerIPs.Count > 0 && allowedPeerIPs.Count > 0)
throw new Exception("Can not set both allowed and disallowed peers.");
}
/// <summary>
/// Shutdown the DFS. All local DFS items are deleted.
/// </summary>
public static void Shutdown()
{
if (DFSShutdownEvent!=null)
DFSShutdownEvent.Set();
RemoveAllItemsFromLocalOnly();
//Remove all packethandlers
NetworkComms.RemoveGlobalIncomingPacketHandler<ItemAssemblyConfig>("DFS_IncomingLocalItemBuild", IncomingLocalItemBuild);
NetworkComms.RemoveGlobalIncomingPacketHandler<string[]>("DFS_RequestLocalItemBuild", RequestLocalItemBuilds);
NetworkComms.RemoveGlobalIncomingPacketHandler<ChunkAvailabilityRequest>("DFS_ChunkAvailabilityInterestRequest", IncomingChunkInterestRequest);
NetworkComms.RemoveGlobalIncomingPacketHandler<byte[]>("DFS_ChunkAvailabilityInterestReplyData", IncomingChunkInterestReplyData);
NetworkComms.RemoveGlobalIncomingPacketHandler<ChunkAvailabilityReply>("DFS_ChunkAvailabilityInterestReplyInfo", IncomingChunkInterestReplyInfo);
NetworkComms.RemoveGlobalIncomingPacketHandler<string>("DFS_ChunkAvailabilityRequest", IncomingChunkAvailabilityRequest);
NetworkComms.RemoveGlobalIncomingPacketHandler<PeerChunkAvailabilityUpdate>("DFS_PeerChunkAvailabilityUpdate", IncomingPeerChunkAvailabilityUpdate);
NetworkComms.RemoveGlobalIncomingPacketHandler<ItemRemovalUpdate>("DFS_ItemRemovalUpdate", IncomingItemRemovalUpdate);
NetworkComms.RemoveGlobalIncomingPacketHandler<KnownPeerEndPoints>("DFS_KnownPeersUpdate", KnownPeersUpdate);
NetworkComms.RemoveGlobalIncomingPacketHandler<string>("DFS_KnownPeersRequest", KnownPeersRequest);
NetworkComms.RemoveGlobalIncomingPacketHandler<DFSLinkRequest>("DFS_ItemLinkRequest", IncomingRemoteItemLinkRequest);
NetworkComms.RemoveGlobalConnectionCloseHandler(DFSConnectionShutdown);
DFSInitialised = false;
lock (globalDFSLocker)
{
//Cleanup the disk DFS item directory if necessary.
if (Directory.Exists("DFS_" + NetworkComms.NetworkIdentifier))
Directory.Delete("DFS_" + NetworkComms.NetworkIdentifier, true);
}
if (elapsedTimerThread != null && !elapsedTimerThread.Join(2000))
{
try
{
LogTools.LogException(new Exception("DFS elapsedTimerThread did not close after 2 seconds."), "DFSShutdownError");
elapsedTimerThread.Abort();
}
catch (Exception) { }
}
if (loggingEnabled) DFS._DFSLogger.Debug("DFS Shutdown.");
}
/// <summary>
/// Runs in the background to estimate the elapsed time of the application.
/// We can't use DateTime as elapsed time should not include time during which process was suspended
/// </summary>
private static void ElapsedTimerWorker()
{
ElapsedExecutionSeconds = 0;
try
{
while (true)
{
if (DFSShutdownEvent.WaitOne(1000))
break;
ElapsedExecutionSeconds++;
}
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
LogTools.LogException(ex, "DFSElapsedWorkerError");
}
}
#region Logging
internal static object loggingLocker = new object();
internal static bool loggingEnabled = false;
internal static ILogger _DFSLogger;
/// <summary>
/// Access the networkComms logger externally. Allows logging from external sources
/// </summary>
public static ILogger Logger
{
get { return _DFSLogger; }
}
/// <summary>
/// Enable logging in networkComms using the provided logging adaptor
/// </summary>
/// <param name="logger"></param>
public static void EnableLogging(ILogger logger)
{
lock (loggingLocker)
{
loggingEnabled = true;
_DFSLogger = logger;
}
}
/// <summary>
/// Disable logging in networkComms
/// </summary>
public static void DisableLogging()
{
lock (loggingLocker)
{
loggingEnabled = false;
if (_DFSLogger != null)
_DFSLogger.Shutdown();
}
}
#endregion
/// <summary>
/// Returns true if the provided item is already present within the swarm
/// </summary>
/// <param name="item">The relevant DFS item</param>
/// <returns></returns>
public static bool ItemAlreadyInLocalCache(DistributedItem item)
{
lock (globalDFSLocker)
{
if (swarmedItemsDict.ContainsKey(item.Data.CompleteDataCheckSum))
{
if (swarmedItemsDict[item.Data.CompleteDataCheckSum].Data.ItemBytesLength == item.Data.ItemBytesLength)
return true;
else
throw new Exception("Potential Md5 conflict detected in DFS.");
}
return false;
}
}
/// <summary>
/// Returns true if an item with a matching itemCheckSum is present within the local cache
/// </summary>
/// <param name="itemCheckSum">The relevant item MD5 checksum</param>
/// <returns></returns>
public static bool ItemAlreadyInLocalCache(string itemCheckSum)
{
return swarmedItemsDict.ContainsKey(itemCheckSum);
}
/// <summary>
/// Returns the most recently completed item in the DFS. Returns null if there are no DFS items.
/// </summary>
/// <returns></returns>
public static DistributedItem MostRecentlyCompletedItem()
{
lock (globalDFSLocker)
{
if (swarmedItemsDict.Count > 0)
return (from current in swarmedItemsDict.Values orderby current.ItemBuildCompleted descending select current).First();
else
return null;
}
}
/// <summary>
/// Returns the distributed item with a matching itemCheckSum. Returns null if item is not found.
/// </summary>
/// <param name="itemCheckSum">The item MD5 checksum to match</param>
/// <returns></returns>
public static DistributedItem GetDistributedItemByChecksum(string itemCheckSum)
{
lock (globalDFSLocker)
{
if (swarmedItemsDict.ContainsKey(itemCheckSum))
return swarmedItemsDict[itemCheckSum];
else
return null;
}
}
/// <summary>
/// Returns the distributed item with a matching itemIdentifier. Returns null if item is not found.
/// </summary>
/// <param name="itemIdentifier">The item identifier to match</param>
/// <returns></returns>
public static DistributedItem GetDistributedItemByIdentifier(string itemIdentifier)
{
lock (globalDFSLocker)
{
foreach (DistributedItem item in swarmedItemsDict.Values)
{
if (item.ItemIdentifier == itemIdentifier)
return item;
}
}
return null;
}
/// <summary>
/// Remove an item from the DFS. Possibly swarmWide and with or without a removal broadcast
/// </summary>
/// <param name="itemCheckSum">The checksum corresponding with the item to remove</param>
/// <param name="broadcastRemoval">If true all peers will be notified that we are removing this item.</param>
/// <param name="removeSwarmWide">True if this item should be removed swarm wide</param>
public static void RemoveItem(string itemCheckSum, bool broadcastRemoval = true, bool removeSwarmWide = false)
{
try
{
if (!broadcastRemoval && removeSwarmWide)
throw new Exception("BroadcastRemoval must be true if RemoveSwarmWide is also true.");
DistributedItem itemToRemove = null;
lock (globalDFSLocker)
{
if (swarmedItemsDict.ContainsKey(itemCheckSum))
{
itemToRemove = swarmedItemsDict[itemCheckSum];
swarmedItemsDict.Remove(itemCheckSum);
//Set the abort build here incase another thread tries to use the item
itemToRemove.ItemClosed = true;
}
}
//This BroadcastItemRemoval has to be outside lock (globalDFSLocker) otherwise it can deadlock
if (itemToRemove != null)
{
if (broadcastRemoval)
//Broadcast to the swarm we are removing this file
itemToRemove.SwarmChunkAvailability.BroadcastItemRemoval(itemCheckSum, removeSwarmWide);
//Dispose of the distributed item incase it has any open file handles
itemToRemove.Dispose();
}
//try { GC.Collect(); }
//catch (Exception) { }
}
catch (Exception e)
{
LogTools.LogException(e, "DFS_RemoveItemError");
}
}
/// <summary>
/// Removes all items from local only
/// </summary>
/// <param name="broadcastRemoval">If true all peers will be notified that we are removing all items.</param>
public static void RemoveAllItemsFromLocalOnly(bool broadcastRemoval = false)
{
string[] keysToRemove;
lock (globalDFSLocker)
keysToRemove = swarmedItemsDict.Keys.ToArray();
foreach (string key in keysToRemove)
RemoveItem(key, broadcastRemoval);
}
/// <summary>
/// Closes all connections to peers who have completed items
/// </summary>
public static void CloseConnectionToCompletedPeers()
{
lock (globalDFSLocker)
{
foreach(var item in swarmedItemsDict.Values)
item.SwarmChunkAvailability.CloseConnectionsToCompletedPeers(item.Data.TotalNumChunks);
}
}
/// <summary>
/// Remove any items from the DFS with a matching itemTypeStr
/// </summary>
/// <param name="ItemTypeStr">The item type string to match</param>
/// <param name="broadcastRemoval">If true all peers will be notified that we are removing matching items.</param>
public static void RemoveAllItemsFromLocalOnly(string ItemTypeStr, bool broadcastRemoval = false)
{
List<string> keysToRemove = new List<string>();
lock (globalDFSLocker)
{
foreach (DistributedItem item in swarmedItemsDict.Values)
{
if (item.ItemTypeStr == ItemTypeStr)
keysToRemove.Add(item.Data.CompleteDataCheckSum);
}
}
foreach (string key in keysToRemove)
RemoveItem(key, broadcastRemoval);
}
/// <summary>
/// Introduces a new item into the swarm and sends a build command to the originating requester
/// </summary>
/// <param name="peerConnection">The peer which requested the DFS item</param>
/// <param name="itemToDistribute">The item to be distributed</param>
/// <param name="completedPacketType">The packet type to use once the item has been fully assembled</param>
public static void PushItemToPeer(Connection peerConnection, DistributedItem itemToDistribute, string completedPacketType)
{
try
{
if (peerConnection.ConnectionInfo.ConnectionType != ConnectionType.TCP)
throw new Exception("Only able to push DFS item when the request is made via TCP.");
if (itemToDistribute.ItemClosed)
throw new ArgumentException("Unable to push a closed item.");
ItemAssemblyConfig assemblyConfig;
lock (globalDFSLocker)
{
//First double check to see if it's already in the swarm
if (!ItemAlreadyInLocalCache(itemToDistribute))
swarmedItemsDict.Add(itemToDistribute.Data.CompleteDataCheckSum, itemToDistribute);
else
itemToDistribute = swarmedItemsDict[itemToDistribute.Data.CompleteDataCheckSum];
}
itemToDistribute.IncrementPushCount();
//We add the requester to the item swarm at this point
itemToDistribute.SwarmChunkAvailability.AddOrUpdateCachedPeerChunkFlags(peerConnection.ConnectionInfo, new ChunkFlags(0));
//There is a possibility when we create this assembly config that the peer has been removed again
//We handle this on the peer end
assemblyConfig = new ItemAssemblyConfig(itemToDistribute, completedPacketType);
//Send the config information to the client that wanted the file
peerConnection.SendObject("DFS_IncomingLocalItemBuild", assemblyConfig, nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Debug("Pushed DFS item " + itemToDistribute.Data.CompleteDataCheckSum + " to peer " + peerConnection + ".");
}
catch (CommsException)
{
//LogTools.LogException(ex, "CommsError_AddItemToSwarm");
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_AddItemToSwarm");
}
//try { GC.Collect(); }
//catch (Exception) { }
}
/// <summary>
/// Adds a distributed item to the local cache and informs any known peers of the item availability
/// </summary>
/// <param name="itemToAdd">The item to add</param>
/// <returns>The actual item added to the local cache. May not be the provided itemToAdd if an item with the same
/// checksum already existed.</returns>
public static DistributedItem AddItem(DistributedItem itemToAdd)
{
try
{
lock (globalDFSLocker)
{
//First double check to see if it's already in the swarm
if (!ItemAlreadyInLocalCache(itemToAdd))
{
swarmedItemsDict.Add(itemToAdd.Data.CompleteDataCheckSum, itemToAdd);
if (DFS.loggingEnabled) DFS._DFSLogger.Debug("... added existing item to DFS (" + itemToAdd.Data.CompleteDataCheckSum + ").");
}
else
{
itemToAdd = swarmedItemsDict[itemToAdd.Data.CompleteDataCheckSum];
if (DFS.loggingEnabled) DFS._DFSLogger.Debug("... added new item to DFS (" + itemToAdd.Data.CompleteDataCheckSum + ").");
}
}
//Send the config information to the client that wanted the file
//NetworkComms.SendObject("DFS_IncomingLocalItemBuild, requestOriginConnectionId, false, new ItemAssemblyConfig(itemToDistribute, completedPacketType));
itemToAdd.SwarmChunkAvailability.BroadcastLocalAvailability(itemToAdd.Data.CompleteDataCheckSum);
}
catch (CommsException)
{
//LogTools.LogException(ex, "CommsError_AddItemToSwarm");
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_AddItemToSwarm");
}
//try { GC.Collect(); }
//catch (Exception) { }
return itemToAdd;
}
/// <summary>
/// Communicates with the provided peer to see if any item swarms can be linked. This is a single link event,
/// possibly use InitialiseDFSLink() for a maintained link.
/// </summary>
/// <param name="peerIP">The IPAddress of the peer</param>
/// <param name="peerPort">The port of the peer</param>
public static void CheckForSharedItems(string peerIP, int peerPort)
{
try
{
TCPConnection.GetConnection(new ConnectionInfo(peerIP, peerPort)).SendObject("DFS_ItemLinkRequest", new DFSLinkRequest(AllLocalDFSItemsWithBuildTime(), false), nullCompressionSRO);
}
catch (CommsException)
{
}
}
/// <summary>
/// Returns all item MD5 checksums for DFS items
/// </summary>
/// <param name="completeItemsOnly">If true only returns checksums for completed items</param>
/// <returns></returns>
public static string[] AllLocalDFSItemKeys(bool completeItemsOnly = true)
{
string[] returnArray;
lock (globalDFSLocker)
returnArray = (from current in swarmedItemsDict where (completeItemsOnly ? current.Value.LocalItemComplete() : true) select current.Key).ToArray();
return returnArray;
}
/// <summary>
/// Returns a dictionary of DFS items along with corresponding ItemBuildCompleted times
/// </summary>
/// <param name="completeItemsOnly">If true only returns information for completed items</param>
/// <returns></returns>
public static Dictionary<string, DateTime> AllLocalDFSItemsWithBuildTime(bool completeItemsOnly = true)
{
string[] itemCheckSums = AllLocalDFSItemKeys(completeItemsOnly);
Dictionary<string, DateTime> returnDict = new Dictionary<string, DateTime>();
lock (globalDFSLocker)
{
foreach (string item in itemCheckSums)
{
if (swarmedItemsDict.ContainsKey(item))
returnDict.Add(item, swarmedItemsDict[item].ItemBuildCompleted);
}
}
return returnDict;
}
/// <summary>
/// Flick through the chunk data cache and remove any items that have timed out
/// </summary>
private static void CheckForChunkDataCacheTimeouts()
{
lock (chunkDataCacheLocker)
{
if ((DateTime.Now - lastChunkCacheCleanup).TotalSeconds > ChunkCacheDataCleanupIntervalSecs)
{
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Starting ChunkDataCache cleanup.");
int removedCount = 0;
ShortGuid[] peerKeys = chunkDataCache.Keys.ToArray();
for (int i = 0; i < peerKeys.Length; i++)
{
string[] dataSequenceKeys = chunkDataCache[peerKeys[i]].Keys.ToArray();
for (int k = 0; k < dataSequenceKeys.Length; k++)
{
if ((DateTime.Now - chunkDataCache[peerKeys[i]][dataSequenceKeys[k]].TimeCreated).TotalSeconds > ChunkCacheDataTimeoutSecs)
{
//If we have timed out data we will remove it
chunkDataCache[peerKeys[i]].Remove(dataSequenceKeys[k]);
removedCount++;
}
}
//If there is no longer any data for a particular peer we remove the peer entry
if (chunkDataCache[peerKeys[i]].Count == 0)
chunkDataCache.Remove(peerKeys[i]);
}
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Completed ChunkDataCache cleanup having removed " + removedCount + " items.");
lastChunkCacheCleanup = DateTime.Now;
}
}
}
#region NetworkCommsDelegates
/// <summary>
/// If a connection is disconnected we want to make sure we handle it within the DFS
/// </summary>
/// <param name="connection"></param>
private static void DFSConnectionShutdown(Connection connection)
{
try
{
//We can only rely on the network identifier if this is a TCP connection shutting down
if (connection.ConnectionInfo.ConnectionType == ConnectionType.TCP && connection.ConnectionInfo.NetworkIdentifier != ShortGuid.Empty)
{
List<DistributedItem> allItems;
lock (globalDFSLocker)
allItems = swarmedItemsDict.Values.ToList();
//Remove peer from any items
foreach (var item in allItems)
item.SwarmChunkAvailability.RemovePeerIPEndPointFromSwarm(connection.ConnectionInfo.NetworkIdentifier, (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint);
//Remove any outstanding chunk requests for this peer
lock (chunkDataCacheLocker)
chunkDataCache.Remove(connection.ConnectionInfo.NetworkIdentifier);
if (loggingEnabled) DFS._DFSLogger.Debug("DFSConnectionShutdown Global - Removed peer from all items - " + connection + ".");
}
else
if (loggingEnabled) DFS._DFSLogger.Trace("DFSConnectionShutdown Global - Disconnection ignored - " + connection + ".");
}
catch (CommsException e)
{
LogTools.LogException(e, "CommsError_DFSConnectionShutdown");
}
catch (Exception e)
{
LogTools.LogException(e, "Error_DFSConnectionShutdown");
}
}
/// <summary>
/// UDP - Used by a client when requesting a list of known peers
/// </summary>
/// <param name="packetHeader"></param>
/// <param name="connection"></param>
/// <param name="itemCheckSum"></param>
private static void KnownPeersRequest(PacketHeader packetHeader, Connection connection, string itemCheckSum)
{
try
{
DistributedItem selectedItem = null;
if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... known peers request for item (" + itemCheckSum + ").");
lock (globalDFSLocker)
{
if (swarmedItemsDict.ContainsKey(itemCheckSum))
selectedItem = swarmedItemsDict[itemCheckSum];
}
if (selectedItem == null)
//Inform peer that we don't actually have the requested item so that it won't bother us again