-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
SystemdHelpers.cs
67 lines (59 loc) · 2.2 KB
/
SystemdHelpers.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.IO;
using System.Text;
#if !NET
using System.Diagnostics;
#endif
namespace Microsoft.Extensions.Hosting.Systemd
{
/// <summary>
/// Helper methods for systemd Services.
/// </summary>
public static class SystemdHelpers
{
private static readonly bool _isSystemdService = GetIsSystemdService();
/// <summary>
/// Check if the current process is hosted as a systemd Service.
/// </summary>
/// <returns>
/// <see langword="true" /> if the current process is hosted as a systemd Service; otherwise, <see langword="false" />.
/// </returns>
public static bool IsSystemdService() => _isSystemdService;
private static bool GetIsSystemdService()
{
// No point in testing anything unless it's Unix
if (Environment.OSVersion.Platform != PlatformID.Unix)
{
return false;
}
// To support containerized systemd services, check if we're the main process (PID 1)
// and if there are systemd environment variables defined for notifying the service
// manager, or passing listen handles.
#if NET
int processId = Environment.ProcessId;
#else
int processId = Process.GetCurrentProcess().Id;
#endif
if (processId == 1)
{
return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NOTIFY_SOCKET")) ||
!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LISTEN_PID"));
}
try
{
// Check whether our direct parent is 'systemd'.
int parentPid = Interop.libc.GetParentPid();
string ppidString = parentPid.ToString(NumberFormatInfo.InvariantInfo);
byte[] comm = File.ReadAllBytes("/proc/" + ppidString + "/comm");
return comm.AsSpan().SequenceEqual("systemd\n"u8);
}
catch
{
}
return false;
}
}
}