Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consume PosixSignal in Hosting.Systemd's SystemdLifetime #59880

Merged
merged 4 commits into from
Nov 1, 2021
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
<Import Project="..\Directory.Build.props" />
<PropertyGroup>
<PackageTags>hosting</PackageTags>
<IncludePlatformAttributes>true</IncludePlatformAttributes>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hostin
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting", "..\Microsoft.Extensions.Hosting\src\Microsoft.Extensions.Hosting.csproj", "{AFC1BDAA-7E40-4118-BB80-F8057752A600}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn3.11.csproj", "{5F69DAFF-F4BC-4E29-A4FA-E96A4D55EC2D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn3.11", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn3.11.csproj", "{5F69DAFF-F4BC-4E29-A4FA-E96A4D55EC2D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn4.0.csproj", "{0D1BFEB4-CEF6-4319-9212-E3E7840B287A}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Generators.Roslyn4.0", "..\Microsoft.Extensions.Logging.Abstractions\gen\Microsoft.Extensions.Logging.Generators.Roslyn4.0.csproj", "{0D1BFEB4-CEF6-4319-9212-E3E7840B287A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Logging.Abstractions", "..\Microsoft.Extensions.Logging.Abstractions\ref\Microsoft.Extensions.Logging.Abstractions.csproj", "{860B845B-929F-4442-AED1-1F4186DBF497}"
EndProject
Expand Down Expand Up @@ -137,9 +137,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Encodings.Web", "..\System.Text.Encodings.Web\src\System.Text.Encodings.Web.csproj", "{47A3CDB0-8252-4536-B61F-C2E10F6EC2B9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj", "{5C6A1B61-B02B-46AA-8AD5-B8F61EE57453}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn3.11", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj", "{5C6A1B61-B02B-46AA-8AD5-B8F61EE57453}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn4.0.csproj", "{771CB4BB-4237-444E-82CE-C81A4979D89F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json.SourceGeneration.Roslyn4.0", "..\System.Text.Json\gen\System.Text.Json.SourceGeneration.Roslyn4.0.csproj", "{771CB4BB-4237-444E-82CE-C81A4979D89F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Text.Json", "..\System.Text.Json\ref\System.Text.Json.csproj", "{AA2CD494-414F-42BF-9C68-7822DEB09255}"
EndProject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,19 @@ public static partial class SystemdHelpers
{
public static bool IsSystemdService() { throw null; }
}
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("maccatalyst")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public partial class SystemdLifetime : Microsoft.Extensions.Hosting.IHostLifetime, System.IDisposable
{
public SystemdLifetime(Microsoft.Extensions.Hosting.IHostEnvironment environment, Microsoft.Extensions.Hosting.IHostApplicationLifetime applicationLifetime, Microsoft.Extensions.Hosting.Systemd.ISystemdNotifier systemdNotifier, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { }
public void Dispose() { }
public System.Threading.Tasks.Task StopAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task WaitForStartAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
}
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public partial class SystemdNotifier : Microsoft.Extensions.Hosting.Systemd.ISystemdNotifier
{
public SystemdNotifier() { }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.1</TargetFrameworks>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1</TargetFrameworks>
<EnableDefaultItems>true</EnableDefaultItems>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Hosting\ref\Microsoft.Extensions.Hosting.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
<Reference Include="netstandard" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp' and '$(TargetFramework)' != '$(NetCoreAppCurrent)'">
<Reference Include="System.Runtime" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.1</TargetFrameworks>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1</TargetFrameworks>
<EnableDefaultItems>true</EnableDefaultItems>
<PackageDescription>.NET hosting infrastructure for Systemd Services.</PackageDescription>
<!-- Use targeting pack references instead of granular ones in the project file. -->
<DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences>
</PropertyGroup>

<ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">
<Compile Remove="SystemdLifetime.netcoreapp.cs" />
</ItemGroup>

<ItemGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">
<Compile Remove="SystemdLifetime.netstandard.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Hosting\src\Microsoft.Extensions.Hosting.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder)
options.FormatterName = ConsoleFormatterNames.Systemd;
});

// IsSystemdService() will never return true for android/browser/iOS/tvOS
#pragma warning disable CA1416 // Validate platform compatibility
services.AddSingleton<ISystemdNotifier, SystemdNotifier>();
services.AddSingleton<IHostLifetime, SystemdLifetime>();
#pragma warning restore CA1416 // Validate platform compatibility
});
}
return hostBuilder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Microsoft.Extensions.Hosting.Systemd
{
public class SystemdLifetime : IHostLifetime, IDisposable
[UnsupportedOSPlatform("android")]
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("maccatalyst")]
[UnsupportedOSPlatform("tvos")]
public partial class SystemdLifetime : IHostLifetime, IDisposable
{
private readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false);
private CancellationTokenRegistration _applicationStartedRegistration;
private CancellationTokenRegistration _applicationStoppingRegistration;

Expand Down Expand Up @@ -45,12 +50,13 @@ public Task WaitForStartAsync(CancellationToken cancellationToken)
},
this);

// systemd sends SIGTERM to stop the service.
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
RegisterShutdownHandlers();

return Task.CompletedTask;
}

private partial void RegisterShutdownHandlers();

private void OnApplicationStarted()
{
Logger.LogInformation("Application started. Hosting environment: {EnvironmentName}; Content root path: {ContentRoot}",
Expand All @@ -66,25 +72,14 @@ private void OnApplicationStopping()
SystemdNotifier.Notify(ServiceState.Stopping);
}

private void OnProcessExit(object sender, EventArgs e)
{
ApplicationLifetime.StopApplication();

_shutdownBlock.WaitOne();

// On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code.
// Suppress that since we shut down gracefully. https://github.com/dotnet/aspnetcore/issues/6526
System.Environment.ExitCode = 0;
}

public void Dispose()
{
_shutdownBlock.Set();

AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
UnregisterShutdownHandlers();

_applicationStartedRegistration.Dispose();
_applicationStoppingRegistration.Dispose();
}

private partial void UnregisterShutdownHandlers();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Microsoft.Extensions.Hosting.Systemd
{
public partial class SystemdLifetime
{
private PosixSignalRegistration _sigTermRegistration;

private partial void RegisterShutdownHandlers()
{
// systemd only sends SIGTERM to the service process, so we only listen for that signal.
// Other signals (ex. SIGINT/SIGQUIT) will be handled by the default .NET runtime signal handler
// and won't cause a graceful shutdown of the systemd service.
_sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandlePosixSignal);
}

private void HandlePosixSignal(PosixSignalContext context)
{
Debug.Assert(context.Signal == PosixSignal.SIGTERM);

context.Cancel = true;
ApplicationLifetime.StopApplication();
}

private partial void UnregisterShutdownHandlers()
{
_sigTermRegistration?.Dispose();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// 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.Threading;

namespace Microsoft.Extensions.Hosting.Systemd
{
public partial class SystemdLifetime
{
private readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false);

private partial void RegisterShutdownHandlers()
{
// systemd sends SIGTERM to stop the service.
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}

private void OnProcessExit(object sender, EventArgs e)
{
ApplicationLifetime.StopApplication();

_shutdownBlock.WaitOne();

// On Linux if the shutdown is triggered by SIGTERM then that's signaled with the 143 exit code.
// Suppress that since we shut down gracefully. https://github.com/dotnet/aspnetcore/issues/6526
System.Environment.ExitCode = 0;
}

private partial void UnregisterShutdownHandlers()
{
_shutdownBlock.Set();

AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Versioning;

namespace Microsoft.Extensions.Hosting.Systemd
{
[UnsupportedOSPlatform("browser")]
public class SystemdNotifier : ISystemdNotifier
{
private const string NOTIFY_SOCKET = "NOTIFY_SOCKET";
Expand Down Expand Up @@ -57,7 +58,11 @@ private static string GetNotifySocketPath()
// Support abstract socket paths.
if (socketPath[0] == '@')
{
socketPath = "\0" + socketPath.Substring(1);
socketPath = string.Create(socketPath.Length, socketPath, (buffer, state) =>
{
buffer[0] = '\0';
state.AsSpan(1).CopyTo(buffer.Slice(1));
});
eerhardt marked this conversation as resolved.
Show resolved Hide resolved
}

return socketPath;
Expand Down