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
|
// **********************************************************************
//
// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
namespace Ice
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
internal static extern bool
SetConsoleCtrlHandler(CtrlCEventHandler eh, [MarshalAsAttribute(UnmanagedType.Bool)]bool add);
}
/// <summary>
/// The signal policy for Ice.Application signal handling.
/// </summary>
public enum SignalPolicy
{
/// <summary>
/// If a signal is received, Ice.Application reacts to the signal
/// by calling Communicator.destroy or Communicator.shutdown,
/// or by calling a custom shutdown hook installed by the application.
/// </summary>
HandleSignals,
/// <summary>
/// Any signal that is received is not intercepted and takes the default action.
/// </summary>
NoSignalHandling
}
/// <summary>
/// Utility base class that makes it easy to correctly initialize and finalize
/// the Ice run time, as well as handle signals. Unless the application specifies
/// a logger, Application installs a per-process logger that logs to the standard
/// error output.
/// Applications must create a derived class that implements the run method.
/// A program can contain only one instance of this class.
/// </summary>
public abstract class Application
{
/// <summary>
/// Called once the communicator has been initialized. The derived class must
/// implement run, which is the application's starting method.
/// </summary>
/// <param name="args">The argument vector for the application. Application
/// scans the argument vector passed to main for options that are
/// specific to the Ice run time and removes them; therefore, the vector passed
/// to run is free from Ice-related options and contains only options
/// and arguments that are application-specific.</param>
/// <returns>The run method should return zero for successful termination, and
/// non-zero otherwise. Application.main returns the value returned by run.</returns>
public abstract int run(string[] args);
/// <summary>
/// Override this method to provide a custom application interrupt
/// hook. You must call callbackOnInterrupt for this method
/// to be called. Note that the interruptCallback can be called
/// concurrently with any other thread (including main) in your
/// application--take appropriate concurrency precautions.
/// </summary>
/// <param name="sig">The cause of the interrupt.</param>
public virtual void interruptCallback(int sig)
{
}
/// <summary>
/// Initializes an instance that handles signals according to the signal policy.
/// If not signal policy is provided the default SinalPolicy.NoSignalHandling
/// will be used, which calls Communicator.shutdown if a signal is received.
/// </summary>
/// <param name="signalPolicy">Determines how to respond to signals.</param>
public Application(SignalPolicy signalPolicy = SignalPolicy.NoSignalHandling)
{
}
/// <summary>
/// The application must call main after it has
/// instantiated the derived class. main creates
/// a communicator, establishes the specified signal policy, and,
/// once run returns, destroys the communicator.
/// The method prints an error message for any exception that propagates
/// out of run and ensures that the communicator is
/// destroyed correctly even if run completes abnormally.
/// </summary>
/// <param name="args">The arguments for the application (as passed to Main(string[])
/// by the operating system.</param>
/// <returns>The value returned by run. If run terminates with an exception,
/// the return value is non-zero.</returns>
public int main(string[] args)
{
return main(args, new InitializationData());
}
/// <summary>
/// The application must call main after it has
/// instantiated the derived class. main creates
/// a communicator, establishes the specified signal policy, and,
/// once run returns, destroys the communicator.
/// The method prints an error message for any exception that propagates
/// out of run and ensures that the communicator is
/// destroyed correctly even if run completes abnormally.
/// </summary>
/// <param name="args">The arguments for the application (as passed to Main(string[])
/// by the operating system.</param>
/// <param name="configFile">The configuration file with which to initialize
/// Ice properties.</param>
/// <returns>The value returned by run. If run terminates with an exception,
/// the return value is non-zero.</returns>
public int main(string[] args, string configFile)
{
if(Util.getProcessLogger() is ConsoleLoggerI)
{
Util.setProcessLogger(new ConsoleLoggerI(iceAppName));
}
InitializationData initData = new InitializationData();
if(configFile != null)
{
try
{
initData.properties = Util.createProperties();
initData.properties.load(configFile);
}
catch(Ice.Exception ex)
{
Util.getProcessLogger().error(ex.ToString());
return 1;
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("unknown exception:\n" + ex);
return 1;
}
}
return main(args, initData);
}
/// <summary>
/// The application must call main after it has
/// instantiated the derived class. main creates
/// a communicator, establishes the specified signal policy, and,
/// once run returns, destroys the communicator.
/// The method prints an error message for any exception that propagates
/// out of run and ensures that the communicator is
/// destroyed correctly even if run completes abnormally.
/// </summary>
/// <param name="args">The arguments for the application (as passed to Main(string[])
/// by the operating system.</param>
/// <param name="initializationData">Additional data used to initialize the communicator.</param>
/// <returns>The value returned by run. If run terminates with an exception,
/// the return value is non-zero.</returns>
public int main(string[] args, InitializationData initializationData)
{
if(Util.getProcessLogger() is ConsoleLoggerI)
{
Util.setProcessLogger(new ConsoleLoggerI(iceAppName));
}
if(iceCommunicator != null)
{
Util.getProcessLogger().error("only one instance of the Application class can be used");
return 1;
}
//
// We parse the properties here to extract Ice.ProgramName.
//
InitializationData initData;
if(initializationData != null)
{
initData = (InitializationData)initializationData.Clone();
}
else
{
initData = new InitializationData();
}
try
{
initData.properties = Util.createProperties(ref args, initData.properties);
}
catch(Ice.Exception ex)
{
Util.getProcessLogger().error(ex.ToString());
return 1;
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("unknown exception:\n" + ex);
return 1;
}
iceAppName = initData.properties.getPropertyWithDefault("Ice.ProgramName", iceAppName);
iceNohup = initData.properties.getPropertyAsInt("Ice.Nohup") > 0;
_application = this;
int status;
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
_signals = new WindowsSignals();
_signals.register(_handler);
status = doMain(args, initData);
_signals.destroy();
_signals = null;
}
else
{
status = doMain(args, initData);
}
return status;
}
/// <summary>
/// Returns the application name (which is also the value of Ice.ProgramName.
/// This method is useful mainly for error messages that
/// include the application name. Because appName is a static method, it is available from anywhere
/// in the program.
/// </summary>
/// <returns>The name of the application.</returns>
public static string appName()
{
return iceAppName;
}
/// <summary>
/// Returns the communicator for the application. Because communicator is a static method,
/// it permits access to the communicator from anywhere in the program. Note that, as a consequence,
/// you cannot have more than one instance of Application in a program.
/// </summary>
/// <returns>The communicator for the application.</returns>
public static Communicator communicator()
{
return iceCommunicator;
}
/// <summary>
/// Instructs Application to call Communicator.destroy on receipt of a signal.
/// This is default signal handling policy established by the default constructor.
/// </summary>
public static void destroyOnInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback == _holdCallback)
{
iceReleased = true;
System.Threading.Monitor.Pulse(iceMutex);
}
_callback = _destroyCallback;
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Instructs Application to call Communicator.shutdown on receipt of a signal.
/// </summary>
public static void shutdownOnInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback == _holdCallback)
{
iceReleased = true;
System.Threading.Monitor.Pulse(iceMutex);
}
_callback = _shutdownCallback;
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Instructs Application to ignore signals.
/// </summary>
public static void ignoreInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback == _holdCallback)
{
iceReleased = true;
System.Threading.Monitor.Pulse(iceMutex);
}
_callback = null;
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Instructs Application to call interruptCallback on receipt of a signal.
/// The derived class can intercept signals by overriding interruptCallback.
/// </summary>
public static void callbackOnInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback == _holdCallback)
{
iceReleased = true;
System.Threading.Monitor.Pulse(iceMutex);
}
_callback = _userCallback;
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Instructs Application to call to hold signals.
/// </summary>
public static void holdInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback != _holdCallback)
{
_previousCallback = _callback;
iceReleased = false;
_callback = _holdCallback;
}
// else, we were already holding signals
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Instructs Application respond to signals. If a signal arrived since the last call
/// to holdInterrupt, it is delivered once you call releaseInterrupt.
/// </summary>
public static void releaseInterrupt()
{
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
lock(iceMutex)
{
if(_callback == _holdCallback)
{
//
// Note that it's very possible no signal is held;
// in this case the callback is just replaced and
// setting iceReleased to true and signalling this
// will do no harm.
//
iceReleased = true;
_callback = _previousCallback;
System.Threading.Monitor.Pulse(iceMutex);
}
// Else nothing to release.
}
}
else
{
Util.getProcessLogger().warning(
"interrupt method called on Application configured to not handle interrupts.");
}
}
/// <summary>
/// Determines whether the application shut down intentionally or was forced to shut down due to a signal.
/// This is useful for logging purposes.
/// </summary>
/// <returns>True if a signal caused the communicator to shut down; false otherwise.</returns>
public static bool interrupted()
{
lock(iceMutex)
{
return iceInterrupted;
}
}
protected virtual int doMain(string[] args, InitializationData initData)
{
int status = 0;
try
{
//
// If the process logger is the default logger, we replace it with a
// a logger which is using the program name for the prefix.
//
if(initData.properties.getProperty("Ice.ProgramName").Length > 0 &&
Util.getProcessLogger() is ConsoleLoggerI)
{
Util.setProcessLogger(new ConsoleLoggerI(initData.properties.getProperty("Ice.ProgramName")));
}
iceCommunicator = Util.initialize(ref args, initData);
iceDestroyed = false;
//
// The default is to destroy when a signal is received.
//
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
destroyOnInterrupt();
}
status = run(args);
}
catch(Ice.Exception ex)
{
Util.getProcessLogger().error(ex.ToString());
status = 1;
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("unknown exception:\n" + ex);
status = 1;
}
//
// Don't want any new interrupt. And at this point
// (post-run), it would not make sense to release a held
// signal to run shutdown or destroy.
//
if(iceSignalPolicy == SignalPolicy.HandleSignals)
{
ignoreInterrupt();
}
lock(iceMutex)
{
while(iceCallbackInProgress)
{
System.Threading.Monitor.Wait(iceMutex);
}
if(iceDestroyed)
{
iceCommunicator = null;
}
else
{
iceDestroyed = true;
//
// iceCommunicator != null means that it will be destroyed
// next; iceDestroyed == true ensures that any
// remaining callback won't do anything
//
}
_application = null;
}
if(iceCommunicator != null)
{
try
{
iceCommunicator.destroy();
}
catch(Ice.Exception ex)
{
Util.getProcessLogger().error(ex.ToString());
status = 1;
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("unknown exception:\n" + ex);
status = 1;
}
iceCommunicator = null;
}
return status;
}
//
// First-level handler.
//
private static void signalHandler(int sig)
{
Callback callback;
lock(iceMutex)
{
callback = _callback;
}
if(callback != null)
{
try
{
callback(sig);
}
catch(System.Exception)
{
Debug.Assert(false);
}
}
}
//
// The callbacks to be invoked from the handler.
//
private static void holdInterruptCallback(int sig)
{
Callback callback = null;
lock(iceMutex)
{
while(!iceReleased)
{
System.Threading.Monitor.Wait(iceMutex);
}
if(iceDestroyed)
{
//
// Being destroyed by main thread
//
return;
}
callback = _callback;
}
if(callback != null)
{
callback(sig);
}
}
//
// The callbacks to be invoked from the handler.
//
private static void destroyOnInterruptCallback(int sig)
{
lock(iceMutex)
{
if(iceDestroyed)
{
//
// Being destroyed by main thread
//
return;
}
if(iceNohup && sig == SIGHUP)
{
return;
}
Debug.Assert(!iceCallbackInProgress);
iceCallbackInProgress = true;
iceInterrupted = true;
iceDestroyed = true;
}
try
{
Debug.Assert(iceCommunicator != null);
iceCommunicator.destroy();
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("(while destroying in response to signal " + sig + "):\n" + ex);
}
lock(iceMutex)
{
iceCallbackInProgress = false;
System.Threading.Monitor.Pulse(iceMutex);
}
}
private static void shutdownOnInterruptCallback(int sig)
{
lock(iceMutex)
{
if(iceDestroyed)
{
//
// Being destroyed by main thread
//
return;
}
if(iceNohup && sig == SIGHUP)
{
return;
}
Debug.Assert(!iceCallbackInProgress);
iceCallbackInProgress = true;
iceInterrupted = true;
}
try
{
Debug.Assert(iceCommunicator != null);
iceCommunicator.shutdown();
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("(while shutting down in response to signal " + sig + "):\n" + ex);
}
lock(iceMutex)
{
iceCallbackInProgress = false;
System.Threading.Monitor.Pulse(iceMutex);
}
}
private static void userCallbackOnInterruptCallback(int sig)
{
lock(iceMutex)
{
if(iceDestroyed)
{
//
// Being destroyed by main thread
//
return;
}
// For SIGHUP the user callback is always called. It can
// decide what to do.
Debug.Assert(!iceCallbackInProgress);
iceCallbackInProgress = true;
iceInterrupted = true;
}
try
{
Debug.Assert(_application != null);
_application.interruptCallback(sig);
}
catch(System.Exception ex)
{
Util.getProcessLogger().error("(while interrupting in response to signal " + sig + "):\n" + ex);
}
lock(iceMutex)
{
iceCallbackInProgress = false;
System.Threading.Monitor.Pulse(iceMutex);
}
}
protected static object iceMutex = new object();
protected static bool iceCallbackInProgress = false;
protected static bool iceDestroyed = false;
protected static bool iceInterrupted = false;
protected static bool iceReleased = false;
protected static bool iceNohup = false;
protected static SignalPolicy iceSignalPolicy = SignalPolicy.HandleSignals;
private delegate void Callback(int sig);
private static readonly Callback _destroyCallback = new Callback(destroyOnInterruptCallback);
private static readonly Callback _shutdownCallback = new Callback(shutdownOnInterruptCallback);
private static readonly Callback _holdCallback = new Callback(holdInterruptCallback);
private static readonly Callback _userCallback = new Callback(userCallbackOnInterruptCallback);
private static Callback _callback = null; // Current callback
private static Callback _previousCallback; // Remembers prev. callback when signals are held
//
// We use FriendlyName instead of Process.GetCurrentProcess().ProcessName because the latter
// is terribly slow. (It takes around 1 second!)
//
protected static string iceAppName = AppDomain.CurrentDomain.FriendlyName;
protected static Communicator iceCommunicator;
private static Application _application;
private static int SIGHUP;
static Application()
{
SIGHUP = 5; // CTRL_LOGOFF_EVENT, from wincon.h
}
private delegate void SignalHandler(int sig);
private static readonly SignalHandler _handler = new SignalHandler(signalHandler);
private Signals _signals;
private interface Signals
{
void register(SignalHandler handler);
void destroy();
}
private class WindowsSignals : Signals
{
#if MANAGED
public void register(SignalHandler handler)
{
_handler = handler;
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs args)
{
args.Cancel = true;
_handler(0);
};
}
public void destroy()
{
}
#else
public void register(SignalHandler handler)
{
_handler = handler;
_callback = new CtrlCEventHandler(callback);
bool rc = NativeMethods.SetConsoleCtrlHandler(_callback, true);
Debug.Assert(rc);
}
public void destroy()
{
}
private CtrlCEventHandler _callback;
private bool callback(int sig)
{
_handler(sig);
return true;
}
#endif
private SignalHandler _handler;
}
}
delegate bool CtrlCEventHandler(int sig);
}
|