Welcome to mirror list, hosted at ThFree Co, Russian Federation.

lease.cs « remoting « runtime « system « mscorlib « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a0884ce4e522a714f059b2ccc144508c62a085a0 (plain)
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
// ==++==
// 
//   Copyright (c) Microsoft Corporation.  All rights reserved.
// 
// ==--==
//+----------------------------------------------------------------------------
//
// Microsoft Windows
// File:        Lease.cs
//
// Contents:    Lease class
//
// History:     1/5/00   <EMAIL>[....]</EMAIL>        Created
//
//+----------------------------------------------------------------------------

namespace System.Runtime.Remoting.Lifetime
{
    using System;
    using System.Security;
    using System.Security.Permissions;
    using System.Collections;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;
    using System.Runtime.Remoting.Proxies;
    using System.Globalization;

    internal class Lease : MarshalByRefObject, ILease
    {
        internal int id = 0;
        
        // Lease Time
        internal DateTime leaseTime;
        internal TimeSpan initialLeaseTime;
        
        // Renewal Policies
        internal TimeSpan renewOnCallTime;
        internal TimeSpan sponsorshipTimeout;

        // Sponsors
        internal Hashtable sponsorTable;
        internal int sponsorCallThread;

        // Links to leasemanager and managed object
        internal LeaseManager leaseManager;
        internal MarshalByRefObject managedObject;

        // State
        internal LeaseState state;

        internal static volatile int nextId = 0;        


        internal Lease(TimeSpan initialLeaseTime,
                       TimeSpan renewOnCallTime,                       
                       TimeSpan sponsorshipTimeout,
                       MarshalByRefObject managedObject
                      )
        {
            id = nextId++;
            BCLDebug.Trace("REMOTE", "Lease Constructor ",managedObject," initialLeaseTime "+initialLeaseTime+" renewOnCall "+renewOnCallTime+" sponsorshipTimeout ",sponsorshipTimeout);

            // Set Policy            
            this.renewOnCallTime = renewOnCallTime;
            this.sponsorshipTimeout = sponsorshipTimeout;
            this.initialLeaseTime = initialLeaseTime;
            this.managedObject = managedObject;

            //Add lease to leaseManager
            leaseManager = LeaseManager.GetLeaseManager();

            // Initialize tables
            sponsorTable = new Hashtable(10);
            state = LeaseState.Initial;
        }

        internal void ActivateLease()
        {
            // Set leaseTime
            leaseTime = DateTime.UtcNow.Add(initialLeaseTime);
            state = LeaseState.Active;
            leaseManager.ActivateLease(this);
        }

        // Override MarshalByRefObject InitializeLifetimeService
        // Don't want a lease on a lease therefore returns null
        [System.Security.SecurityCritical]  // auto-generated
        public override Object InitializeLifetimeService()
        {
            BCLDebug.Trace("REMOTE", "Lease ",id," InitializeLifetimeService, lease Marshalled");
            return null;
        }

        // ILease Property and Methods

        public TimeSpan RenewOnCallTime
        {
            [System.Security.SecurityCritical]  // auto-generated
            get { return renewOnCallTime; }
            [System.Security.SecurityCritical]  // auto-generated
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
            set
            {
                if (state == LeaseState.Initial)
                {
                    renewOnCallTime = value;
                    BCLDebug.Trace("REMOTE", "Lease Set RenewOnCallProperty ",managedObject," "+renewOnCallTime);
                }
                else
                    throw new RemotingException(Environment.GetResourceString("Remoting_Lifetime_InitialStateRenewOnCall", ((Enum)state).ToString()));                    
            }
        }

        public TimeSpan SponsorshipTimeout
        {
            [System.Security.SecurityCritical]  // auto-generated
            get { return sponsorshipTimeout; }
            [System.Security.SecurityCritical]  // auto-generated
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
            set
            {
                if (state == LeaseState.Initial)
                {
                    sponsorshipTimeout = value;
                    BCLDebug.Trace("REMOTE", "Lease Set SponsorshipTimeout Property ",managedObject," "+sponsorshipTimeout);                    
                }
                else
                    throw new RemotingException(Environment.GetResourceString("Remoting_Lifetime_InitialStateSponsorshipTimeout", ((Enum)state).ToString()));                                        
            }
        }

        public TimeSpan InitialLeaseTime
        {
            [System.Security.SecurityCritical]  // auto-generated
            get { return initialLeaseTime; }

            [System.Security.SecurityCritical]  // auto-generated
            [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
            set
            {
                if (state == LeaseState.Initial)
                {
                    initialLeaseTime = value;
                    if (TimeSpan.Zero.CompareTo(value) >= 0)
                        state = LeaseState.Null;
                    BCLDebug.Trace("REMOTE", "Lease Set InitialLeaseTime Property ",managedObject,"  "+InitialLeaseTime+", current state "+((Enum)state).ToString());                                                            
                }
                else
                    throw new RemotingException(Environment.GetResourceString("Remoting_Lifetime_InitialStateInitialLeaseTime", ((Enum)state).ToString()));                                                            
            }
        }

        public TimeSpan CurrentLeaseTime
        {
            [System.Security.SecurityCritical]  // auto-generated
            get { return leaseTime.Subtract(DateTime.UtcNow); }
        }

        public LeaseState CurrentState
        {
            [System.Security.SecurityCritical]  // auto-generated
            get { return state;}
        }        


        [System.Security.SecurityCritical]  // auto-generated
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
        public void Register(ISponsor obj)
        {
            Register(obj, TimeSpan.Zero);
        }
        
        [System.Security.SecurityCritical]  // auto-generated
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
        public void Register(ISponsor obj, TimeSpan renewalTime)
        {
            lock(this)
            {
                BCLDebug.Trace("REMOTE", "Lease "+id+" Register Sponsor  renewalTime ",renewalTime," state ",((Enum)state).ToString());
                if (state == LeaseState.Expired || sponsorshipTimeout == TimeSpan.Zero)
                    return;

                Object sponsorId = GetSponsorId(obj);
                lock(sponsorTable)
                {
                    if (renewalTime > TimeSpan.Zero)
                        AddTime(renewalTime);
                    if (!sponsorTable.ContainsKey(sponsorId))
                    {
                        // Place in tables
                        sponsorTable[sponsorId] = new SponsorStateInfo(renewalTime, SponsorState.Initial);
                    }
                }
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
        public void Unregister(ISponsor sponsor)
        {
            lock(this)
            {
                BCLDebug.Trace("REMOTE", "Lease",id," Unregister  state ",((Enum)state).ToString());
                if (state == LeaseState.Expired)
                    return;

                Object sponsorId = GetSponsorId(sponsor);
                lock(sponsorTable)
                {
                    if (sponsorId != null)
                    {
                        leaseManager.DeleteSponsor(sponsorId);                
                        SponsorStateInfo sponsorStateInfo = (SponsorStateInfo)sponsorTable[sponsorId];
                        sponsorTable.Remove(sponsorId);
                    }
                }
            }
        }

        // Get the local representative of the sponsor to prevent a remote access when placing
        // in a hash table.
        [System.Security.SecurityCritical]  // auto-generated
        private Object GetSponsorId(ISponsor obj)
        {
            Object sponsorId = null;
            if (obj != null)
            {
                if (RemotingServices.IsTransparentProxy(obj))
                    sponsorId = RemotingServices.GetRealProxy(obj);
                else
                    sponsorId = obj;
            }
            return sponsorId;
        }

        // Convert from the local representative of the sponsor to either the MarshalByRefObject or local object
        [System.Security.SecurityCritical]  // auto-generated
        private ISponsor GetSponsorFromId(Object sponsorId)
        {
            Object sponsor = null;
            RealProxy rp = sponsorId as RealProxy;
            if (null != rp)
                sponsor = rp.GetTransparentProxy();
            else
                sponsor = sponsorId;
            return (ISponsor)sponsor;
        }
        
        [System.Security.SecurityCritical]  // auto-generated
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
        public TimeSpan Renew(TimeSpan renewalTime)
        {
            return RenewInternal(renewalTime);
        }

        // We will call this internally within the server domain
        internal TimeSpan RenewInternal(TimeSpan renewalTime)
        {
            lock(this)
            {
                BCLDebug.Trace("REMOTE","Lease ",id," Renew ",renewalTime," state ",((Enum)state).ToString());
                if (state == LeaseState.Expired)
                    return TimeSpan.Zero;
                AddTime(renewalTime);
                return leaseTime.Subtract(DateTime.UtcNow);
            }
        }

        // Used for a lease which has been created, but will not be used
        internal void Remove()
        {
            BCLDebug.Trace("REMOTE","Lease ",id," Remove state ",((Enum)state).ToString());
            if (state == LeaseState.Expired)
                return;
            state = LeaseState.Expired;            
            leaseManager.DeleteLease(this);
        }

        [System.Security.SecurityCritical]  // auto-generated
        internal void Cancel()
        {
            lock(this)
            {                        
                BCLDebug.Trace("REMOTE","Lease ",id," Cancel Managed Object ",managedObject," state ",((Enum)state).ToString());

                if (state == LeaseState.Expired)
                    return;

                Remove();
                // Disconnect the object ... 
                // We use the internal version of Disconnect passing "false"
                // for the bResetURI flag. This allows the object to keep its 
                // old URI in case its lease gets reactivated later.
                RemotingServices.Disconnect(managedObject, false);

                // Disconnect the lease for the object.
                RemotingServices.Disconnect(this);
            }
        }



#if _DEBUG
        ~Lease()
        {
            BCLDebug.Trace("REMOTE","Lease ",id," Finalize");
        }
#endif

        internal void RenewOnCall()
        {
            lock(this)
            {
                //BCLDebug.Trace("REMOTE","Lease ",id," RenewOnCall state ",((Enum)state).ToString());
                if (state == LeaseState.Initial || state == LeaseState.Expired)
                    return;            
                AddTime(renewOnCallTime);
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        internal void LeaseExpired(DateTime now)
        {
            lock(this)
            {
                BCLDebug.Trace("REMOTE","Lease ",id," LeaseExpired state ",((Enum)state).ToString());
                if (state == LeaseState.Expired)
                    return;

                // There is a small window between the time the leaseManager
                // thread examines all the leases and tests for expiry and 
                // when an indivisual lease is locked for expiry. The object 
                // could get marshal-ed in this time which would reset its lease
                // Therefore we check again to see if we should indeed proceed
                // with the expire code (using the same value of 'now' as used
                // by the leaseManager thread)
                if (leaseTime.CompareTo(now) < 0)
                    ProcessNextSponsor();
            }
        }

        internal delegate TimeSpan AsyncRenewal(ILease lease);
        
        [System.Security.SecurityCritical]  // auto-generated
        internal void SponsorCall(ISponsor sponsor)
        {
            BCLDebug.Trace("REMOTE","Lease ",id," SponsorCall state ",((Enum)state).ToString());
            bool exceptionOccurred = false;
            if (state == LeaseState.Expired)
                return;

            lock(sponsorTable)
            {
                try
                {
                    Object sponsorId = GetSponsorId(sponsor);            
                    sponsorCallThread = Thread.CurrentThread.GetHashCode();
                    AsyncRenewal ar = new AsyncRenewal(sponsor.Renewal);
                    SponsorStateInfo sponsorStateInfo = (SponsorStateInfo)sponsorTable[sponsorId];            
                    sponsorStateInfo.sponsorState = SponsorState.Waiting;

                    // The first parameter should be the lease we are trying to renew.
                    IAsyncResult iar = ar.BeginInvoke(this, new AsyncCallback(this.SponsorCallback), null);
                    if ((sponsorStateInfo.sponsorState == SponsorState.Waiting) && (state != LeaseState.Expired))
                    {
                        //   Even if we get here, the operation could still complete before
                        //   we call the the line below. This seems to be a ----.
                        
                        // Sponsor could have completed before statement is reached, so only execute
                        // if the sponsor state is still waiting
                        leaseManager.RegisterSponsorCall(this, sponsorId, sponsorshipTimeout);
                    }
                    sponsorCallThread = 0;
                }catch(Exception)
                {
                    // Sponsor not avaiable
                    exceptionOccurred = true;

                    sponsorCallThread = 0;
                }
            }

            if (exceptionOccurred)
            {
                BCLDebug.Trace("REMOTE","Lease ",id," SponsorCall Sponsor Exception ");
                Unregister(sponsor);
                ProcessNextSponsor();
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        internal void SponsorTimeout(Object sponsorId)
        {
            lock (this)
            {
                if (!sponsorTable.ContainsKey(sponsorId))
                    return;
                lock(sponsorTable)
                {
                    SponsorStateInfo sponsorStateInfo = (SponsorStateInfo)sponsorTable[sponsorId];
                    BCLDebug.Trace("REMOTE","Lease ",id," SponsorTimeout  sponsorState ",((Enum)sponsorStateInfo.sponsorState).ToString());
                    if (sponsorStateInfo.sponsorState == SponsorState.Waiting)
                    {
                        Unregister(GetSponsorFromId(sponsorId));
                        ProcessNextSponsor();
                    }
                }
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        private void ProcessNextSponsor()
        {
            BCLDebug.Trace("REMOTE","Lease ",id," ProcessNextSponsor");

            Object largestSponsor = null;
            TimeSpan largestRenewalTime = TimeSpan.Zero;
            
            
            lock(sponsorTable)
            {
                IDictionaryEnumerator e = sponsorTable.GetEnumerator();
                // Find sponsor with largest previous renewal value
                while(e.MoveNext())
                {
                    Object sponsorId = e.Key;
                    SponsorStateInfo sponsorStateInfo = (SponsorStateInfo)e.Value;
                    if ((sponsorStateInfo.sponsorState == SponsorState.Initial) && (largestRenewalTime == TimeSpan.Zero))
                    {
                        largestRenewalTime = sponsorStateInfo.renewalTime;
                        largestSponsor = sponsorId;                        
                    }
                    else if (sponsorStateInfo.renewalTime > largestRenewalTime)
                    {
                        largestRenewalTime = sponsorStateInfo.renewalTime;
                        largestSponsor = sponsorId;
                    }
                }
            }

            if (largestSponsor != null)
                SponsorCall(GetSponsorFromId(largestSponsor));
            else
            {
                // No more sponsors to try, Cancel
                BCLDebug.Trace("REMOTE","Lease ",id," ProcessNextSponsor no more sponsors");                
                Cancel();
            }
        }


        // This gets called when we explicitly transfer the call back from the 
        // called function to a threadpool thread.
        [System.Security.SecurityCritical]  // auto-generated
        internal void SponsorCallback(Object obj)
        {
            SponsorCallback((IAsyncResult)obj);
        }

        // On another thread
        [System.Security.SecurityCritical]  // auto-generated
        internal void SponsorCallback(IAsyncResult iar)
        {
            BCLDebug.Trace("REMOTE","Lease ",id," SponsorCallback IAsyncResult ",iar," state ",((Enum)state).ToString());
            if (state == LeaseState.Expired)
            {
                return;
            }

            int thisThread = Thread.CurrentThread.GetHashCode();
            if (thisThread == sponsorCallThread)
            {
                // Looks like something went wrong and the thread that
                // did the AsyncRenewal::BeginInvoke is executing the callback
                // We will queue the work to the thread pool (otherwise there
                // is a possibility of stack overflow if all sponsors are down)
                WaitCallback threadFunc = new WaitCallback(this.SponsorCallback);
                ThreadPool.QueueUserWorkItem(threadFunc, iar);
                return;
            }

            AsyncResult asyncResult = (AsyncResult)iar;
            AsyncRenewal ar = (AsyncRenewal)asyncResult.AsyncDelegate;
            ISponsor sponsor = (ISponsor)ar.Target;
            SponsorStateInfo sponsorStateInfo = null;
            if (iar.IsCompleted)
            {
                // Sponsor came back with renewal
                BCLDebug.Trace("REMOTE","Lease ",id," SponsorCallback sponsor completed");
                bool exceptionOccurred = false;
                TimeSpan renewalTime = TimeSpan.Zero;
                try
                {
                    renewalTime = (TimeSpan)ar.EndInvoke(iar);
                }catch(Exception)
                {
                    // Sponsor not avaiable
                    exceptionOccurred = true;
                }
                if (exceptionOccurred)
                {
                    BCLDebug.Trace("REMOTE","Lease ",id," SponsorCallback Sponsor Exception ");
                    Unregister(sponsor);
                    ProcessNextSponsor();
                }
                else
                {
                    Object sponsorId = GetSponsorId(sponsor);
                    lock(sponsorTable)
                    {
                        if (sponsorTable.ContainsKey(sponsorId))
                        {
                            sponsorStateInfo = (SponsorStateInfo)sponsorTable[sponsorId];
                            sponsorStateInfo.sponsorState = SponsorState.Completed;
                            sponsorStateInfo.renewalTime = renewalTime;
                        }
                        else
                        {
                            // Sponsor was deleted, possibly from a sponsor time out
                        }
                    }

                    if (sponsorStateInfo == null)
                    {
                        // Sponsor was deleted
                        ProcessNextSponsor();
                    }
                    else if (sponsorStateInfo.renewalTime == TimeSpan.Zero)
                    {
                        BCLDebug.Trace("REMOTE","Lease ",id," SponsorCallback sponsor did not renew ");                                            
                        Unregister(sponsor);
                        ProcessNextSponsor();
                    }
                    else
                        RenewInternal(sponsorStateInfo.renewalTime);
                }
            }
            else
            {
                // Sponsor timed out
                // Note time outs should be handled by the LeaseManager
                BCLDebug.Trace("REMOTE","Lease ",id," SponsorCallback sponsor did not complete, timed out");
                Unregister(sponsor);                    
                ProcessNextSponsor();
            }
        }

        

        private void AddTime(TimeSpan renewalSpan)
        {
            if (state == LeaseState.Expired)
                return;

            DateTime now = DateTime.UtcNow;
            DateTime oldLeaseTime = leaseTime;
            DateTime renewTime = now.Add(renewalSpan);
            if (leaseTime.CompareTo(renewTime) < 0)
            {
                leaseManager.ChangedLeaseTime(this, renewTime);
                leaseTime = renewTime;
                state = LeaseState.Active;
            }
            //BCLDebug.Trace("REMOTE","Lease ",id," AddTime renewalSpan ",renewalSpan," current Time ",now," old leaseTime ",oldLeaseTime," new leaseTime ",leaseTime," state ",((Enum)state).ToString());            
        }



        [Serializable]
        internal enum SponsorState
        {
            Initial = 0,
            Waiting = 1,
            Completed = 2
        }

        internal sealed class SponsorStateInfo
        {
            internal TimeSpan renewalTime;
            internal SponsorState sponsorState;

            internal SponsorStateInfo(TimeSpan renewalTime, SponsorState sponsorState)
            {
                this.renewalTime = renewalTime;
                this.sponsorState = sponsorState;
            }
        }
    }

    internal class LeaseSink : IMessageSink
    {
        Lease lease = null;
        IMessageSink nextSink = null;

        public LeaseSink(Lease lease, IMessageSink nextSink)
        {
            this.lease = lease;
            this.nextSink = nextSink;
        }
        
        //IMessageSink methods
        [System.Security.SecurityCritical]  // auto-generated
        public IMessage SyncProcessMessage(IMessage msg)
        {
            //BCLDebug.Trace("REMOTE","Lease ",id," SyncProcessMessage");
            lease.RenewOnCall();
            return nextSink.SyncProcessMessage(msg);
        }

        [System.Security.SecurityCritical]  // auto-generated
        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            //BCLDebug.Trace("REMOTE","Lease ",id," AsyncProcessMessage");
            lease.RenewOnCall();
            return nextSink.AsyncProcessMessage(msg, replySink);        
        }

        public IMessageSink NextSink
        {
            [System.Security.SecurityCritical]  // auto-generated
            get
            {
                //BCLDebug.Trace("REMOTE","Lease ",id," NextSink");        
                return nextSink;
            }
        }
    }
}