Skip to content

Commit 2ca239d

Browse files
authored
Implement support for multiple sockets for systemd activation (#24118)
1 parent c2bc640 commit 2ca239d

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/Servers/Kestrel/Core/src/Systemd/KestrelServerOptionsSystemdExtensions.cs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ namespace Microsoft.AspNetCore.Hosting
1111
public static class KestrelServerOptionsSystemdExtensions
1212
{
1313
// SD_LISTEN_FDS_START https://www.freedesktop.org/software/systemd/man/sd_listen_fds.html
14-
private const ulong SdListenFdsStart = 3;
14+
private const int SdListenFdsStart = 3;
1515
private const string ListenPidEnvVar = "LISTEN_PID";
16+
private const string ListenFdsEnvVar = "LISTEN_FDS";
1617

1718
/// <summary>
18-
/// Open file descriptor (SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
19+
/// Open file descriptors (starting from SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
1920
/// </summary>
2021
/// <returns>
2122
/// The <see cref="KestrelServerOptions"/>.
@@ -26,7 +27,7 @@ public static KestrelServerOptions UseSystemd(this KestrelServerOptions options)
2627
}
2728

2829
/// <summary>
29-
/// Open file descriptor (SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
30+
/// Open file descriptors (starting from SD_LISTEN_FDS_START) initialized by systemd socket-based activation logic if available.
3031
/// Specify callback to configure endpoint-specific settings.
3132
/// </summary>
3233
/// <returns>
@@ -36,7 +37,16 @@ public static KestrelServerOptions UseSystemd(this KestrelServerOptions options,
3637
{
3738
if (string.Equals(Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture), Environment.GetEnvironmentVariable(ListenPidEnvVar), StringComparison.Ordinal))
3839
{
39-
options.ListenHandle(SdListenFdsStart, configure);
40+
// This matches sd_listen_fds behavior that requires %LISTEN_FDS% to be present and in range [1;INT_MAX-SD_LISTEN_FDS_START]
41+
if (int.TryParse(Environment.GetEnvironmentVariable(ListenFdsEnvVar), NumberStyles.None, NumberFormatInfo.InvariantInfo, out var listenFds)
42+
&& listenFds > 0
43+
&& listenFds <= int.MaxValue - SdListenFdsStart)
44+
{
45+
for (var handle = SdListenFdsStart; handle < SdListenFdsStart + listenFds; ++handle)
46+
{
47+
options.ListenHandle((ulong)handle, configure);
48+
}
49+
}
4050
}
4151

4252
return options;

0 commit comments

Comments
 (0)