未验证 提交 c40c32cc 编写于 作者: J judilsteve 提交者: GitHub

Detect systemd when inside a container. (#67288)

* Detect systemd when inside a container.

Modify IsSystemdService to function correctly
for containerised services.

Fix #67203

Adds conditional compilation to fall back
to Process.GetCurrentProcess().Id when
Environment.ProcessId is not available.

* Apply suggestions from code review

The minimum supported .NETCoreApp version in the repository is 6.0, so just using NETCOREAPP.

Co-authored-by: james <judilsteve>
Co-authored-by: NEric Erhardt <eric.erhardt@microsoft.com>
上级 7e641e6d
......@@ -5,6 +5,9 @@
using System.Globalization;
using System.IO;
using System.Text;
#if !NETCOREAPP
using System.Diagnostics;
#endif
namespace Microsoft.Extensions.Hosting.Systemd
{
......@@ -20,9 +23,9 @@ public static partial class SystemdHelpers
/// </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 = CheckParentIsSystemd());
=> _isSystemdService ??= GetIsSystemdService();
private static bool CheckParentIsSystemd()
private static bool GetIsSystemdService()
{
// No point in testing anything unless it's Unix
if (Environment.OSVersion.Platform != PlatformID.Unix)
......@@ -30,6 +33,21 @@ private static bool CheckParentIsSystemd()
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 NETCOREAPP
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'.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册