File: PeerMaintainer.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (676 lines) | stat: -rw-r--r-- 28,913 bytes parent folder | download | duplicates (9)
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Runtime;
    using System.Security;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.ServiceModel.Diagnostics;
    using System.Threading;
    using Microsoft.Win32;


    delegate void NeighborClosedHandler(IPeerNeighbor neighbor);
    delegate void NeighborConnectedHandler(IPeerNeighbor neighbor);
    delegate void MaintainerClosedHandler();
    delegate void ReferralsAddedHandler(IList<Referral> referrals, IPeerNeighbor neighbor);

    interface IPeerMaintainer
    {
        event NeighborClosedHandler NeighborClosed;
        event NeighborConnectedHandler NeighborConnected;
        event MaintainerClosedHandler MaintainerClosed;
        event ReferralsAddedHandler ReferralsAdded;

        int ConnectedNeighborCount { get; }
        int NonClosingNeighborCount { get; }
        bool IsOpen { get; }

        IAsyncResult BeginOpenNeighbor(PeerNodeAddress to, TimeSpan timeout, AsyncCallback callback, object asyncState);
        IPeerNeighbor EndOpenNeighbor(IAsyncResult result);

        void CloseNeighbor(IPeerNeighbor neighbor, PeerCloseReason closeReason);

        IPeerNeighbor FindDuplicateNeighbor(PeerNodeAddress address);
        PeerNodeAddress GetListenAddress();
        IPeerNeighbor GetLeastUsefulNeighbor();
    }

    interface IConnectAlgorithms : IDisposable
    {
        void Connect(TimeSpan timeout);
        void Initialize(IPeerMaintainer maintainer, PeerNodeConfig config, int wantedConnectedNeighbors, Dictionary<EndpointAddress, Referral> referralCache);
        void PruneConnections();
        void UpdateEndpointsCollection(ICollection<PeerNodeAddress> src);
    }

    class PeerMaintainerBase<TConnectAlgorithms> : IPeerMaintainer where TConnectAlgorithms : IConnectAlgorithms, new()
    {
        public delegate void ConnectCallback(Exception e);

        ConnectCallback connectCallback;

        PeerNodeConfig config;
        PeerFlooder flooder;
        PeerNeighborManager neighborManager;
        Dictionary<EndpointAddress, Referral> referralCache;
        object thisLock;
        PeerNodeTraceRecord traceRecord;

        // Double-checked locking pattern requires volatile for read/write synchronization
        volatile bool isRunningMaintenance = false;                    // true indicates performing connection Maintenance
        volatile bool isOpen = false;
        IOThreadTimer maintainerTimer;
        public event ReferralsAddedHandler ReferralsAdded;

        object ThisLock
        {
            get { return thisLock; }
        }

        public PeerMaintainerBase(PeerNodeConfig config, PeerNeighborManager neighborManager, PeerFlooder flooder)
        {
            this.neighborManager = neighborManager;
            this.flooder = flooder;
            this.config = config;
            thisLock = new object();

            referralCache = new Dictionary<EndpointAddress, Referral>();
            maintainerTimer = new IOThreadTimer(new Action<object>(OnMaintainerTimer), this, false);
        }

        // Maintainer is expected to validate and accept the contents of referrals
        // and to determine how many referrals it will accept from the array.
        // Neighbor reference is passed in case the Maintainer decided to reject a referral 
        // based on invalid content and close the neighbor.
        public bool AddReferrals(IList<Referral> referrals, IPeerNeighbor neighbor)
        {
            Fx.Assert(null != config.Resolver, "");

            bool valid = true;
            bool canShareReferrals = false;
            try
            {
                canShareReferrals = config.Resolver.CanShareReferrals;
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e)) throw;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(SR.GetString(SR.ResolverException), e);
            }
            if (referrals != null && canShareReferrals)
            {
                foreach (Referral referral in referrals)
                {
                    // If any referral is invalid then the connection is bad so don't accept any referals from this neighbor.
                    if (referral == null
                    || referral.NodeId == PeerTransportConstants.InvalidNodeId
                    || !PeerValidateHelper.ValidNodeAddress(referral.Address)
                    || !PeerValidateHelper.ValidReferralNodeAddress(referral.Address))
                    {
                        valid = false;
                        break;
                    }
                }
                if (valid)
                {
                    lock (ThisLock)
                    {
                        foreach (Referral referral in referrals)
                        {
                            EndpointAddress key = referral.Address.EndpointAddress;
                            if (referralCache.Count <= this.config.MaxReferralCacheSize && !referralCache.ContainsKey(key))
                            {
                                referralCache.Add(key, referral);
                            }
                        }
                    }

                    // Invoke any handler that is interested in Referrals being added.
                    ReferralsAddedHandler handler = ReferralsAdded;
                    if (handler != null)
                    {
                        ReferralsAdded(referrals, neighbor);
                    }
                }
            }
            return valid;
        }

        [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
        public void Close()
        {
            lock (ThisLock)
            {
                isOpen = false;
            }
            maintainerTimer.Cancel();                        // No reconnect while closed
            SystemEvents.PowerModeChanged -= new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
            MaintainerClosedHandler handler = MaintainerClosed;
            if (handler != null)
            {
                handler();
            }
        }

        void InitialConnection(object dummy)
        {
            // Are we open and is any maintenance activity occuring
            if (isOpen)
            {
                bool continueMaintenance = false;
                if (!isRunningMaintenance)
                {
                    lock (ThisLock)
                    {
                        if (!isRunningMaintenance)
                        {
                            isRunningMaintenance = true;
                            continueMaintenance = true;
                        }
                    }
                }
                if (continueMaintenance)
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerInitialConnect, this.config.MeshId));
                        TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                            record, this, null);
                    }

                    TimeoutHelper timeoutHelper = new TimeoutHelper(config.MaintainerTimeout);
                    Exception exception = null;
                    // The connection algorithm may be pluggable if we provide an api or metadata to enable it.
                    // I am sure that research would be interested in doing such a thing.
                    try
                    {
                        maintainerTimer.Cancel();                   // No reconnect until after connect has succeeded

                        using (IConnectAlgorithms connectAlgorithm = (IConnectAlgorithms)new TConnectAlgorithms())
                        {
                            connectAlgorithm.Initialize(this, config, config.MinNeighbors, referralCache);
                            if (referralCache.Count == 0)
                            {
                                ReadOnlyCollection<PeerNodeAddress> addresses = ResolveNewAddresses(timeoutHelper.RemainingTime(), false);
                                connectAlgorithm.UpdateEndpointsCollection(addresses);
                            }
                            if (isOpen)
                            {
                                connectAlgorithm.Connect(timeoutHelper.RemainingTime());
                            }
                        }
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e)) throw;
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        exception = e;                              // Exeption is saved and transferred
                    }
                    if (isOpen)
                    {
                        try
                        {
                            lock (ThisLock)
                            {
                                if (isOpen)
                                {
                                    // No reconnect until after connect has succeeded
                                    if (neighborManager.ConnectedNeighborCount < 1)
                                    {
                                        maintainerTimer.Set(config.MaintainerRetryInterval);
                                    }
                                    else
                                    {
                                        maintainerTimer.Set(config.MaintainerInterval);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e)) throw;
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                            if (exception == null) exception = e;                // Exeption is saved and transferred via callback
                        }
                    }
                    lock (ThisLock)
                    {
                        isRunningMaintenance = false;
                    }
                    if (connectCallback != null)
                    {
                        connectCallback(exception);
                    }
                }
            }
        }

        // This activity maintains the connected nodes
        void MaintainConnections(object dummy)
        {
            // Are we open and is any maintenance activity occuring
            if (isOpen)
            {
                bool continueMaintenance = false;
                if (!isRunningMaintenance)
                {
                    lock (ThisLock)
                    {
                        if (!isRunningMaintenance)
                        {
                            isRunningMaintenance = true;
                            continueMaintenance = true;
                        }
                    }
                }
                if (continueMaintenance)
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerStarting, this.config.MeshId));
                        TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                            record, this, null);
                    }

                    TimeoutHelper timeoutHelper = new TimeoutHelper(config.MaintainerTimeout);
                    try
                    {
                        maintainerTimer.Cancel();                               // No reconnect until after connect has succeeded

                        int currentlyConnected = neighborManager.ConnectedNeighborCount;
                        if (currentlyConnected != config.IdealNeighbors)        // Already at ideal no work to do
                        {
                            using (IConnectAlgorithms connectAlgorithm = (IConnectAlgorithms)new TConnectAlgorithms())
                            {
                                connectAlgorithm.Initialize(this, config, config.IdealNeighbors, referralCache);
                                if (currentlyConnected > config.IdealNeighbors)
                                {
                                    if (DiagnosticUtility.ShouldTraceInformation)
                                    {
                                        PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerPruneMode, this.config.MeshId));
                                        TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                                            record, this, null);
                                    }
                                    connectAlgorithm.PruneConnections();
                                }

                                // During Prune some other neighbor may have gone away which leaves us below Ideal
                                // So try to reconnect
                                currentlyConnected = neighborManager.ConnectedNeighborCount;
                                if (currentlyConnected < config.IdealNeighbors)
                                {
                                    if (referralCache.Count == 0)
                                    {
                                        ReadOnlyCollection<PeerNodeAddress> addresses = ResolveNewAddresses(timeoutHelper.RemainingTime(), true);
                                        connectAlgorithm.UpdateEndpointsCollection(addresses);
                                    }
                                    if (DiagnosticUtility.ShouldTraceInformation)
                                    {
                                        PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerConnectMode, this.config.MeshId));
                                        TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                                            record, this, null);
                                    }
                                    connectAlgorithm.Connect(timeoutHelper.RemainingTime());
                                }
                            }
                        }
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e)) throw;
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        // We ---- all non Fatal exceptions because this is a worker thread, with no user code waiting
                    }
                    finally
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord("Maintainer cycle finish");
                            TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                                record, this, null);
                        }
                    }
                    ResetMaintenance();
                }
            }
        }

        void OnMaintainerTimer(object state)
        {
            ActionItem.Schedule(new Action<object>(MaintainConnections), null);
        }

        public void RefreshConnection()
        {
            // Are we open and is any maintenance activity occuring
            if (isOpen)
            {
                bool continueMaintenance = false;
                if (!isRunningMaintenance)
                {
                    lock (ThisLock)
                    {
                        if (!isRunningMaintenance)
                        {
                            isRunningMaintenance = true;
                            continueMaintenance = true;
                        }
                    }
                }
                if (continueMaintenance)
                {
                    try
                    {
                        TimeoutHelper timeoutHelper = new TimeoutHelper(config.MaintainerTimeout);
                        maintainerTimer.Cancel();                   // No maintainer until after connect has succeeded

                        using (IConnectAlgorithms connectAlgorithm = (IConnectAlgorithms)new TConnectAlgorithms())
                        {
                            // Always go to the resolver for RefreshConnection
                            ReadOnlyCollection<PeerNodeAddress> addresses = ResolveNewAddresses(timeoutHelper.RemainingTime(), true);
                            connectAlgorithm.Initialize(this, config, neighborManager.ConnectedNeighborCount + 1, new Dictionary<EndpointAddress, Referral>());
                            if (addresses.Count > 0)
                            {
                                if (isOpen)
                                {
                                    connectAlgorithm.UpdateEndpointsCollection(addresses);
                                    connectAlgorithm.Connect(timeoutHelper.RemainingTime());
                                }
                            }
                        }
                    }
                    finally
                    {
                        ResetMaintenance();
                    }
                }
            }
        }

        void ResetMaintenance()
        {
            if (isOpen)
            {
                lock (ThisLock)
                {
                    if (isOpen)
                    {
                        try
                        {
                            maintainerTimer.Set(config.MaintainerInterval);                 // No reconnect until after connect has succeeded
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e)) throw;
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                            // We ---- all non Fatal exceptions because this is a worker thread, with no user code waiting
                        }
                    }
                }
            }
            lock (ThisLock)
            {
                isRunningMaintenance = false;
            }
        }

        public void ScheduleConnect(ConnectCallback connectCallback)
        {
            this.connectCallback = connectCallback;
            ActionItem.Schedule(new Action<object>(InitialConnection), null);
        }

        public Referral[] GetReferrals()
        {
            Fx.Assert(null != config.Resolver, "");

            Referral[] referrals = null;
            bool canShareReferrals = false;
            try
            {
                canShareReferrals = config.Resolver.CanShareReferrals;
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e)) throw;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(SR.GetString(SR.ResolverException), e);
            }

            if (canShareReferrals)
            {
                List<IPeerNeighbor> neighbors = this.neighborManager.GetConnectedNeighbors();
                int count = Math.Min(this.config.MaxReferrals, neighbors.Count);
                referrals = new Referral[count];
                for (int i = 0; i < count; i++)
                {
                    referrals[i] = new Referral(neighbors[i].NodeId, neighbors[i].ListenAddress);
                }
            }
            else
            {
                referrals = new Referral[0];
            }
            return referrals;
        }

        // Notify whoever is interested in NeighborClosed, and start the Maintenance algorithms at threshold
        public virtual void OnNeighborClosed(IPeerNeighbor neighbor)
        {
            if (isOpen)
            {
                lock (ThisLock)
                {
                    if (neighbor != null && neighbor.ListenAddress != null)
                    {
                        EndpointAddress key = neighbor.ListenAddress.EndpointAddress;
                    }

                    if (isOpen && !isRunningMaintenance && neighborManager.ConnectedNeighborCount < config.MinNeighbors)
                    {
                        maintainerTimer.Set(0);
                    }
                }
            }

            NeighborClosedHandler handler = NeighborClosed;
            if (handler != null)
            {
                handler(neighbor);
            }
        }

        public virtual void OnNeighborConnected(IPeerNeighbor neighbor)
        {
            NeighborConnectedHandler handler = NeighborConnected;
            if (handler != null)
            {
                handler(neighbor);
            }
        }

        [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
        public void Open()
        {
            traceRecord = new PeerNodeTraceRecord(config.NodeId);

            if (isRunningMaintenance)
            {
                return;
            }
            lock (ThisLock)
            {
                SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
                isOpen = true;
            }
        }

        // Get some addresses and make sure they are not in my neighborlist
        ReadOnlyCollection<PeerNodeAddress> ResolveNewAddresses(TimeSpan timeLeft, bool retryResolve)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeLeft);
            Dictionary<string, PeerNodeAddress> alreadySeen = new Dictionary<string, PeerNodeAddress>();
            List<PeerNodeAddress> reply = new List<PeerNodeAddress>();

            // Is this address me
            PeerNodeAddress lclNodeAddress = config.GetListenAddress(true);
            alreadySeen.Add(lclNodeAddress.ServicePath, lclNodeAddress);

            // Maximum of 2 resolves to get new addresses - if the resolver doesn't return us good addresses in 2 goes (8 randomly returned addresses)
            // it is probably messing with us
            int nresolves = (retryResolve) ? 2 : 1;
            if (DiagnosticUtility.ShouldTraceInformation)
            {
                PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord("Resolving");
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                    record, this, null);
            }

            for (int i = 0; i < nresolves && reply.Count < config.MaxResolveAddresses && isOpen && timeoutHelper.RemainingTime() > TimeSpan.Zero; i++)
            {
                ReadOnlyCollection<PeerNodeAddress> addresses;
                try
                {
                    addresses = config.Resolver.Resolve(config.MeshId, config.MaxResolveAddresses, timeoutHelper.RemainingTime());
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e)) throw;
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord("Resolve exception " + e.Message);
                        TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity),
                            record, this, null);
                    }

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.ResolverException), e));
                }

                if (addresses != null)
                {
                    foreach (PeerNodeAddress address in addresses)
                    {
                        if (!alreadySeen.ContainsKey(address.ServicePath))
                        {
                            alreadySeen.Add(address.ServicePath, address);
                            if (((IPeerMaintainer)this).FindDuplicateNeighbor(address) == null)
                            {
                                reply.Add(address);
                            }
                        }
                    }
                }
            }
            return (new ReadOnlyCollection<PeerNodeAddress>(reply));
        }

        // interface IPeerMaintainer implementation
        public event NeighborClosedHandler NeighborClosed;
        public event NeighborConnectedHandler NeighborConnected;
        public event MaintainerClosedHandler MaintainerClosed;

        void IPeerMaintainer.CloseNeighbor(IPeerNeighbor neighbor, PeerCloseReason closeReason)
        {
            neighborManager.CloseNeighbor(neighbor, closeReason, PeerCloseInitiator.LocalNode);
        }

        IPeerNeighbor IPeerMaintainer.FindDuplicateNeighbor(PeerNodeAddress address)
        {
            return neighborManager.FindDuplicateNeighbor(address);
        }

        PeerNodeAddress IPeerMaintainer.GetListenAddress()
        {
            return config.GetListenAddress(true);
        }

        IPeerNeighbor IPeerMaintainer.GetLeastUsefulNeighbor()
        {
            IPeerNeighbor leastUsefulNeighbor = null;
            uint minUtility = UInt32.MaxValue;

            foreach (IPeerNeighbor neighbor in this.neighborManager.GetConnectedNeighbors())
            {
                UtilityExtension utilityExtension = neighbor.Extensions.Find<UtilityExtension>();
                if (utilityExtension != null && utilityExtension.IsAccurate && utilityExtension.LinkUtility < minUtility && !neighbor.IsClosing)
                {
                    minUtility = utilityExtension.LinkUtility;
                    leastUsefulNeighbor = neighbor;
                }
            }
            return leastUsefulNeighbor;
        }

        IAsyncResult IPeerMaintainer.BeginOpenNeighbor(PeerNodeAddress address, TimeSpan timeout, AsyncCallback callback, object asyncState)
        {
            lock (ThisLock)
            {
                EndpointAddress key = address.EndpointAddress;
                if (referralCache.ContainsKey(key))
                {
                    referralCache.Remove(key);
                }
            }

            return neighborManager.BeginOpenNeighbor(address, timeout, callback, asyncState);
        }

        IPeerNeighbor IPeerMaintainer.EndOpenNeighbor(IAsyncResult result)
        {
            return neighborManager.EndOpenNeighbor(result);
        }

        int IPeerMaintainer.ConnectedNeighborCount
        {
            get { return neighborManager.ConnectedNeighborCount; }
        }

        int IPeerMaintainer.NonClosingNeighborCount
        {
            get { return neighborManager.NonClosingNeighborCount; }
        }

        bool IPeerMaintainer.IsOpen
        {
            get { return isOpen; }
        }

        public void PingConnections()
        {
            neighborManager.PingNeighbors();
        }

        public void PingAndRefresh(object state)
        {
            PingConnections();
            if (this.neighborManager.ConnectedNeighborCount < this.config.IdealNeighbors)
                MaintainConnections(null);
        }

        [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
        void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            if (e.Mode != PowerModes.Resume)
                return;
            if (!isOpen)
                return;
            ActionItem.Schedule(new Action<object>(PingAndRefresh), null);
        }

    }

    partial class PeerMaintainer : PeerMaintainerBase<ConnectAlgorithms>
    {
        public PeerMaintainer(PeerNodeConfig config, PeerNeighborManager neighborManager, PeerFlooder flooder)
            : base(config, neighborManager, flooder)
        {
        }
    }
}