Skip to content

Commit

Permalink
Fixes and required changes after review
Browse files Browse the repository at this point in the history
  • Loading branch information
pawelvds committed Jan 11, 2024
1 parent 29e3579 commit b27af72
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 103 deletions.
30 changes: 9 additions & 21 deletions src/fiskaltrust.Launcher.Common/Configuration/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ public record LauncherConfiguration
public LauncherConfiguration()
{
_rawAccess = false;
_launcherServiceUri = OperatingSystem.IsWindows()
? $"net.pipe://localhost/fiskaltrust-{_cashboxId}"
: $"/tmp/fiskaltrust-{_cashboxId}.sock";
}

public T Raw<T>(System.Linq.Expressions.Expression<Func<LauncherConfiguration, T>> accessor)
Expand Down Expand Up @@ -85,7 +82,15 @@ private T WithDefault<T>(T value, Func<T> defaultValue)

private string? _launcherServiceUri;
[JsonPropertyName("launcherServiceUri")]
public string? LauncherServiceUri { get => _launcherServiceUri; set => _launcherServiceUri = value; }
public string? LauncherServiceUri {
get => WithDefault(
_launcherServiceUri,
OperatingSystem.IsWindows()
? $"net.pipe://localhost/fiskaltrust-{_cashboxId}"
: $"/tmp/fiskaltrust-{_cashboxId}.sock"
);
set => _launcherServiceUri = value;
}

private string? _serviceFolder;
[JsonPropertyName("serviceFolder")]
Expand All @@ -95,12 +100,6 @@ private T WithDefault<T>(T value, Func<T> defaultValue)
[JsonPropertyName("sandbox")]
public bool? Sandbox { get => WithDefault(_sandbox, false); set => _sandbox = value; }

[JsonPropertyName("domainSocket")]
public LauncherConfiguration.DomainSocketConfig DomainSocket { get; init; } = new();

[JsonPropertyName("namedPipe")]
public LauncherConfiguration.NamedPipeConfig NamedPipe { get; init; } = new();

private bool? _useOffline;
[JsonPropertyName("useOffline")]
public bool? UseOffline { get => WithDefault(_useOffline, false); set => _useOffline = value; }
Expand Down Expand Up @@ -340,17 +339,6 @@ public void Decrypt(IDataProtector dataProtector)
return null;
}

public record DomainSocketConfig
{
public bool Enabled { get; init; }
public string? Path { get; init; }
}

public record NamedPipeConfig
{
public bool Enabled { get; init; }
public string? Name { get; init; }
}
}

public record LauncherConfigurationInCashBoxConfiguration
Expand Down
67 changes: 58 additions & 9 deletions src/fiskaltrust.Launcher/Commands/HostCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
using fiskaltrust.Launcher.Download;
using fiskaltrust.Launcher.Constants;
using System.Diagnostics;
using System.IO.Pipes;
using System.Net;
using System.Net.Sockets;
using System.Security.Principal;
using fiskaltrust.Launcher.Common.Extensions;
using fiskaltrust.Launcher.Common.Configuration;
using fiskaltrust.Launcher.Configuration;
Expand All @@ -36,9 +40,7 @@ public HostCommand() : base("host")

public class HostOptions
{
public HostOptions(string launcherConfiguration, string plebeianConfiguration, bool noProcessHostService,
bool debugging, string? namedPipeName, bool useNamedPipes, string? domainSocketPath,
bool useDomainSockets)
public HostOptions(string launcherConfiguration, string plebeianConfiguration, bool noProcessHostService, bool debugging)
{
LauncherConfiguration = launcherConfiguration;
PlebeianConfiguration = plebeianConfiguration;
Expand Down Expand Up @@ -81,7 +83,7 @@ public static async Task<int> HandleAsync(HostOptions hostOptions, HostServices
var plebeianConfiguration = PlebeianConfiguration.Deserialize(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(hostOptions.PlebeianConfiguration)));

var cashboxConfiguration = CashBoxConfigurationExt.Deserialize(await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!));
cashboxConfiguration.Decrypt(launcherConfiguration, await CommonHandler.LoadCurve(launcherConfiguration.CashboxId.Value, launcherConfiguration.AccessToken!, launcherConfiguration.ServiceFolder!));
cashboxConfiguration.Decrypt(launcherConfiguration, await CommonHandler.LoadCurve(launcherConfiguration.CashboxId!.Value, launcherConfiguration.AccessToken!, launcherConfiguration.ServiceFolder!));

var packageConfiguration = (plebeianConfiguration.PackageType switch
{
Expand All @@ -96,9 +98,22 @@ public static async Task<int> HandleAsync(HostOptions hostOptions, HostServices
IProcessHostService? processHostService = null;
if (!hostOptions.NoProcessHostService)
{
string grpcAddress = launcherConfiguration.LauncherServiceUri?.ToString();
processHostService = GrpcChannel.ForAddress(grpcAddress).CreateGrpcService<IProcessHostService>();

var grpcAddress = launcherConfiguration.LauncherServiceUri;
if (OperatingSystem.IsWindows())
{
var pipeName = new Uri(grpcAddress!).LocalPath.TrimStart('/');
var factory = new NamedPipesConnectionFactory(pipeName);
var handler = new SocketsHttpHandler { ConnectCallback = factory.ConnectAsync };
processHostService = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions { HttpHandler = handler }).CreateGrpcService<IProcessHostService>();
}
else // Unix
{
var socketPath = grpcAddress;
var udsEndPoint = new UnixDomainSocketEndPoint(socketPath!);
var factory = new UnixDomainSocketsConnectionFactory(udsEndPoint);
var handler = new SocketsHttpHandler { ConnectCallback = factory.ConnectAsync };
processHostService = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions { HttpHandler = handler }).CreateGrpcService<IProcessHostService>();
}
}

Log.Logger = new LoggerConfiguration()
Expand Down Expand Up @@ -148,7 +163,7 @@ public static async Task<int> HandleAsync(HostOptions hostOptions, HostServices
}
catch (Exception e)
{
Log.Error(e, "Could not load {Type}.", nameof(IMiddlewareBootstrapper));
Log.Error(e, "Could not load {Type}", nameof(IMiddlewareBootstrapper));
throw;
}
});
Expand All @@ -160,7 +175,7 @@ public static async Task<int> HandleAsync(HostOptions hostOptions, HostServices
}
catch (Exception e)
{
Log.Error(e, "An unhandled exception occured.");
Log.Error(e, "An unhandled exception occured");
throw;
}
finally
Expand All @@ -170,6 +185,40 @@ public static async Task<int> HandleAsync(HostOptions hostOptions, HostServices

return 0;
}

public class NamedPipesConnectionFactory
{
private readonly string _pipeName;

public NamedPipesConnectionFactory(string pipeName)
{
_pipeName = pipeName;
}

public async ValueTask<Stream> ConnectAsync(SocketsHttpConnectionContext _, CancellationToken cancellationToken)
{
var clientStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.WriteThrough | PipeOptions.Asynchronous, TokenImpersonationLevel.Anonymous);
await clientStream.ConnectAsync(cancellationToken).ConfigureAwait(false);
return clientStream;
}
}

public class UnixDomainSocketsConnectionFactory
{
private readonly EndPoint _endPoint;

public UnixDomainSocketsConnectionFactory(EndPoint endPoint)
{
_endPoint = endPoint;
}

public async ValueTask<Stream> ConnectAsync(SocketsHttpConnectionContext _, CancellationToken cancellationToken)
{
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
await socket.ConnectAsync(_endPoint, cancellationToken).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: true);
}
}

private static Dictionary<string, object> ProcessPackageConfiguration(Dictionary<string, object> configuration, LauncherConfiguration launcherConfiguration, ftCashBoxConfiguration cashboxConfiguration)
{
Expand Down
20 changes: 17 additions & 3 deletions src/fiskaltrust.Launcher/Commands/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,23 @@ public static async Task<int> HandleAsync(CommonOptions commonOptions, CommonPro
services.AddSingleton(_ => Log.Logger);
services.AddSingleton(_ => runServices.LauncherExecutablePath);
});

builder.WebHost.ConfigureBinding(new Uri($"http://[::1]:{commonProperties.LauncherConfiguration.LauncherServiceUri}"), protocols: HttpProtocols.Http2);


//Configure Kestrel
if (OperatingSystem.IsWindows())
{
builder.WebHost.UseKestrel(serverOptions =>
{
serverOptions.ListenNamedPipe(commonProperties.LauncherConfiguration.LauncherServiceUri!);
});
}
else
{
builder.WebHost.UseKestrel(serverOptions =>
{
serverOptions.ListenUnixSocket(commonProperties.LauncherConfiguration.LauncherServiceUri!);
});
}

builder.Services.AddCodeFirstGrpc();

var app = builder.Build();
Expand Down
51 changes: 0 additions & 51 deletions src/fiskaltrust.Launcher/ProcessHost/ProcessHostMonarcStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ public class AlreadyLoggedException : Exception { }
private readonly ILoggerFactory _loggerFactory;
private readonly ILifetime _lifetime;
private readonly LauncherExecutablePath _launcherExecutablePath;
private readonly TaskCompletionSource<Uri> _kestrelReady;
private readonly WebApplicationBuilder _webHostBuilder;

public ProcessHostMonarcStartup(ILoggerFactory loggerFactory, ILogger<ProcessHostMonarcStartup> logger, Dictionary<Guid, IProcessHostMonarch> hosts, LauncherConfiguration launcherConfiguration, ftCashBoxConfiguration cashBoxConfiguration, PackageDownloader downloader, ILifetime lifetime, LauncherExecutablePath launcherExecutablePath, IHostApplicationLifetime hostApplicationLifetime, IServer server)
{
Expand All @@ -39,45 +37,14 @@ public ProcessHostMonarcStartup(ILoggerFactory loggerFactory, ILogger<ProcessHos
_downloader = downloader;
_lifetime = lifetime;
_launcherExecutablePath = launcherExecutablePath;
_kestrelReady = new TaskCompletionSource<Uri>();
_webHostBuilder = WebApplication.CreateBuilder();

hostApplicationLifetime.ApplicationStarted.Register(() =>
{
try
{
_kestrelReady.TrySetResult(new Uri(server.Features.Get<IServerAddressesFeature>()!.Addresses!.First()));
}
catch (Exception e)
{
_kestrelReady.TrySetException(e);
}
});
}

protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
_lifetime.ApplicationLifetime.ApplicationStopping.Register(() => _logger.LogInformation("Shutting down launcher."));
cancellationToken.Register(() => _kestrelReady.TrySetCanceled());

StartupLogging();

if (string.IsNullOrEmpty(_launcherConfiguration.LauncherServiceUri))
{
try
{
var uri = new Uri(_launcherConfiguration.LauncherServiceUri);
ConfigureKestrel(uri, _webHostBuilder);
_logger.LogInformation("ProcessHostService running on {uri}", uri);
}
catch (Exception e)
{
if (cancellationToken.IsCancellationRequested) { return; }
_logger.LogError(e, "Could not get Kestrel port.");
throw new AlreadyLoggedException();
}
}

_downloader.CopyPackagesToCache();

try
Expand Down Expand Up @@ -140,24 +107,6 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken)
_lifetime.ApplicationLifetime.StopApplication();
}

private void ConfigureKestrel(Uri launcherServiceUri, WebApplicationBuilder builder)
{
if (OperatingSystem.IsWindows())
{
builder.WebHost.UseKestrel(serverOptions =>
{
serverOptions.ListenNamedPipe(launcherServiceUri.ToString());
});
}
else
{
builder.WebHost.UseKestrel(serverOptions =>
{
serverOptions.ListenUnixSocket(launcherServiceUri.ToString());
});
}
}

private async Task StartProcessHostMonarch(PackageConfiguration configuration, PackageType packageType, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
Expand Down
23 changes: 5 additions & 18 deletions src/fiskaltrust.Launcher/Services/HostingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,28 +246,15 @@ private WebApplication CreateGrpcHost<T>(WebApplicationBuilder builder, Uri uri,
_logger.LogWarning($"{nameof(_launcherConfiguration.UseHttpSysBinding)} is not supported for grpc.");
}

// Support for domain sockets/namespots
if (_launcherConfiguration.DomainSocket.Enabled)
{
builder.WebHost.UseKestrel(options =>
{
options.ListenUnixSocket(_launcherConfiguration.DomainSocket.Path!, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
ConfigureTls(listenOptions);
});
});
}
else
{
builder.WebHost.BindKestrel(uri, listenOptions => ConfigureTls(listenOptions), false, HttpProtocols.Http2);
}

builder.WebHost.BindKestrel(uri, listenOptions => ConfigureTls(listenOptions), false, HttpProtocols.Http2);
builder.Services.AddCodeFirstGrpc(options => options.EnableDetailedErrors = true);
builder.Services.AddSingleton(instance);

var app = builder.Build();
if (!OperatingSystem.IsWindows() || _launcherConfiguration.UseHttpSysBinding!.Value == false) { app.UsePathBase(uri.AbsolutePath); }
if (!OperatingSystem.IsWindows() || _launcherConfiguration.UseHttpSysBinding!.Value == false)
{
app.UsePathBase(uri.AbsolutePath);
}

app.UseRouting();
#pragma warning disable ASP0014
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ public void RandomConfiguration_SerializaAndDeserialize_ShouldPreserveNull()
var serialized = configuration.Serialize();
var deserialized = LauncherConfiguration.Deserialize(serialized);

deserialized.Should().BeEquivalentTo(configuration, options => options.Excluding(cfg => cfg.LauncherServiceUri));
deserialized.Raw(d => configuration.Raw(c => d.Should().BeEquivalentTo(c, "")));

deserialized.Should().BeEquivalentTo(deserialized);
}
}

Expand Down

0 comments on commit b27af72

Please sign in to comment.