Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 3 additions & 21 deletions src/Hosting/Systemd/src/SystemdHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,46 +14,28 @@ namespace Microsoft.Extensions.Hosting.Systemd
/// </summary>
public static class SystemdHelpers
{
private const string INVOCATION_ID = "INVOCATION_ID";

private static bool? _isSystemdService;

/// <summary>
/// Check if the current process is hosted as a systemd Service.
/// </summary>
/// <returns><c>True</c> if the current process is hosted as a systemd Service, otherwise <c>false</c>.</returns>
public static bool IsSystemdService()
=> _isSystemdService ?? (bool)(_isSystemdService = CheckSystemdUnit());
=> _isSystemdService ?? (bool)(_isSystemdService = CheckParentIsSystemd());

private static bool CheckSystemdUnit()
private static bool CheckParentIsSystemd()
{
// No point in testing anything unless it's Unix
if (Environment.OSVersion.Platform != PlatformID.Unix)
{
return false;
}

// We've got invocation id, it's systemd >= 232 running a unit (either directly or through a child process)
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(INVOCATION_ID)))
{
return true;
}

// Either it's not a unit, or systemd is < 232, do a bit more digging
try
{
// Test parent process (this matches only direct parents, walking all the way up to the PID 1 is probably not what we would want)
// Check whether our direct parent is 'systemd'.
var parentPid = GetParentPid();
var ppidString = parentPid.ToString(NumberFormatInfo.InvariantInfo);

// If parent PID is not 1, this may be a user unit, in this case it must match MANAGERPID envvar
if (parentPid != 1
&& Environment.GetEnvironmentVariable("MANAGERPID") != ppidString)
{
return false;
}

// Check parent process name to match "systemd\n"
var comm = File.ReadAllBytes("/proc/" + ppidString + "/comm");
return comm.AsSpan().SequenceEqual(Encoding.ASCII.GetBytes("systemd\n"));
}
Expand Down