File: CustomPeerResolverService.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 (688 lines) | stat: -rw-r--r-- 24,685 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
677
678
679
680
681
682
683
684
685
686
687
688
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.PeerResolvers
{
    using System;
    using System.Collections.Generic;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Threading;


    [ObsoleteAttribute ("PeerChannel feature is obsolete and will be removed in the future.", false)]
    [ServiceBehavior(UseSynchronizationContext = false, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class CustomPeerResolverService : IPeerResolverContract
    {
        internal enum RegistrationState
        {
            OK, Deleted
        }

        internal class RegistrationEntry
        {
            Guid clientId;
            Guid registrationId;
            string meshId;
            DateTime expires;
            PeerNodeAddress address;
            RegistrationState state;


            public RegistrationEntry(Guid clientId, Guid registrationId, string meshId, DateTime expires, PeerNodeAddress address)
            {
                this.ClientId = clientId;
                this.RegistrationId = registrationId;
                this.MeshId = meshId;
                this.Expires = expires;
                this.Address = address;
                this.State = RegistrationState.OK;
            }

            public Guid ClientId
            {
                get { return clientId; }
                set { clientId = value; }
            }

            public Guid RegistrationId
            {
                get { return registrationId; }
                set { registrationId = value; }
            }

            public string MeshId
            {
                get { return meshId; }
                set { meshId = value; }
            }

            public DateTime Expires
            {
                get { return expires; }
                set { expires = value; }
            }

            public PeerNodeAddress Address
            {
                get { return address; }
                set { address = value; }
            }

            public RegistrationState State
            {
                get { return state; }
                set { state = value; }
            }

        }

        internal class LiteLock
        {
            bool forWrite;
            bool upgraded;
            ReaderWriterLock locker;
            TimeSpan timeout = TimeSpan.FromMinutes(1);
            LockCookie lc;

            LiteLock(ReaderWriterLock locker, bool forWrite)
            {
                this.locker = locker;
                this.forWrite = forWrite;
            }

            public static void Acquire(out LiteLock liteLock, ReaderWriterLock locker)
            {
                Acquire(out liteLock, locker, false);
            }

            public static void Acquire(out LiteLock liteLock, ReaderWriterLock locker, bool forWrite)
            {
                LiteLock theLock = new LiteLock(locker, forWrite);
                try { }
                finally
                {
                    if (forWrite)
                    {
                        locker.AcquireWriterLock(theLock.timeout);
                    }
                    else
                    {
                        locker.AcquireReaderLock(theLock.timeout);
                    }
                    liteLock = theLock;
                }
            }

            public static void Release(LiteLock liteLock)
            {
                if (liteLock == null)
                {
                    return;
                }

                if (liteLock.forWrite)
                {
                    liteLock.locker.ReleaseWriterLock();
                }
                else
                {
                    Fx.Assert(!liteLock.upgraded, "Can't release while upgraded!");
                    liteLock.locker.ReleaseReaderLock();
                }
            }
            public void UpgradeToWriterLock()
            {
                Fx.Assert(!forWrite, "Invalid call to Upgrade!!");
                Fx.Assert(!upgraded, "Already upgraded!");
                try { }
                finally
                {
                    lc = locker.UpgradeToWriterLock(timeout);
                    upgraded = true;
                }
            }
            public void DowngradeFromWriterLock()
            {
                Fx.Assert(!forWrite, "Invalid call to Downgrade!!");
                if (upgraded)
                {
                    locker.DowngradeFromWriterLock(ref lc);
                    upgraded = false;
                }
            }
        }

        internal class MeshEntry
        {
            Dictionary<Guid, RegistrationEntry> entryTable;
            Dictionary<string, RegistrationEntry> service2EntryTable;
            List<RegistrationEntry> entryList;
            ReaderWriterLock gate;

            internal MeshEntry()
            {
                EntryTable = new Dictionary<Guid, RegistrationEntry>();
                Service2EntryTable = new Dictionary<string, RegistrationEntry>();
                EntryList = new List<RegistrationEntry>();
                Gate = new ReaderWriterLock();
            }

            public Dictionary<Guid, RegistrationEntry> EntryTable
            {
                get { return entryTable; }
                set { entryTable = value; }
            }

            public Dictionary<string, RegistrationEntry> Service2EntryTable
            {
                get { return service2EntryTable; }
                set { service2EntryTable = value; }
            }

            public List<RegistrationEntry> EntryList
            {
                get { return entryList; }
                set { entryList = value; }
            }

            public ReaderWriterLock Gate
            {
                get { return gate; }
                set { gate = value; }
            }
        }

        Dictionary<string, MeshEntry> meshId2Entry = new Dictionary<string, MeshEntry>();
        ReaderWriterLock gate;

        TimeSpan timeout = TimeSpan.FromMinutes(1);
        TimeSpan cleanupInterval = TimeSpan.FromMinutes(1);
        TimeSpan refreshInterval = TimeSpan.FromMinutes(10);
        bool controlShape;
        bool isCleaning;
        IOThreadTimer timer;
        object thisLock = new object();
        bool opened;
        TimeSpan LockWait = TimeSpan.FromSeconds(5);

        public CustomPeerResolverService()
        {
            isCleaning = false;
            gate = new ReaderWriterLock();
        }

        public TimeSpan CleanupInterval
        {
            get
            {
                return cleanupInterval;
            }
            set
            {
                if (value < TimeSpan.Zero)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRange0)));
                }

                if (TimeoutHelper.IsTooLarge(value))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
                }

                lock (ThisLock)
                {
                    ThrowIfOpened("Set CleanupInterval");
                    this.cleanupInterval = value;
                }
            }
        }

        public TimeSpan RefreshInterval
        {
            get
            {
                return refreshInterval;
            }
            set
            {
                if (value < TimeSpan.Zero)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRange0)));
                }

                if (TimeoutHelper.IsTooLarge(value))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
                }

                lock (ThisLock)
                {
                    ThrowIfOpened("Set RefreshInterval");
                    this.refreshInterval = value;
                }
            }
        }

        public bool ControlShape
        {
            get
            {
                return this.controlShape;
            }
            set
            {
                lock (ThisLock)
                {
                    ThrowIfOpened("Set ControlShape");
                    this.controlShape = value;
                }
            }
        }

        MeshEntry GetMeshEntry(string meshId) { return GetMeshEntry(meshId, true); }
        MeshEntry GetMeshEntry(string meshId, bool createIfNotExists)
        {
            MeshEntry meshEntry = null;
            LiteLock ll = null;
            try
            {
                LiteLock.Acquire(out ll, gate);
                if (!this.meshId2Entry.TryGetValue(meshId, out meshEntry) && createIfNotExists)
                {
                    meshEntry = new MeshEntry();
                    try
                    {
                        ll.UpgradeToWriterLock();
                        meshId2Entry.Add(meshId, meshEntry);
                    }
                    finally
                    {
                        ll.DowngradeFromWriterLock();
                    }
                }
            }
            finally
            {
                LiteLock.Release(ll);
            }
            Fx.Assert(meshEntry != null || !createIfNotExists, "GetMeshEntry failed to get an entry!");
            return meshEntry;
        }

        public virtual RegisterResponseInfo Register(Guid clientId, string meshId, PeerNodeAddress address)
        {
            Guid registrationId = Guid.NewGuid();
            DateTime expiry = DateTime.UtcNow + RefreshInterval;

            RegistrationEntry entry = null;
            MeshEntry meshEntry = null;

            lock (ThisLock)
            {
                entry = new RegistrationEntry(clientId, registrationId, meshId, expiry, address);
                meshEntry = GetMeshEntry(meshId);
                if (meshEntry.Service2EntryTable.ContainsKey(address.ServicePath))
                    PeerExceptionHelper.ThrowInvalidOperation_DuplicatePeerRegistration(address.ServicePath);
                LiteLock ll = null;

                try
                {
                    // meshEntry.gate can be held by this thread for write if this is coming from update
                    // else MUST not be held at all.
                    if (!meshEntry.Gate.IsWriterLockHeld)
                    {
                        LiteLock.Acquire(out ll, meshEntry.Gate, true);
                    }
                    meshEntry.EntryTable.Add(registrationId, entry);
                    meshEntry.EntryList.Add(entry);
                    meshEntry.Service2EntryTable.Add(address.ServicePath, entry);
                }
                finally
                {
                    if (ll != null)
                        LiteLock.Release(ll);
                }
            }
            return new RegisterResponseInfo(registrationId, RefreshInterval);
        }

        public virtual RegisterResponseInfo Register(RegisterInfo registerInfo)
        {
            if (registerInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("registerInfo", SR.GetString(SR.PeerNullRegistrationInfo));
            }

            ThrowIfClosed("Register");

            if (!registerInfo.HasBody() || String.IsNullOrEmpty(registerInfo.MeshId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("registerInfo", SR.GetString(SR.PeerInvalidMessageBody, registerInfo));
            }
            return Register(registerInfo.ClientId, registerInfo.MeshId, registerInfo.NodeAddress);
        }

        public virtual RegisterResponseInfo Update(UpdateInfo updateInfo)
        {
            if (updateInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("updateInfo", SR.GetString(SR.PeerNullRegistrationInfo));
            }

            ThrowIfClosed("Update");

            if (!updateInfo.HasBody() || String.IsNullOrEmpty(updateInfo.MeshId) || updateInfo.NodeAddress == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("updateInfo", SR.GetString(SR.PeerInvalidMessageBody, updateInfo));
            }

            Guid registrationId = updateInfo.RegistrationId;
            RegistrationEntry entry;

            MeshEntry meshEntry = GetMeshEntry(updateInfo.MeshId);
            LiteLock ll = null;

            //handle cases when Update ----s with Register.
            if (updateInfo.RegistrationId == Guid.Empty || meshEntry == null)
                return Register(updateInfo.ClientId, updateInfo.MeshId, updateInfo.NodeAddress);
            //
            // preserve locking order between ThisLock and the LiteLock.
            lock (ThisLock)
            {
                try
                {
                    LiteLock.Acquire(out ll, meshEntry.Gate);
                    if (!meshEntry.EntryTable.TryGetValue(updateInfo.RegistrationId, out entry))
                    {
                        try
                        {
                            // upgrade to writer lock
                            ll.UpgradeToWriterLock();
                            return Register(updateInfo.ClientId, updateInfo.MeshId, updateInfo.NodeAddress);
                        }
                        finally
                        {
                            ll.DowngradeFromWriterLock();
                        }
                    }
                    lock (entry)
                    {
                        entry.Address = updateInfo.NodeAddress;
                        entry.Expires = DateTime.UtcNow + this.RefreshInterval;
                    }
                }
                finally
                {
                    LiteLock.Release(ll);
                }
            }
            return new RegisterResponseInfo(registrationId, RefreshInterval);
        }

        public virtual ResolveResponseInfo Resolve(ResolveInfo resolveInfo)
        {
            if (resolveInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("resolveInfo", SR.GetString(SR.PeerNullResolveInfo));
            }

            ThrowIfClosed("Resolve");

            if (!resolveInfo.HasBody())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("resolveInfo", SR.GetString(SR.PeerInvalidMessageBody, resolveInfo));
            }

            int currentCount = 0;
            int index = 0;
            int maxEntries = resolveInfo.MaxAddresses;
            ResolveResponseInfo response = new ResolveResponseInfo();
            List<PeerNodeAddress> results = new List<PeerNodeAddress>();
            List<RegistrationEntry> entries = null;
            PeerNodeAddress address;
            RegistrationEntry entry;
            MeshEntry meshEntry = GetMeshEntry(resolveInfo.MeshId, false);
            if (meshEntry != null)
            {
                LiteLock ll = null;
                try
                {
                    LiteLock.Acquire(out ll, meshEntry.Gate);
                    entries = meshEntry.EntryList;
                    if (entries.Count <= maxEntries)
                    {
                        foreach (RegistrationEntry e in entries)
                        {
                            results.Add(e.Address);
                        }
                    }
                    else
                    {
                        Random random = new Random();
                        while (currentCount < maxEntries)
                        {
                            index = random.Next(entries.Count);
                            entry = entries[index];
                            Fx.Assert(entry.State == RegistrationState.OK, "A deleted registration is still around!");
                            address = entry.Address;
                            if (!results.Contains(address))
                                results.Add(address);
                            currentCount++;
                        }
                    }
                }
                finally
                {
                    LiteLock.Release(ll);
                }
            }
            response.Addresses = results.ToArray();
            return response;
        }

        public virtual void Unregister(UnregisterInfo unregisterInfo)
        {
            if (unregisterInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterinfo", SR.GetString(SR.PeerNullRegistrationInfo));
            }

            ThrowIfClosed("Unregister");

            if (!unregisterInfo.HasBody() || String.IsNullOrEmpty(unregisterInfo.MeshId) || unregisterInfo.RegistrationId == Guid.Empty)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterInfo", SR.GetString(SR.PeerInvalidMessageBody, unregisterInfo));
            }

            RegistrationEntry registration = null;
            MeshEntry meshEntry = GetMeshEntry(unregisterInfo.MeshId, false);
            //there could be a ---- that two different threads could be working on the same entry
            //we wont optimize for that case.
            LiteLock ll = null;
            try
            {
                LiteLock.Acquire(out ll, meshEntry.Gate, true);
                if (!meshEntry.EntryTable.TryGetValue(unregisterInfo.RegistrationId, out registration))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("unregisterInfo", SR.GetString(SR.PeerInvalidMessageBody, unregisterInfo));
                meshEntry.EntryTable.Remove(unregisterInfo.RegistrationId);
                meshEntry.EntryList.Remove(registration);
                meshEntry.Service2EntryTable.Remove(registration.Address.ServicePath);
                registration.State = RegistrationState.Deleted;
            }
            finally
            {
                LiteLock.Release(ll);
            }
        }

        public virtual RefreshResponseInfo Refresh(RefreshInfo refreshInfo)
        {
            if (refreshInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("refreshInfo", SR.GetString(SR.PeerNullRefreshInfo));
            }

            ThrowIfClosed("Refresh");

            if (!refreshInfo.HasBody() || String.IsNullOrEmpty(refreshInfo.MeshId) || refreshInfo.RegistrationId == Guid.Empty)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("refreshInfo", SR.GetString(SR.PeerInvalidMessageBody, refreshInfo));
            }
            RefreshResult result = RefreshResult.RegistrationNotFound;
            RegistrationEntry entry = null;
            MeshEntry meshEntry = GetMeshEntry(refreshInfo.MeshId, false);
            LiteLock ll = null;

            if (meshEntry != null)
            {
                try
                {
                    LiteLock.Acquire(out ll, meshEntry.Gate);
                    if (!meshEntry.EntryTable.TryGetValue(refreshInfo.RegistrationId, out entry))
                        return new RefreshResponseInfo(RefreshInterval, result);
                    lock (entry)
                    {
                        if (entry.State == RegistrationState.OK)
                        {
                            entry.Expires = DateTime.UtcNow + RefreshInterval;
                            result = RefreshResult.Success;
                        }
                    }
                }
                finally
                {
                    LiteLock.Release(ll);
                }
            }
            return new RefreshResponseInfo(RefreshInterval, result);
        }

        public virtual ServiceSettingsResponseInfo GetServiceSettings()
        {
            ThrowIfClosed("GetServiceSettings");
            ServiceSettingsResponseInfo info = new ServiceSettingsResponseInfo(this.ControlShape);
            return info;
        }

        public virtual void Open()
        {
            ThrowIfOpened("Open");
            if (this.refreshInterval <= TimeSpan.Zero)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("RefreshInterval", SR.GetString(SR.RefreshIntervalMustBeGreaterThanZero, this.refreshInterval));
            if (this.CleanupInterval <= TimeSpan.Zero)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("CleanupInterval", SR.GetString(SR.CleanupIntervalMustBeGreaterThanZero, this.cleanupInterval));

            //check that we are good to open
            timer = new IOThreadTimer(new Action<object>(CleanupActivity), null, false);
            timer.Set(CleanupInterval);
            opened = true;
        }

        public virtual void Close()
        {
            ThrowIfClosed("Close");
            timer.Cancel();
            opened = false;
        }

        internal virtual void CleanupActivity(object state)
        {
            if (!opened)
                return;

            if (!isCleaning)
            {
                lock (ThisLock)
                {
                    if (!isCleaning)
                    {
                        isCleaning = true;
                        try
                        {
                            MeshEntry meshEntry = null;
                            //acquire a write lock.  from the reader/writer lock can we postpone until no contention?
                            ICollection<string> keys = null;
                            LiteLock ll = null;
                            try
                            {
                                LiteLock.Acquire(out ll, gate);
                                keys = meshId2Entry.Keys;
                            }
                            finally
                            {
                                LiteLock.Release(ll);
                            }
                            foreach (string meshId in keys)
                            {
                                meshEntry = GetMeshEntry(meshId);
                                CleanupMeshEntry(meshEntry);
                            }
                        }
                        finally
                        {
                            isCleaning = false;
                            if (opened)
                                timer.Set(this.CleanupInterval);
                        }
                    }
                }
            }
        }

        //always call this from a readlock
        void CleanupMeshEntry(MeshEntry meshEntry)
        {
            List<Guid> remove = new List<Guid>();
            if (!opened)
                return;
            LiteLock ll = null;
            try
            {
                LiteLock.Acquire(out ll, meshEntry.Gate, true);
                foreach (KeyValuePair<Guid, RegistrationEntry> item in meshEntry.EntryTable)
                {
                    if ((item.Value.Expires <= DateTime.UtcNow) || (item.Value.State == RegistrationState.Deleted))
                    {
                        remove.Add(item.Key);
                        meshEntry.EntryList.Remove(item.Value);
                        meshEntry.Service2EntryTable.Remove(item.Value.Address.ServicePath);
                    }
                }
                foreach (Guid id in remove)
                {
                    meshEntry.EntryTable.Remove(id);
                }
            }
            finally
            {
                LiteLock.Release(ll);
            }
        }

        object ThisLock
        {
            get
            {
                return this.thisLock;
            }
        }
        void ThrowIfOpened(string operation)
        {
            if (opened)
                PeerExceptionHelper.ThrowInvalidOperation_NotValidWhenOpen(operation);
        }
        void ThrowIfClosed(string operation)
        {
            if (!opened)
                PeerExceptionHelper.ThrowInvalidOperation_NotValidWhenClosed(operation);

        }
    }
}