-
Notifications
You must be signed in to change notification settings - Fork 10
/
Program.cs
85 lines (71 loc) · 2.15 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using LittleForker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Serilog;
var logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(100));
var configRoot = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables()
.Build();
// Running program with --debug=true will attach a debugger.
// Used to assist with debugging LittleForker.
if (configRoot.GetValue("debug", false))
{
Debugger.Launch();
}
var ignoreShutdownSignal = configRoot.GetValue<bool>("ignore-shutdown-signal", false);
if (ignoreShutdownSignal)
{
Log.Logger.Information("Will ignore Shutdown Signal");
}
var exitWithNonZero = configRoot.GetValue<bool>("exit-with-non-zero", false);
if (exitWithNonZero)
{
Log.Logger.Information("Will exit with non-zero exit code");
}
var pid = Environment.ProcessId;
logger.Information($"Long running process started. PID={pid}");
var parentPid = configRoot.GetValue<int?>("ParentProcessId");
using (parentPid.HasValue
? new ProcessExitedHelper(parentPid.Value, _ => ParentExited(parentPid.Value), new NullLoggerFactory())
: NoopDisposable.Instance)
{
using (await CooperativeShutdown.Listen(ExitRequested, new NullLoggerFactory()))
{
// Poll the shutdown token in a tight loop
while (!shutdown.IsCancellationRequested || ignoreShutdownSignal)
{
await Task.Delay(100);
}
Log.Information("Exiting.");
}
}
return exitWithNonZero ? -1 : 0;
void ExitRequested()
{
Log.Logger.Information("Cooperative shutdown requested.");
if (ignoreShutdownSignal)
{
Log.Logger.Information("Shut down signal ignored.");
return;
}
shutdown.Cancel();
}
void ParentExited(int processId)
{
Log.Logger.Information($"Parent process {processId} exited.");
shutdown.Cancel();
}
class NoopDisposable : IDisposable
{
public void Dispose()
{ }
internal static readonly IDisposable Instance = new NoopDisposable();
}