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

Add SystemdServices package that provides Host integration for systemd. #1804

Merged
merged 12 commits into from Jun 10, 2019
30 changes: 30 additions & 0 deletions Extensions.sln
Expand Up @@ -297,6 +297,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{B0D89499
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "testassets", "testassets", "{15AC3300-D335-4C5C-9E3A-22F26904AB26}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Systemd", "src\Hosting\Systemd\src\Microsoft.Extensions.Hosting.Systemd.csproj", "{86C50991-634A-41BB-86EE-22B09A3EAD2D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Systemd.Tests", "src\Hosting\Systemd\test\Microsoft.Extensions.Hosting.Systemd.Tests.csproj", "{C85BC039-863D-4577-AECF-681A8ACA601A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.WindowsServices", "src\Hosting\WindowsServices\src\Microsoft.Extensions.Hosting.WindowsServices.csproj", "{452F9F79-40E8-4B1C-8857-404062886080}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.WindowsServices.Tests", "src\Hosting\WindowsServices\test\Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj", "{47D27C64-B8B7-4D10-9112-1432EACC79B3}"
Expand Down Expand Up @@ -1871,6 +1875,30 @@ Global
{60313ECC-7C20-4509-B41B-C0F69F5162E7}.Release|x64.Build.0 = Release|Any CPU
{60313ECC-7C20-4509-B41B-C0F69F5162E7}.Release|x86.ActiveCfg = Release|Any CPU
{60313ECC-7C20-4509-B41B-C0F69F5162E7}.Release|x86.Build.0 = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|x64.ActiveCfg = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|x64.Build.0 = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|x86.ActiveCfg = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Debug|x86.Build.0 = Debug|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|Any CPU.Build.0 = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|x64.ActiveCfg = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|x64.Build.0 = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|x86.ActiveCfg = Release|Any CPU
{86C50991-634A-41BB-86EE-22B09A3EAD2D}.Release|x86.Build.0 = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|x64.ActiveCfg = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|x64.Build.0 = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|x86.ActiveCfg = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Debug|x86.Build.0 = Debug|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|Any CPU.Build.0 = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|x64.ActiveCfg = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|x64.Build.0 = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|x86.ActiveCfg = Release|Any CPU
{C85BC039-863D-4577-AECF-681A8ACA601A}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -2012,6 +2040,8 @@ Global
{1DF2C30F-4A33-4711-B198-6163C931FAC8} = {6868A014-43FD-4047-B536-30D5D159D9D4}
{C7204C14-0FA5-4EE6-B538-CAAEB7854E98} = {1DF2C30F-4A33-4711-B198-6163C931FAC8}
{60313ECC-7C20-4509-B41B-C0F69F5162E7} = {6868A014-43FD-4047-B536-30D5D159D9D4}
{86C50991-634A-41BB-86EE-22B09A3EAD2D} = {C4A5DF0A-0798-40BD-B7A4-CF02D3A993D5}
{C85BC039-863D-4577-AECF-681A8ACA601A} = {C4A5DF0A-0798-40BD-B7A4-CF02D3A993D5}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {814BFC88-0867-451F-AC8F-20FE107809B4}
Expand Down
1 change: 1 addition & 0 deletions eng/ProjectReferences.props
Expand Up @@ -35,6 +35,7 @@
<ProjectReferenceProvider Include="Microsoft.Extensions.Diagnostics.HealthChecks" ProjectPath="$(RepoRoot)src\HealthChecks\HealthChecks\src\Microsoft.Extensions.Diagnostics.HealthChecks.csproj" RefProjectPath="$(RepoRoot)src\HealthChecks\HealthChecks\ref\Microsoft.Extensions.Diagnostics.HealthChecks.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Hosting.Abstractions" ProjectPath="$(RepoRoot)src\Hosting\Abstractions\src\Microsoft.Extensions.Hosting.Abstractions.csproj" RefProjectPath="$(RepoRoot)src\Hosting\Abstractions\ref\Microsoft.Extensions.Hosting.Abstractions.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Hosting" ProjectPath="$(RepoRoot)src\Hosting\Hosting\src\Microsoft.Extensions.Hosting.csproj" RefProjectPath="$(RepoRoot)src\Hosting\Hosting\ref\Microsoft.Extensions.Hosting.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Hosting.Systemd" ProjectPath="$(RepoRoot)src\Hosting\Systemd\src\Microsoft.Extensions.Hosting.Systemd.csproj" RefProjectPath="$(RepoRoot)src\Hosting\Systemd\ref\Microsoft.Extensions.Hosting.Systemd.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Hosting.WindowsServices" ProjectPath="$(RepoRoot)src\Hosting\WindowsServices\src\Microsoft.Extensions.Hosting.WindowsServices.csproj" RefProjectPath="$(RepoRoot)src\Hosting\WindowsServices\ref\Microsoft.Extensions.Hosting.WindowsServices.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Http" ProjectPath="$(RepoRoot)src\HttpClientFactory\Http\src\Microsoft.Extensions.Http.csproj" RefProjectPath="$(RepoRoot)src\HttpClientFactory\Http\ref\Microsoft.Extensions.Http.csproj" />
<ProjectReferenceProvider Include="Microsoft.Extensions.Http.Polly" ProjectPath="$(RepoRoot)src\HttpClientFactory\Polly\src\Microsoft.Extensions.Http.Polly.csproj" RefProjectPath="$(RepoRoot)src\HttpClientFactory\Polly\ref\Microsoft.Extensions.Http.Polly.csproj" />
Expand Down
12 changes: 12 additions & 0 deletions src/Hosting/Hosting.sln
Expand Up @@ -15,6 +15,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleMsmqHost", "samples\S
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{D754FD75-091F-48DF-B3DA-91D0DB601E8B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Systemd", "Systemd\src\Microsoft.Extensions.Hosting.Systemd.csproj", "{A7356D45-9A20-493C-9C95-EEF54727D931}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.Systemd.Tests", "Systemd\test\Microsoft.Extensions.Hosting.Systemd.Tests.csproj", "{0A1C6C61-F5C6-4688-8C86-3B4D8DB0E6FF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.WindowsServices", "WindowsServices\src\Microsoft.Extensions.Hosting.WindowsServices.csproj", "{EC466ABD-86DF-42A8-A307-1F0B28B36A2F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Hosting.WindowsServices.Tests", "WindowsServices\test\Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj", "{1A3BC0DA-CB53-4C21-BDD0-2B2CF83655FA}"
Expand Down Expand Up @@ -71,6 +75,14 @@ Global
{A5C1CB77-4286-40BD-A87A-8EB13548F755}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A5C1CB77-4286-40BD-A87A-8EB13548F755}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A5C1CB77-4286-40BD-A87A-8EB13548F755}.Release|Any CPU.Build.0 = Release|Any CPU
{A7356D45-9A20-493C-9C95-EEF54727D931}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7356D45-9A20-493C-9C95-EEF54727D931}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7356D45-9A20-493C-9C95-EEF54727D931}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A7356D45-9A20-493C-9C95-EEF54727D931}.Release|Any CPU.Build.0 = Release|Any CPU
{0A1C6C61-F5C6-4688-8C86-3B4D8DB0E6FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A1C6C61-F5C6-4688-8C86-3B4D8DB0E6FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A1C6C61-F5C6-4688-8C86-3B4D8DB0E6FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A1C6C61-F5C6-4688-8C86-3B4D8DB0E6FF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
@@ -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>
@@ -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) { }
}
}
20 changes: 20 additions & 0 deletions src/Hosting/Systemd/src/ISystemdNotifier.cs
@@ -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; }
}
}
@@ -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>
42 changes: 42 additions & 0 deletions src/Hosting/Systemd/src/ServiceState.cs
@@ -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;
}
}
26 changes: 26 additions & 0 deletions src/Hosting/Systemd/src/SystemdHelpers.cs
@@ -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));
}
}
}
51 changes: 51 additions & 0 deletions src/Hosting/Systemd/src/SystemdHostBuilderExtensions.cs
@@ -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 ())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (SystemdHelpers.IsSystemdService ())
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;
}
}
}
90 changes: 90 additions & 0 deletions src/Hosting/Systemd/src/SystemdLifetime.cs
@@ -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();
}
}
}