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
Add SystemdServices package that provides Host integration for systemd. #1804
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
a9a08d8
Add SystemdServices package that provides Host integration for systemd.
tmds 6a50284
Encode in ServiceState and accept a single ServiceState in Notify
tmds ff9dbdd
Rename SystemdService to Systemd
tmds f07681e
Rename ServiceHelpers
tmds d191c4e
End *.cs files with a newline
tmds 75552ab
Don't clear INVOCATION_ID envvar
tmds 1dce548
Remove ExcludeFromSourceBuild
tmds b0d5c9a
Document why it's fine to do a sync send
tmds d319735
Update ref assembly
tmds 164ebd5
Remove ServiceState.GetData xml doc
tmds d8c80b2
Update WindowsServices ref assembly
tmds fda9cc0
Update src/Hosting/Systemd/src/ServiceState.cs
tmds File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
src/Hosting/Systemd/ref/Microsoft.Extensions.Hosting.Systemd.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
<!-- This file is automatically generated. --> | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<TargetFrameworks>netstandard2.1</TargetFrameworks> | ||
</PropertyGroup> | ||
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.1'"> | ||
<Compile Include="Microsoft.Extensions.Hosting.Systemd.netstandard2.1.cs" /> | ||
<Reference Include="Microsoft.Extensions.Hosting" /> | ||
</ItemGroup> | ||
</Project> |
44 changes: 44 additions & 0 deletions
44
src/Hosting/Systemd/ref/Microsoft.Extensions.Hosting.Systemd.netstandard2.1.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
namespace Microsoft.Extensions.Hosting | ||
{ | ||
public static partial class SystemdHostBuilderExtensions | ||
{ | ||
public static Microsoft.Extensions.Hosting.IHostBuilder UseSystemd(this Microsoft.Extensions.Hosting.IHostBuilder hostBuilder) { throw null; } | ||
} | ||
} | ||
namespace Microsoft.Extensions.Hosting.Systemd | ||
{ | ||
public partial interface ISystemdNotifier | ||
{ | ||
bool IsEnabled { get; } | ||
void Notify(Microsoft.Extensions.Hosting.Systemd.ServiceState state); | ||
} | ||
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] | ||
public partial struct ServiceState | ||
{ | ||
private object _dummy; | ||
public static readonly Microsoft.Extensions.Hosting.Systemd.ServiceState Ready; | ||
public static readonly Microsoft.Extensions.Hosting.Systemd.ServiceState Stopping; | ||
public ServiceState(string state) { throw null; } | ||
public override string ToString() { throw null; } | ||
} | ||
public static partial class SystemdHelpers | ||
{ | ||
public static bool IsSystemdService() { throw null; } | ||
} | ||
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; } | ||
} | ||
public partial class SystemdNotifier : Microsoft.Extensions.Hosting.Systemd.ISystemdNotifier | ||
{ | ||
public SystemdNotifier() { } | ||
public bool IsEnabled { get { throw null; } } | ||
public void Notify(Microsoft.Extensions.Hosting.Systemd.ServiceState state) { } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
namespace Microsoft.Extensions.Hosting.Systemd | ||
{ | ||
/// <summary> | ||
/// Provides support to notify systemd about the service status. | ||
/// </summary> | ||
public interface ISystemdNotifier | ||
{ | ||
/// <summary> | ||
/// Sends a notification to systemd. | ||
/// </summary> | ||
void Notify(ServiceState state); | ||
/// <summary> | ||
/// Returns whether systemd is configured to receive service notifications. | ||
/// </summary> | ||
bool IsEnabled { get; } | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
src/Hosting/Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<Description>.NET hosting infrastructure for Systemd Services.</Description> | ||
<TargetFramework>netstandard2.1</TargetFramework> | ||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<PackageTags>hosting</PackageTags> | ||
<IsShipping>true</IsShipping> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.Extensions.Hosting" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Text; | ||
|
||
namespace Microsoft.Extensions.Hosting.Systemd | ||
{ | ||
/// <summary> | ||
/// Describes a service state change. | ||
/// </summary> | ||
public struct ServiceState | ||
{ | ||
private byte[] _data; | ||
|
||
/// <summary> | ||
/// Service startup is finished. | ||
/// </summary> | ||
public static readonly ServiceState Ready = new ServiceState("READY=1"); | ||
|
||
/// <summary> | ||
/// Service is beginning its shutdown. | ||
/// </summary> | ||
public static readonly ServiceState Stopping = new ServiceState("STOPPING=1"); | ||
|
||
/// <summary> | ||
/// Create custom ServiceState. | ||
/// </summary> | ||
public ServiceState(string state) | ||
{ | ||
_data = Encoding.UTF8.GetBytes(state ?? throw new ArgumentNullException(nameof(state))); | ||
} | ||
|
||
/// <summary> | ||
/// String representation of service state. | ||
/// </summary> | ||
public override string ToString() | ||
=> _data == null ? string.Empty : Encoding.UTF8.GetString(_data); | ||
|
||
internal byte[] GetData() => _data; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Threading; | ||
|
||
namespace Microsoft.Extensions.Hosting.Systemd | ||
{ | ||
/// <summary> | ||
/// Helper methods for systemd Services. | ||
/// </summary> | ||
public static class SystemdHelpers | ||
{ | ||
private const string INVOCATION_ID = "INVOCATION_ID"; | ||
|
||
/// <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 () | ||
{ | ||
// We use the INVOCATION_ID envirionment variable that was introduced in systemd 232 (released 2016-11-03). | ||
return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(INVOCATION_ID)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting.Systemd; | ||
using Microsoft.Extensions.Logging.Console; | ||
|
||
namespace Microsoft.Extensions.Hosting | ||
{ | ||
/// <summary> | ||
/// Extension methods for setting up SystemdLifetime. | ||
/// </summary> | ||
public static class SystemdHostBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Sets the host lifetime to SystemdLifetime, | ||
/// provides notification messages for application started and stopping, | ||
/// and configures console logging to the systemd format. | ||
/// </summary> | ||
/// <remarks> | ||
/// <para> | ||
/// This is context aware and will only activate if it detects the process is running | ||
/// as a systemd Service. | ||
/// </para> | ||
/// <para> | ||
/// The systemd service file must be configured with <c>Type=notify</c> to enable | ||
/// notifications. See https://www.freedesktop.org/software/systemd/man/systemd.service.html. | ||
/// </para> | ||
/// </remarks> | ||
/// <param name="hostBuilder"></param> | ||
/// <returns></returns> | ||
public static IHostBuilder UseSystemd(this IHostBuilder hostBuilder) | ||
{ | ||
if (SystemdHelpers.IsSystemdService ()) | ||
{ | ||
hostBuilder.ConfigureServices((hostContext, services) => | ||
{ | ||
services.Configure<ConsoleLoggerOptions>(options => | ||
{ | ||
options.Format = ConsoleLoggerFormat.Systemd; | ||
}); | ||
|
||
services.AddSingleton<ISystemdNotifier, SystemdNotifier>(); | ||
|
||
services.AddSingleton<IHostLifetime, SystemdLifetime>(); | ||
}); | ||
} | ||
return hostBuilder; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Microsoft.Extensions.Hosting.Systemd | ||
{ | ||
public class SystemdLifetime : IHostLifetime, IDisposable | ||
{ | ||
private readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false); | ||
private CancellationTokenRegistration _applicationStartedRegistration; | ||
private CancellationTokenRegistration _applicationStoppingRegistration; | ||
|
||
public SystemdLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ISystemdNotifier systemdNotifier, ILoggerFactory loggerFactory) | ||
{ | ||
Environment = environment ?? throw new ArgumentNullException(nameof(environment)); | ||
ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime)); | ||
SystemdNotifier = systemdNotifier ?? throw new ArgumentNullException(nameof(systemdNotifier)); | ||
Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); | ||
} | ||
|
||
private IHostApplicationLifetime ApplicationLifetime { get; } | ||
private IHostEnvironment Environment { get; } | ||
private ILogger Logger { get; } | ||
private ISystemdNotifier SystemdNotifier { get; } | ||
|
||
public Task StopAsync(CancellationToken cancellationToken) | ||
{ | ||
return Task.CompletedTask; | ||
} | ||
|
||
public Task WaitForStartAsync(CancellationToken cancellationToken) | ||
{ | ||
_applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(state => | ||
{ | ||
((SystemdLifetime)state).OnApplicationStarted(); | ||
}, | ||
this); | ||
_applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(state => | ||
{ | ||
((SystemdLifetime)state).OnApplicationStopping(); | ||
}, | ||
this); | ||
|
||
// systemd sends SIGTERM to stop the service. | ||
AppDomain.CurrentDomain.ProcessExit += OnProcessExit; | ||
|
||
return Task.CompletedTask; | ||
} | ||
|
||
private void OnApplicationStarted() | ||
{ | ||
Logger.LogInformation("Application started. Hosting environment: {envName}; Content root path: {contentRoot}", | ||
Environment.EnvironmentName, Environment.ContentRootPath); | ||
|
||
SystemdNotifier.Notify(ServiceState.Ready); | ||
} | ||
|
||
private void OnApplicationStopping() | ||
{ | ||
Logger.LogInformation("Application is shutting down..."); | ||
|
||
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/aspnet/AspNetCore/issues/6526 | ||
System.Environment.ExitCode = 0; | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
_shutdownBlock.Set(); | ||
Tratcher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit; | ||
|
||
_applicationStartedRegistration.Dispose(); | ||
_applicationStoppingRegistration.Dispose(); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.