Skip to content
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
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ jobs:
cert_path: ""
native_http: 0
needs_dind: false
- name: unix-native
docker_host: unix:///var/run/docker.sock
tls_verify: ""
cert_path: ""
native_http: 1
needs_dind: false
- name: tcp-2375
docker_host: tcp://localhost:2375
tls_verify: ""
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ var client = new DockerClientBuilder()
This is achieved by setting the environment variable `DOCKER_DOTNET_NATIVE_HTTP_ENABLED` to `1`.
By doing so, the handler used to communicate with the Docker Engine will switch to the .NET built-in one, potentially improving performance and reliability.

The native handler supports `tcp://`, `http://`, and `https://` endpoints and, on .NET 8 or later, `unix://` endpoints. To select it without the environment variable:

```csharp
using Docker.DotNet;
using Docker.DotNet.NativeHttp;

var client = new DockerClientBuilder()
.WithEndpoint(new Uri("unix:///var/run/docker.sock"))
.WithTransportOptions(new NativeHttpTransportOptions())
.Build();
```

### Transport-specific options

Use `WithTransportOptions` to select a transport explicitly and configure transport-specific options.
Expand Down
4 changes: 3 additions & 1 deletion src/Docker.DotNet.NativeHttp/Docker.DotNet.NativeHttp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>Docker.DotNet.NativeHttp</AssemblyName>
<PackageId>Docker.DotNet.Enhanced.NativeHttp</PackageId>
<Description>A Docker.DotNet transport implementation for HTTP(S) Docker Engine connections.</Description>
<Description>A Docker.DotNet transport implementation for HTTP(S) and Unix domain socket Docker Engine connections.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Docker.DotNet.Handler.Abstractions\Docker.DotNet.Handler.Abstractions.csproj" />
Expand All @@ -11,8 +11,10 @@
<Using Include="System" />
<Using Include="System.IO" />
<Using Include="System.IO.Pipes" />
<Using Include="System.Linq" />
<Using Include="System.Net.Http" />
<Using Include="System.Net.Http.Headers" />
<Using Include="System.Net.Sockets" />
<Using Include="System.Runtime.InteropServices" />
<Using Include="System.Security" />
<Using Include="System.Text" />
Expand Down
65 changes: 60 additions & 5 deletions src/Docker.DotNet.NativeHttp/DockerHandlerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,9 @@ public ResolvedTransport CreateHandler(NativeHttpTransportOptions transportOptio
throw new ArgumentNullException(nameof(clientOptions));
}

var endpoint = clientOptions.Endpoint;
var uri = clientOptions.Endpoint;

Validate(endpoint);

var scheme = clientOptions.AuthProvider.TlsEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
var uri = new UriBuilder(endpoint) { Scheme = scheme }.Uri;
Validate(uri);

#if NET
var handler = new SocketsHttpHandler
Expand All @@ -43,8 +40,24 @@ public ResolvedTransport CreateHandler(NativeHttpTransportOptions transportOptio
PooledConnectionIdleTimeout = PooledConnectionIdleTimeout,
};

if (IsUnixSocket(uri))
{
var socketName = uri.Segments.Last();
var socketPath = uri.LocalPath;
uri = new UriBuilder(Uri.UriSchemeHttp, socketName).Uri;

// Proxies do not apply to Unix domain sockets.
handler.UseProxy = false;
handler.ConnectCallback = (_, cancellationToken) => ConnectUnixSocketAsync(socketPath, cancellationToken);
}
else
{
uri = CreateHttpUri(uri, clientOptions);
}

transportOptions.ConfigureHandler(handler);
#else
uri = CreateHttpUri(uri, clientOptions);
var handler = new HttpClientHandler();
transportOptions.ConfigureHandler(handler);
#endif
Expand All @@ -64,11 +77,53 @@ private static void Validate(Uri endpoint)
{
var scheme = endpoint.Scheme;

#if NET
if (IsUnixSocket(endpoint))
{
return;
}
#endif

if (!string.Equals(scheme, "tcp", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
{
#if NET
throw new InvalidOperationException($"The selected '{nameof(NativeHttpTransportOptions)}' can only be used with endpoint schemes 'tcp', 'http', 'https', or 'unix', but '{scheme}' was provided.");
#else
throw new InvalidOperationException($"The selected '{nameof(NativeHttpTransportOptions)}' can only be used with endpoint schemes 'tcp', 'http', or 'https', but '{scheme}' was provided.");
#endif
}
}

#if NET
private static bool IsUnixSocket(Uri endpoint)
{
return string.Equals(endpoint.Scheme, "unix", StringComparison.OrdinalIgnoreCase);
}

private static async ValueTask<Stream> ConnectUnixSocketAsync(string socketPath, CancellationToken cancellationToken)
{
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);

try
{
await socket.ConnectAsync(new UnixDomainSocketEndPoint(socketPath), cancellationToken)
.ConfigureAwait(false);

return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
#endif

private static Uri CreateHttpUri(Uri endpoint, ResolvedClientOptions clientOptions)
{
var scheme = clientOptions.AuthProvider.TlsEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
return new UriBuilder(endpoint) { Scheme = scheme }.Uri;
}
}
7 changes: 7 additions & 0 deletions src/Docker.DotNet/DockerClientBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,14 @@ protected virtual IDockerHandlerFactory ResolveTransportFactory(string scheme)
return scheme.ToLowerInvariant() switch
{
"npipe" => NPipe.DockerHandlerFactory.Instance,
#if NET
"unix" => NativeHttpEnabled
? NativeHttp.DockerHandlerFactory.Instance
: Unix.DockerHandlerFactory.Instance,
#else
// The native transport needs SocketsHttpHandler to reach a Unix domain socket.
"unix" => Unix.DockerHandlerFactory.Instance,
#endif
"tcp" or "http" or "https" => NativeHttpEnabled
? NativeHttp.DockerHandlerFactory.Instance
: LegacyHttp.DockerHandlerFactory.Instance,
Expand Down
22 changes: 17 additions & 5 deletions test/Docker.DotNet.TestsV2/DockerClientBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -293,14 +293,26 @@ public void PreservesEndpointInClientOptionsWhenTransportNormalizesEndpoint()
Assert.Equal(expectedEndpoint, transportFactory.LastClientOptions.Endpoint);
}

[Theory]
[InlineData("npipe://./pipe/docker_engine", typeof(NPipe.DockerHandlerFactory))]
[InlineData("unix:/var/run/docker.sock", typeof(Unix.DockerHandlerFactory))]
public void UsesExpectedFactoryWhenSocketSchemeIsProvided(string endpoint, Type expectedFactoryType)
[Fact]
public void UsesExpectedFactoryWhenNamedPipeSchemeIsProvided()
{
var builder = new TestDockerClientBuilder();

var actualFactory = builder.ResolveTransportFactory(new Uri(endpoint));
var actualFactory = builder.ResolveTransportFactory(new Uri("npipe://./pipe/docker_engine"));

Assert.IsType<NPipe.DockerHandlerFactory>(actualFactory);
}

[Fact]
public void UsesExpectedFactoryWhenUnixSchemeIsProvided()
{
var builder = new TestDockerClientBuilder();

var actualFactory = builder.ResolveTransportFactory(new Uri("unix:/var/run/docker.sock"));

var expectedFactoryType = Environment.GetEnvironmentVariable("DOCKER_DOTNET_NATIVE_HTTP_ENABLED") == "1"
? typeof(NativeHttp.DockerHandlerFactory)
: typeof(Unix.DockerHandlerFactory);

Assert.IsType(expectedFactoryType, actualFactory);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public static TheoryData<Func<ResolvedClientOptions, ResolvedTransport>, Uri, st
},
{
options => NativeHttp.DockerHandlerFactory.Instance.CreateHandler(options, NullLogger.Instance),
new Uri("unix:/var/run/docker.sock"),
new Uri("npipe://./pipe/docker_engine"),
"NativeHttpTransportOptions",
"tcp', 'http', or 'https"
"tcp', 'http', 'https', or 'unix"
},
{
options => NPipe.DockerHandlerFactory.Instance.CreateHandler(options, NullLogger.Instance),
Expand Down