Skip to content

Improve auto-discovery of configuration assemblies in bundled mode #304

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

Closed
wants to merge 6 commits into from
Closed
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
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,6 @@ For legacy .NET Framework projects it also scans default probing path(s).

For all other cases, as well as in the case of non-conventional configuration assembly names **DO** use [Using](#using-section-and-auto-discovery-of-configuration-assemblies) section.

#### .NET 5.0 Single File Applications

Currently, auto-discovery of configuration assemblies is not supported in bundled mode. **DO** use [Using](#using-section-and-auto-discovery-of-configuration-assemblies) section for workaround.

### MinimumLevel, LevelSwitches, overrides and dynamic reload

The `MinimumLevel` configuration property can be set to a single value as in the sample above, or, levels can be overridden per logging source.
Expand Down
5 changes: 5 additions & 0 deletions serilog-settings-configuration.sln
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample", "sample\Sample\Sam
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestDummies", "test\TestDummies\TestDummies.csproj", "{B7CF5068-DD19-4868-A268-5280BDE90361}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestSingleFileApp", "test\TestSingleFileApp\TestSingleFileApp.csproj", "{C959B095-5B29-4663-A5B6-4742D5EA97AB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -53,6 +55,8 @@ Global
{B7CF5068-DD19-4868-A268-5280BDE90361}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B7CF5068-DD19-4868-A268-5280BDE90361}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B7CF5068-DD19-4868-A268-5280BDE90361}.Release|Any CPU.Build.0 = Release|Any CPU
{C959B095-5B29-4663-A5B6-4742D5EA97AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C959B095-5B29-4663-A5B6-4742D5EA97AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -62,6 +66,7 @@ Global
{F793C6E8-C40A-4018-8884-C97E2BE38A54} = {D551DCB0-7771-4D01-BEBD-F7B57D1CF0E3}
{A00E5E32-54F9-401A-BBA1-2F6FCB6366CD} = {D24872B9-57F3-42A7-BC8D-F9DA222FCE1B}
{B7CF5068-DD19-4868-A268-5280BDE90361} = {D551DCB0-7771-4D01-BEBD-F7B57D1CF0E3}
{C959B095-5B29-4663-A5B6-4742D5EA97AB} = {D551DCB0-7771-4D01-BEBD-F7B57D1CF0E3}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {485F8843-42D7-4267-B5FB-20FE9181DEE9}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
Expand All @@ -16,19 +16,28 @@ protected static bool IsCaseInsensitiveMatch(string text, string textToFind)

public static AssemblyFinder Auto()
{
try
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
// Need to check `Assembly.GetEntryAssembly()` first because
// `DependencyContext.Default` throws an exception when `Assembly.GetEntryAssembly()` returns null
if (Assembly.GetEntryAssembly() != null && DependencyContext.Default != null)
var isBundled = entryAssembly.Location.Length == 0;
if (isBundled)
{
return new DependencyContextAssemblyFinder(DependencyContext.Default);
using var depsJsonStream = SingleFileApplication.GetDepsJsonStream();
if (depsJsonStream != null)
{
using var depsJsonReader = new DependencyContextJsonReader();
var dependencyContext = depsJsonReader.Read(depsJsonStream);
return new DependencyContextAssemblyFinder(dependencyContext);
}
}

var entryAssemblyContext = DependencyContext.Load(entryAssembly);
if (entryAssemblyContext != null)
{
return new DependencyContextAssemblyFinder(entryAssemblyContext);
}
}
catch (NotSupportedException) when (typeof(object).Assembly.Location is "") // bundled mode detection
{
}


return new DllScanningAssemblyFinder();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;

namespace Serilog.Settings.Configuration.Assemblies
{
static class SingleFileApplication
{
static byte[] bundleSignature =
{
// 32 bytes represent the bundle signature: SHA-256 for ".net core bundle"
// The first byte is actually 0x8b but we don't want to accidentally have a second place where the bundle
// signature can appear in the single file application so the first byte is set in the static constructor
// See https://github.com/dotnet/runtime/blob/v6.0.3/src/installer/managed/Microsoft.NET.HostModel/AppHost/HostWriter.cs#L216-L222
0x00, 0x12, 0x02, 0xb9, 0x6a, 0x61, 0x20, 0x38, 0x72, 0x7b, 0x93, 0x02, 0x14, 0xd7, 0xa0, 0x32,
0x13, 0xf5, 0xb9, 0xe6, 0xef, 0xae, 0x33, 0x18, 0xee, 0x3b, 0x2d, 0xce, 0x24, 0xb3, 0x6a, 0xae
};

static SingleFileApplication()
{
bundleSignature[0] = 0x8b;
}

public static Stream GetDepsJsonStream()
{
var appHostPath = Process.GetCurrentProcess().MainModule?.FileName;
if (appHostPath == null)
{
return null;
}

using var appHostFile = MemoryMappedFile.CreateFromFile(appHostPath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read);
using Stream appHostStream = appHostFile.CreateViewStream(0, 0, MemoryMappedFileAccess.Read);
var bundleSignatureIndex = SearchBundleSignature(appHostStream);
if (bundleSignatureIndex == -1)
{
return null;
}

using var appHostReader = new BinaryReader(appHostStream);
appHostReader.BaseStream.Position = bundleSignatureIndex - 8;
var bundleHeaderOffset = appHostReader.ReadInt64();
if (bundleHeaderOffset <= 0 || bundleHeaderOffset >= appHostStream.Length)
{
return null;
}

// See https://github.com/dotnet/runtime/blob/v6.0.3/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs#L32-L39
// and https://github.com/dotnet/runtime/blob/v6.0.3/src/installer/managed/Microsoft.NET.HostModel/Bundle/Manifest.cs#L144-L155
appHostReader.BaseStream.Position = bundleHeaderOffset;
var majorVersion = appHostReader.ReadUInt32();
_ = appHostReader.ReadUInt32(); // minorVersion
var numEmbeddedFiles = appHostReader.ReadInt32();
_ = appHostReader.ReadString(); // bundleId
if (majorVersion >= 2)
{
var depsJsonOffset = appHostReader.ReadInt64();
var depsJsonSize = appHostReader.ReadInt64();
return appHostFile.CreateViewStream(depsJsonOffset, depsJsonSize, MemoryMappedFileAccess.Read);
}

// For version < 2 all the file entries must be enumerated until the `DepsJson` type is found
// See https://github.com/dotnet/runtime/blob/v6.0.3/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileEntry.cs#L43-L54
for (var i = 0; i < numEmbeddedFiles; i++)
{
var offset = appHostReader.ReadInt64();
var size = appHostReader.ReadInt64();
var type = appHostReader.ReadByte();
_ = appHostReader.ReadString(); // relativePath
if (type == 3)
{
// type 3 is the .deps.json configuration file
// See https://github.com/dotnet/runtime/blob/v6.0.3/src/installer/managed/Microsoft.NET.HostModel/Bundle/FileType.cs#L17
return appHostFile.CreateViewStream(offset, size, MemoryMappedFileAccess.Read);
}
}

return null;
}

static int SearchBundleSignature(Stream stream)
{
var m = 0;
var i = 0;

var length = stream.Length;
while (m + i < length)
{
stream.Position = m + i;
if (bundleSignature[i] == stream.ReadByte())
{
if (i == bundleSignature.Length - 1)
{
return m;
}
i++;
}
else
{
m += i == 0 ? 1 : i;
i = 0;
}
}

return -1;
}
}
}
50 changes: 50 additions & 0 deletions test/Serilog.Settings.Configuration.Tests/SingleFileAppTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Serilog.Settings.Configuration.Tests.Support;
using Xunit;

namespace Serilog.Settings.Configuration.Tests
{
public class SingleFileAppTest
{
[Theory]
[InlineData(true)]
[InlineData(false)]
void SingleFileApp(bool includeAllContentForSelfExtract)
{
var testDirectory = new DirectoryInfo(GetCurrentFilePath()).Parent?.Parent ?? throw new DirectoryNotFoundException("Can't find the 'test' directory");
var workingDirectory = Path.Combine(testDirectory.FullName, "TestSingleFileApp");
var publishDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

try
{
ProcessExtensions.RunDotnet(workingDirectory, "publish",
"-c", "Release",
$"-p:IncludeAllContentForSelfExtract={includeAllContentForSelfExtract.ToString().ToLower()}",
$"-p:CliBaseOutputPath={Path.Combine(publishDirectory, "bin" + Path.DirectorySeparatorChar)}",
$"-p:CliBaseIntermediateOutputPath={Path.Combine(publishDirectory, "obj" + Path.DirectorySeparatorChar)}",
"-o", publishDirectory);
var exeName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "TestSingleFileApp.exe" : "TestSingleFileApp";
var exePath = Path.Combine(publishDirectory, exeName);
var result = ProcessExtensions.RunCommand(exePath);

Assert.Matches("^$", result.Error);
Assert.Equal("Everything is working as expected", result.Output);
}
finally
{
try
{
Directory.Delete(publishDirectory, recursive: true);
}
catch
{
// Don't hide the actual exception, if any
}
}
}

static string GetCurrentFilePath([CallerFilePath] string path = "") => path;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Serilog.Settings.Configuration.Tests.Support
{
public static class ProcessExtensions
{
public struct CommandResult
{
public CommandResult(string output, string error)
{
Output = output;
Error = error;
}

public string Output { get; }
public string Error { get; }
}

public static void RunDotnet(string workingDirectory, params string[] args)
{
RunCommand("dotnet", workingDirectory, args);
}

public static CommandResult RunCommand(string command, params string[] args)
{
return RunCommand(command, "", args);
}

static CommandResult RunCommand(string command, string workingDirectory, params string[] args)
{
var arguments = new StringBuilder(args.Select(e => e.Length + 3).Sum());
foreach (var arg in args)
{
var hasSpace = arg.Contains(" ");
if (hasSpace) arguments.Append('"');
arguments.Append(arg);
if (hasSpace) arguments.Append('"');
arguments.Append(' ');
}
var startInfo = new ProcessStartInfo(command, arguments.ToString())
{
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
var process = new Process { StartInfo = startInfo };
process.Start();
var timeout = TimeSpan.FromSeconds(30);
var exited = process.WaitForExit((int)timeout.TotalMilliseconds);
if (!exited)
{
process.Kill();
throw new TimeoutException($"The command '{command} {arguments}' did not execute within {timeout.TotalSeconds} seconds");
}

var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError.ReadToEnd();
if (process.ExitCode != 0)
{
var message = new StringBuilder();
message.AppendLine($"The command '{command} {arguments}' exited with code {process.ExitCode}");
if (output.Length > 0)
{
message.AppendLine("*** Output ***");
message.AppendLine(output);
}
if (error.Length > 0)
{
message.AppendLine("*** Error ***");
message.AppendLine(error);
}
throw new InvalidOperationException(message.ToString());
}

return new CommandResult(output, error);
}
}
}
6 changes: 6 additions & 0 deletions test/TestSingleFileApp/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Project>
<PropertyGroup>
<BaseOutputPath Condition="$(MSBuildProjectName) == 'TestSingleFileApp' AND $(CliBaseOutputPath) != ''">$(CliBaseOutputPath)</BaseOutputPath>
<BaseIntermediateOutputPath Condition="$(MSBuildProjectName) == 'TestSingleFileApp' AND $(CliBaseIntermediateOutputPath) != ''">$(CliBaseIntermediateOutputPath)</BaseIntermediateOutputPath>
</PropertyGroup>
</Project>
24 changes: 24 additions & 0 deletions test/TestSingleFileApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Debugging;

try
{
SelfLog.Enable(text => Console.Error.WriteLine(text));

var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
{
["Serilog:WriteTo:0:Name"] = "InMemory",
["Serilog:WriteTo:1:Name"] = "Console",
["Serilog:WriteTo:1:Args:outputTemplate"] = "{Message:l}",
}).Build();

using var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
logger.Information("Everything is working as expected");
}
catch (Exception exception)
{
Console.Error.WriteLine($"An unexpected exception occurred: {exception}");
}
34 changes: 34 additions & 0 deletions test/TestSingleFileApp/TestSingleFileApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup>
<DebugType>embedded</DebugType>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>false</SelfContained>
</PropertyGroup>

<PropertyGroup Condition="$([MSBuild]::VersionGreaterThanOrEquals('$(NETCoreSdkVersion)', '6.0'))">
<UseCurrentRuntimeIdentifier>true</UseCurrentRuntimeIdentifier>
</PropertyGroup>

<PropertyGroup Condition="!$([MSBuild]::VersionGreaterThanOrEquals('$(NETCoreSdkVersion)', '6.0'))">
<RuntimeIdentifier Condition="$([MSBuild]::IsOSPlatform('Linux'))">linux-x64</RuntimeIdentifier>
<RuntimeIdentifier Condition="$([MSBuild]::IsOSPlatform('OSX'))">osx-x64</RuntimeIdentifier>
<RuntimeIdentifier Condition="$([MSBuild]::IsOSPlatform('Windows'))">win-x64</RuntimeIdentifier>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.Settings.Configuration\Serilog.Settings.Configuration.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.InMemory" Version="0.6.0" />
</ItemGroup>

</Project>
Loading