mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
9 changed files with 768360 additions and 0 deletions
250
brutal.monitor/Brutal.Monitor.Common/CrashTail.cs
Normal file
250
brutal.monitor/Brutal.Monitor.Common/CrashTail.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
using System.Buffers;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Text;
|
||||
using System.Text.Unicode;
|
||||
|
||||
namespace Brutal.Monitor.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Ring buffer of the most recent log lines in a memory-mapped file, so the log tail
|
||||
/// survives a crash that kills the host before it flushes. Written by the host, read by
|
||||
/// the monitor subprocess.
|
||||
/// </summary>
|
||||
internal sealed class CrashTailRing : IDisposable
|
||||
{
|
||||
// Layout: header, then slotCount slots of [long seq][int length][utf8 payload]
|
||||
internal const long Magic = 0x4C49_4154_5242_4D42;
|
||||
internal const int Version = 1;
|
||||
internal const int HeaderSize = 64;
|
||||
internal const int SlotHeaderSize = 12;
|
||||
|
||||
internal const int DefaultSlotCount = 1024;
|
||||
|
||||
// A logged exception's stack trace runs to several KB, and a clipped one is worth little here
|
||||
internal const int DefaultSlotSize = 4096;
|
||||
|
||||
// Kept at the end of a slot so a clipped line says so rather than looking complete
|
||||
private static ReadOnlySpan<byte> TruncatedMarker => " [truncated]"u8;
|
||||
|
||||
private readonly MemoryMappedFile _file;
|
||||
private readonly MemoryMappedViewAccessor _accessor;
|
||||
private readonly int _slotCount;
|
||||
private readonly int _slotSize;
|
||||
private long _sequence;
|
||||
private int _disposed;
|
||||
|
||||
// Set when the host is dying, so disposal leaves the tail behind instead of retiring it
|
||||
private volatile bool _preserve;
|
||||
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>Total records ever written; the ring holds the most recent SlotCount.</summary>
|
||||
public long Sequence => Interlocked.Read(ref _sequence);
|
||||
|
||||
public int SlotCount => _slotCount;
|
||||
public int SlotSize => _slotSize;
|
||||
|
||||
public CrashTailRing(string filePath, int slotCount = DefaultSlotCount, int slotSize = DefaultSlotSize)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(slotCount, 1);
|
||||
|
||||
// A slot has to hold its header, the truncation marker and some of a line
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(slotSize, SlotHeaderSize + TruncatedMarker.Length + 1);
|
||||
|
||||
FilePath = filePath;
|
||||
_slotCount = slotCount;
|
||||
_slotSize = slotSize;
|
||||
|
||||
// Shared so the subprocess can map the ring while we hold it open
|
||||
var stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
var size = HeaderSize + (long)slotCount * slotSize;
|
||||
_file = MemoryMappedFile.CreateFromFile(
|
||||
stream,
|
||||
null,
|
||||
size,
|
||||
MemoryMappedFileAccess.ReadWrite,
|
||||
HandleInheritability.None,
|
||||
leaveOpen: false
|
||||
);
|
||||
_accessor = _file.CreateViewAccessor();
|
||||
|
||||
_accessor.Write(0, Magic);
|
||||
_accessor.Write(8, Version);
|
||||
_accessor.Write(12, slotCount);
|
||||
_accessor.Write(16, slotSize);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write a log line straight into the mapped memory, allocation-free and safe from any
|
||||
/// thread. A writer preempted for a full ring of messages can cost one line of tail.
|
||||
/// </summary>
|
||||
public unsafe void Write(string message)
|
||||
{
|
||||
var seq = Interlocked.Increment(ref _sequence);
|
||||
var slot = (int)((seq - 1) % _slotCount);
|
||||
var offset = HeaderSize + (long)slot * _slotSize;
|
||||
|
||||
// Acquire/Release pins the mapping so a concurrent Dispose can't pull it from under us
|
||||
var handle = _accessor.SafeMemoryMappedViewHandle;
|
||||
byte* pointer = null;
|
||||
handle.AcquirePointer(ref pointer);
|
||||
try
|
||||
{
|
||||
// Seqlock write: invalidate the slot, fill it, then publish the new sequence
|
||||
var slotPointer = pointer + _accessor.PointerOffset + offset;
|
||||
|
||||
// Full-fence store, so the payload below cannot reorder ahead of the invalidation
|
||||
Interlocked.Exchange(ref *(long*)slotPointer, 0);
|
||||
|
||||
// Encoded short of the marker's room, so a clipped line is marked instead of lost quietly
|
||||
var payload = new Span<byte>(slotPointer + SlotHeaderSize, _slotSize - SlotHeaderSize);
|
||||
var status = Utf8.FromUtf16(message, payload[..^TruncatedMarker.Length], out _, out var length);
|
||||
if (status == OperationStatus.DestinationTooSmall)
|
||||
{
|
||||
TruncatedMarker.CopyTo(payload[length..]);
|
||||
length += TruncatedMarker.Length;
|
||||
}
|
||||
|
||||
*(int*)(slotPointer + 8) = length;
|
||||
|
||||
// No barrier needed here: this release store already orders the payload ahead of itself
|
||||
Volatile.Write(ref *(long*)slotPointer, seq);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handle.ReleasePointer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keep the ring on disposal, so a crash unwinding through the host's cleanup leaves its tail.</summary>
|
||||
public void Preserve()
|
||||
{
|
||||
_preserve = true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Idempotent - shutdown paths can overlap, and a second pass must not throw
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
// Only a clean exit retires the tail; a crash leaves it readable for the next run
|
||||
if (!_preserve)
|
||||
{
|
||||
// Invalidated first so nothing can be recovered even if the delete below fails
|
||||
try
|
||||
{
|
||||
_accessor.Write(0, 0L);
|
||||
_accessor.Flush();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
_accessor.Dispose();
|
||||
_file.Dispose();
|
||||
|
||||
if (_preserve)
|
||||
return;
|
||||
|
||||
// Best effort - if the subprocess still maps it, the next instance's sweep removes it
|
||||
try
|
||||
{
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a CrashTailRing and writes its surviving records, oldest first, as plain text,
|
||||
/// under a header saying how many lines these are and where the full log lives.
|
||||
/// </summary>
|
||||
public static class CrashTailSnapshot
|
||||
{
|
||||
/// <summary>Nothing to recover: the ring is missing, foreign, or was cleanly retired.</summary>
|
||||
public const int NoTail = -1;
|
||||
|
||||
/// <summary>The snapshot failed, so the ring may still hold a recoverable tail.</summary>
|
||||
public const int SnapshotFailed = -2;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the number of log lines recovered, NoTail, or SnapshotFailed. Writes no file
|
||||
/// when there is nothing to recover.
|
||||
/// </summary>
|
||||
public static int TryWrite(string ringPath, string outputPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(ringPath))
|
||||
return NoTail;
|
||||
|
||||
using var stream = new FileStream(ringPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var file = MemoryMappedFile.CreateFromFile(
|
||||
stream,
|
||||
null,
|
||||
0,
|
||||
MemoryMappedFileAccess.Read,
|
||||
HandleInheritability.None,
|
||||
leaveOpen: false
|
||||
);
|
||||
using var accessor = file.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
|
||||
|
||||
if (accessor.ReadInt64(0) != CrashTailRing.Magic || accessor.ReadInt32(8) != CrashTailRing.Version)
|
||||
return NoTail;
|
||||
var slotCount = accessor.ReadInt32(12);
|
||||
var slotSize = accessor.ReadInt32(16);
|
||||
if (slotCount <= 0 || slotSize <= CrashTailRing.SlotHeaderSize)
|
||||
return NoTail;
|
||||
|
||||
var records = new List<(long Seq, string Line)>(slotCount);
|
||||
var payload = new byte[slotSize - CrashTailRing.SlotHeaderSize];
|
||||
|
||||
for (int slot = 0; slot < slotCount; slot++)
|
||||
{
|
||||
var offset = CrashTailRing.HeaderSize + (long)slot * slotSize;
|
||||
|
||||
// Seqlock read: a slot whose seq moves under us is mid-write, so skip it
|
||||
var seqBefore = accessor.ReadInt64(offset);
|
||||
if (seqBefore <= 0)
|
||||
continue;
|
||||
|
||||
// The seq read must land before the payload reads, or a torn line can pass the recheck
|
||||
Thread.MemoryBarrier();
|
||||
|
||||
var length = accessor.ReadInt32(offset + 8);
|
||||
if (length <= 0 || length > payload.Length)
|
||||
continue;
|
||||
|
||||
accessor.ReadArray(offset + CrashTailRing.SlotHeaderSize, payload, 0, length);
|
||||
Thread.MemoryBarrier();
|
||||
if (accessor.ReadInt64(offset) != seqBefore)
|
||||
continue;
|
||||
|
||||
records.Add((seqBefore, Encoding.UTF8.GetString(payload, 0, length)));
|
||||
}
|
||||
|
||||
records.Sort((a, b) => a.Seq.CompareTo(b.Seq));
|
||||
|
||||
// An empty file would read as a lost tail rather than no tail
|
||||
if (records.Count == 0)
|
||||
return 0;
|
||||
|
||||
using var writer = File.CreateText(outputPath);
|
||||
|
||||
// These are only the last lines of a run, so say so and point at the whole log
|
||||
var logName = Path.GetFileNameWithoutExtension(ringPath);
|
||||
writer.WriteLine($"[Brutal.Monitor] the most recent {records.Count} log lines - full history in {logName}");
|
||||
|
||||
foreach (var record in records)
|
||||
writer.WriteLine(record.Line);
|
||||
|
||||
return records.Count;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Best effort - a failed snapshot must never break dump collection
|
||||
return SnapshotFailed;
|
||||
}
|
||||
}
|
||||
}
|
||||
74
brutal.monitor/Brutal.Monitor.Common/MonitorFileNames.cs
Normal file
74
brutal.monitor/Brutal.Monitor.Common/MonitorFileNames.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Brutal.Monitor.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Naming shared by everything one run produces: every file carries "<name>.<start time>.<pid>",
|
||||
/// so a dump can be matched to its log and instances or reused pids never collide.
|
||||
/// </summary>
|
||||
internal static class MonitorFileNames
|
||||
{
|
||||
// Local time; the dash keeps a run's suffix distinct from an archive's all-numeric "<yyMMdd>.<index>"
|
||||
internal const string StampFormat = "yyMMdd-HHmmss";
|
||||
|
||||
/// <summary>This process's start time as a stamp; the subprocess is handed the host's, never its own.</summary>
|
||||
public static string ProcessStamp { get; } = Stamp(CurrentProcessStart());
|
||||
|
||||
/// <summary>One run's file stem: "<name>.<stamp>.<pid>", the identity all its files carry.</summary>
|
||||
public static string Stem(string name, string stamp, int processId)
|
||||
{
|
||||
return $"{name}.{stamp}.{processId}";
|
||||
}
|
||||
|
||||
/// <summary>Format a start time as a stem's timestamp part.</summary>
|
||||
public static string Stamp(DateTime startTime)
|
||||
{
|
||||
return startTime.ToString(StampFormat, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>True when this suffix part is a run stamp, so stray files never parse as runs.</summary>
|
||||
public static bool IsStamp(string part)
|
||||
{
|
||||
return DateTime.TryParseExact(part, StampFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dot-separated parts following "<name>." in a file's name, or null when the file
|
||||
/// doesn't belong to that name. Directory globs are not enough on their own, since
|
||||
/// "Gruntz.*" also matches Gruntz.client's files.
|
||||
/// </summary>
|
||||
public static string[]? OwnedSuffix(string fileName, string name)
|
||||
{
|
||||
var stem = Path.GetFileNameWithoutExtension(fileName);
|
||||
if (!stem.StartsWith(name + ".", StringComparison.Ordinal))
|
||||
return null;
|
||||
|
||||
return stem[(name.Length + 1)..].Split('.');
|
||||
}
|
||||
|
||||
/// <summary>Match an archive named "<name>.<yyMMdd>.<index>".</summary>
|
||||
public static bool TryParseArchive(string fileName, string name, out int timeStamp, out int index)
|
||||
{
|
||||
timeStamp = 0;
|
||||
index = 0;
|
||||
|
||||
return OwnedSuffix(fileName, name) is { Length: 2 } suffix
|
||||
&& int.TryParse(suffix[0], out timeStamp)
|
||||
&& int.TryParse(suffix[1], out index);
|
||||
}
|
||||
|
||||
private static DateTime CurrentProcessStart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetCurrentProcess();
|
||||
return process.StartTime;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A start time the OS will not give still has to name this run's files
|
||||
return DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
20
brutal.monitor/Brutal.Monitor.Common/ProcessExtension.cs
Normal file
20
brutal.monitor/Brutal.Monitor.Common/ProcessExtension.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.Monitor.Common
|
||||
{
|
||||
internal static class ProcessExtension
|
||||
{
|
||||
public static void WriteLineSync(this Process process, string line)
|
||||
{
|
||||
// Called from crash handlers, so a dead child's broken pipe must never throw
|
||||
try
|
||||
{
|
||||
lock (process.StandardInput)
|
||||
process.StandardInput.WriteLine(line);
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (ObjectDisposedException) { }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
106
brutal.monitor/Brutal.Monitor.Common/ProcessResponseReader.cs
Normal file
106
brutal.monitor/Brutal.Monitor.Common/ProcessResponseReader.cs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.Monitor.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Reads tagged response lines from a child process on its own thread and hands them out by
|
||||
/// command name. Waiting is a memory poll against a deadline, so a silent child can never
|
||||
/// block the caller the way reading the stream directly would. Each command has its own
|
||||
/// slot, so concurrent waiters cannot consume each other's replies.
|
||||
/// </summary>
|
||||
internal sealed class ProcessResponseReader : IDisposable
|
||||
{
|
||||
private const int PollMs = 5;
|
||||
|
||||
private readonly Process _process;
|
||||
private readonly ConcurrentDictionary<string, string> _responses = new(StringComparer.Ordinal);
|
||||
private readonly Thread _thread;
|
||||
private volatile bool _stopping;
|
||||
|
||||
// Set once stdout is closed, so waiters stop counting down a deadline nothing will answer
|
||||
private volatile bool _finished;
|
||||
|
||||
public ProcessResponseReader(Process process)
|
||||
{
|
||||
_process = process;
|
||||
_thread = new Thread(ReadLoop) { Name = "Brutal.Monitor.ResponseReader", IsBackground = true };
|
||||
_thread.Start();
|
||||
}
|
||||
|
||||
private void ReadLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_stopping)
|
||||
{
|
||||
// Blocks here, not in the caller, and ends when the child closes stdout
|
||||
var line = _process.StandardOutput.ReadLine();
|
||||
if (line is null)
|
||||
break;
|
||||
|
||||
if (TrySplitResponse(line, out var command, out var response))
|
||||
_responses[command] = response;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// The child went away mid-read; waiters give up as soon as they see this
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Published after any final response, so a waiter that sees this still finds it
|
||||
_finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Split "FirstChance OK path" into its command tag and the rest.
|
||||
/// </summary>
|
||||
internal static bool TrySplitResponse(string? line, out string command, out string response)
|
||||
{
|
||||
command = string.Empty;
|
||||
response = string.Empty;
|
||||
if (string.IsNullOrEmpty(line))
|
||||
return false;
|
||||
|
||||
var space = line.IndexOf(' ');
|
||||
if (space < 0)
|
||||
{
|
||||
command = line;
|
||||
return true;
|
||||
}
|
||||
|
||||
command = line[..space];
|
||||
response = line[(space + 1)..];
|
||||
return command.Length > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wait for this command's response, or null if none arrived before the timeout. Returns
|
||||
/// as soon as the child closes stdout, so a dead subprocess costs no wait at all.
|
||||
/// </summary>
|
||||
public string? WaitFor(string command, int timeOut)
|
||||
{
|
||||
var deadline = Environment.TickCount64 + timeOut;
|
||||
while (true)
|
||||
{
|
||||
if (_responses.TryRemove(command, out var response))
|
||||
return response;
|
||||
|
||||
// A closed stdout or a disposed reader will never answer, so the rest of the deadline is a pure stall
|
||||
if (_finished || _stopping)
|
||||
return _responses.TryRemove(command, out var last) ? last : null;
|
||||
|
||||
if (Environment.TickCount64 >= deadline)
|
||||
return null;
|
||||
|
||||
Thread.Sleep(PollMs);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stopping = true;
|
||||
}
|
||||
}
|
||||
48
brutal.monitor/Brutal.Monitor.Common/Shared.cs
Normal file
48
brutal.monitor/Brutal.Monitor.Common/Shared.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
namespace Brutal.Monitor.Common;
|
||||
|
||||
public enum DumpType
|
||||
{
|
||||
None = 0,
|
||||
Triage,
|
||||
Mini,
|
||||
Full,
|
||||
Heap,
|
||||
}
|
||||
|
||||
public struct CollectorOptions
|
||||
{
|
||||
/// <summary>Directory dumps are written under, in FirstChance and LastChance subfolders. Must already exist.</summary>
|
||||
public string DumpPath = "";
|
||||
|
||||
public DumpType FirstChance = DumpType.None;
|
||||
public DumpType LastChance = DumpType.None;
|
||||
|
||||
public int KeepCount = 5; // number of dumps to keep
|
||||
|
||||
/// <summary>
|
||||
/// Milliseconds allowed for writing a crash dump, which a dying host waits out.
|
||||
/// </summary>
|
||||
public int DumpTimeoutMs = 60000;
|
||||
|
||||
public CollectorOptions() { }
|
||||
}
|
||||
|
||||
public struct LoggerOptions
|
||||
{
|
||||
/// <summary>Directory the log file ("<name>.<stamp>.<pid>.log") is created in. Must already exist.</summary>
|
||||
public string LogDirectory = "";
|
||||
|
||||
/// <summary>
|
||||
/// How often buffered log lines are flushed to the OS page cache, bounding what a hard
|
||||
/// crash loses from the log file. Floors at 100ms.
|
||||
/// </summary>
|
||||
public int FlushIntervalMs = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Archived logs and recovered crash tails to retain per name. Zero keeps every one,
|
||||
/// which grows without bound, so the default is a real number a shipped game can live with.
|
||||
/// </summary>
|
||||
public int MaxArchives = 10;
|
||||
|
||||
public LoggerOptions() { }
|
||||
}
|
||||
|
|
@ -0,0 +1,516 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Threading.Channels;
|
||||
using Brutal.Monitor.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Monitor.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Writes log lines to file from a background thread fed by a bounded channel, so a log
|
||||
/// call only ever touches memory. On overflow the oldest lines are dropped and counted.
|
||||
/// Custom formatting runs on the writer thread, never the caller's.
|
||||
/// </summary>
|
||||
internal sealed class BackgroundLogWriter : IDisposable
|
||||
{
|
||||
private const int QueueCapacity = 8192;
|
||||
private const int DrainWaitMs = 100;
|
||||
|
||||
// Platform newline as UTF-8, appended after each encoded line
|
||||
private static readonly byte[] NewLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
|
||||
|
||||
// A raw line (null category) skips the formatter: markers and recovery notes
|
||||
private readonly record struct Entry(LogLevel Level, string? Category, string Message);
|
||||
|
||||
private readonly Channel<Entry> _queue;
|
||||
|
||||
private FileStream? _file;
|
||||
private byte[] _lineBuffer = new byte[8192]; // Writer-thread only, grown geometrically to fit the largest line seen
|
||||
private Thread? _thread;
|
||||
private long _totalDropped;
|
||||
private long _reportedDropped; // Writer-thread only: drops already reported into the log
|
||||
private long _linesWritten;
|
||||
private long _bytesWritten;
|
||||
private long _linesDiscarded; // Writer-thread only: lines drained with no file to take them
|
||||
private volatile bool _writerFailed;
|
||||
private int _disposed;
|
||||
|
||||
public BackgroundLogWriter()
|
||||
{
|
||||
// DropOldest counts each eviction, and a completed channel refuses writes quietly.
|
||||
// One atomic per drop: the writer thread works out what is new to report from the total
|
||||
_queue = Channel.CreateBounded<Entry>(
|
||||
new BoundedChannelOptions(QueueCapacity)
|
||||
{
|
||||
FullMode = BoundedChannelFullMode.DropOldest,
|
||||
SingleReader = true,
|
||||
},
|
||||
_ => Interlocked.Increment(ref _totalDropped)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>Lines waiting for the writer thread, cheap enough to poll per frame.</summary>
|
||||
public int QueueDepth => _queue.Reader.Count;
|
||||
|
||||
/// <summary>Lines the queue holds before the oldest are dropped.</summary>
|
||||
public int Capacity => QueueCapacity;
|
||||
|
||||
/// <summary>Lines written to the log file so far.</summary>
|
||||
public long LinesWritten => Interlocked.Read(ref _linesWritten);
|
||||
|
||||
/// <summary>UTF-8 bytes written to the log file so far.</summary>
|
||||
public long BytesWritten => Interlocked.Read(ref _bytesWritten);
|
||||
|
||||
/// <summary>Lines lost to queue overflow so far.</summary>
|
||||
public long LinesDropped => Interlocked.Read(ref _totalDropped);
|
||||
|
||||
/// <summary>Lines that reached the writer thread with no log file to take them.</summary>
|
||||
public long LinesDiscarded => Interlocked.Read(ref _linesDiscarded);
|
||||
|
||||
/// <summary>True once the log file was given up after a write or flush failure.</summary>
|
||||
public bool WriterFailed => _writerFailed;
|
||||
|
||||
/// <summary>Queue a raw line. Never blocks or throws; drops the oldest line when full.</summary>
|
||||
public void Add(string message)
|
||||
{
|
||||
_queue.Writer.TryWrite(new Entry(LogLevel.None, null, message));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a log message. Formatting happens later on the writer thread.
|
||||
/// </summary>
|
||||
public void Add(LogLevel level, string category, string message)
|
||||
{
|
||||
_queue.Writer.TryWrite(new Entry(level, category, message));
|
||||
}
|
||||
|
||||
/// <summary>Path being written to. Null if no file could be opened.</summary>
|
||||
public string? LogFilePath { get; private set; }
|
||||
|
||||
/// <summary>Optional line formatter, read on the writer thread so it never costs a caller.</summary>
|
||||
public Func<LogLevel, string, string, string>? LogFormatter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Sweep dead runs' leftovers, then open this run's log file ("<name>.<stamp>.<pid>.log")
|
||||
/// and start the writer thread. The directory must already exist.
|
||||
/// </summary>
|
||||
public void Open(LoggerOptions options, string name)
|
||||
{
|
||||
if (_thread is not null)
|
||||
throw new InvalidOperationException("BackgroundLogWriter is already open");
|
||||
|
||||
// The caller creates the directory; resolved to a full path so the subprocess's own cwd never matters
|
||||
var directory = Path.GetFullPath(options.LogDirectory);
|
||||
if (!Directory.Exists(directory))
|
||||
throw new DirectoryNotFoundException($"Log directory '{directory}' does not exist.");
|
||||
|
||||
// Nothing past this point may throw into startup; housekeeping is best effort
|
||||
try
|
||||
{
|
||||
SweepDeadRuns(directory, name, options.MaxArchives);
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
var stem = MonitorFileNames.Stem(name, MonitorFileNames.ProcessStamp, Environment.ProcessId);
|
||||
var logFilePath = Path.Combine(directory, $"{stem}.log");
|
||||
try
|
||||
{
|
||||
// Unix would let the open succeed on a held file, so ownership is probed explicitly
|
||||
if (File.Exists(logFilePath) && !LogArchiver.IsUnheld(logFilePath))
|
||||
throw new IOException($"{logFilePath} already has a live writer");
|
||||
|
||||
// A raw stream: lines are encoded to UTF-8 once here, so a StreamWriter would only re-encode
|
||||
_file = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read);
|
||||
LogFilePath = logFilePath;
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
|
||||
var flushInterval = Math.Max(options.FlushIntervalMs, DrainWaitMs);
|
||||
_thread = new Thread(() => WriteLoop(flushInterval)) { Name = "Brutal.Monitor.LogWriter", IsBackground = true };
|
||||
_thread.Start();
|
||||
|
||||
// Hosts that never dispose the Monitor would otherwise lose the queue tail
|
||||
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
|
||||
}
|
||||
|
||||
private void OnProcessExit(object? sender, EventArgs e)
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recover dead runs' crash tails and archive their logs; files held by a live holder are left alone.
|
||||
/// </summary>
|
||||
private void SweepDeadRuns(string directory, string name, int maxArchives)
|
||||
{
|
||||
foreach (var ring in Directory.GetFiles(directory, $"{name}.*.ring"))
|
||||
{
|
||||
// A ring is named <name>.<stamp>.<pid>.log.ring, so two extensions off gives the stem
|
||||
var stem = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(ring));
|
||||
if (!IsRunFile(stem + ".log", name) || !LogArchiver.IsUnheld(ring))
|
||||
continue;
|
||||
|
||||
var recovered = CrashTailSnapshot.TryWrite(ring, Path.Combine(directory, $"{stem}.previous-crash.log"));
|
||||
if (recovered > 0)
|
||||
Add($"[Brutal.Monitor] recovered {recovered} log lines from {Path.GetFileName(ring)}");
|
||||
|
||||
// A failed snapshot leaves the only copy of the tail in the ring; keep it for the next run to retry
|
||||
if (recovered == CrashTailSnapshot.SnapshotFailed)
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(ring);
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
foreach (var log in Directory.GetFiles(directory, $"{name}.*.log"))
|
||||
{
|
||||
// A locked log fails rotation and belongs to a live instance anyway
|
||||
if (IsRunFile(log, name))
|
||||
LogArchiver.TryRotate(log, name, maxArchives);
|
||||
}
|
||||
|
||||
PruneRecoveredTails(directory, name, maxArchives);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tails recovered from dead runs pile up beside the logs, so they get the same retention
|
||||
/// as archives: the newest maxArchives are kept, and zero keeps every one.
|
||||
/// </summary>
|
||||
private static void PruneRecoveredTails(string directory, string name, int maxArchives)
|
||||
{
|
||||
if (maxArchives <= 0)
|
||||
return;
|
||||
|
||||
var tails = new List<FileInfo>();
|
||||
foreach (var path in Directory.GetFiles(directory, $"{name}.*.log"))
|
||||
{
|
||||
if (IsRecoveredTail(path, name))
|
||||
tails.Add(new FileInfo(path));
|
||||
}
|
||||
|
||||
foreach (var expired in tails.OrderByDescending(tail => tail.LastWriteTimeUtc).Skip(maxArchives))
|
||||
{
|
||||
try
|
||||
{
|
||||
expired.Delete();
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
|
||||
// "<name>.<stamp>.<pid>.previous-crash.log" and "<name>.<stamp>.<pid>.<timestamp>.abnormal-exit.log"
|
||||
private static bool IsRecoveredTail(string fileName, string name)
|
||||
{
|
||||
return MonitorFileNames.OwnedSuffix(fileName, name) is { Length: >= 3 } suffix
|
||||
&& MonitorFileNames.IsStamp(suffix[0])
|
||||
&& int.TryParse(suffix[1], out _)
|
||||
&& suffix[^1] is "previous-crash" or "abnormal-exit";
|
||||
}
|
||||
|
||||
// Matches "<name>.<stamp>.<pid>" and nothing looser, so a stray user file is never archived
|
||||
private static bool IsRunFile(string fileName, string name)
|
||||
{
|
||||
return MonitorFileNames.OwnedSuffix(fileName, name) is { Length: 2 } suffix
|
||||
&& MonitorFileNames.IsStamp(suffix[0])
|
||||
&& int.TryParse(suffix[1], out _);
|
||||
}
|
||||
|
||||
private void WriteLoop(int flushInterval)
|
||||
{
|
||||
// Nothing may escape: an unhandled exception here would take the game down
|
||||
try
|
||||
{
|
||||
DrainLoop(flushInterval);
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally
|
||||
{
|
||||
// The writer thread owns closing the file, so a Dispose that gave up waiting can't leak it
|
||||
DisableWriter();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrainLoop(int flushInterval)
|
||||
{
|
||||
var reader = _queue.Reader;
|
||||
var pendingFlush = false;
|
||||
var lastFlush = Environment.TickCount64;
|
||||
|
||||
// One outstanding wait at a time, kept across timeouts so idle flushes still happen
|
||||
Task<bool>? waiting = null;
|
||||
while (true)
|
||||
{
|
||||
waiting ??= reader.WaitToReadAsync().AsTask();
|
||||
|
||||
// The timeout is only there to flush what is buffered, so an idle writer waits for a line
|
||||
var waitMs = pendingFlush ? DrainWaitMs : Timeout.Infinite;
|
||||
if (waiting.Wait(waitMs))
|
||||
{
|
||||
var hasLines = waiting.Result;
|
||||
waiting = null;
|
||||
if (!hasLines)
|
||||
break; // Completed and fully drained
|
||||
|
||||
// Bounded, so producers that outpace the writer can't starve the drop report and flush below
|
||||
var batch = 0;
|
||||
while (batch++ < QueueCapacity && reader.TryRead(out var entry))
|
||||
WriteLine(entry);
|
||||
pendingFlush = true;
|
||||
}
|
||||
|
||||
if (ReportDrops())
|
||||
pendingFlush = true;
|
||||
|
||||
// Flush is page-cache only, so a short cadence is cheap
|
||||
if (pendingFlush && Environment.TickCount64 - lastFlush >= flushInterval)
|
||||
{
|
||||
Flush();
|
||||
pendingFlush = false;
|
||||
lastFlush = Environment.TickCount64;
|
||||
}
|
||||
}
|
||||
|
||||
ReportDrops();
|
||||
Flush();
|
||||
}
|
||||
|
||||
private void WriteLine(in Entry entry)
|
||||
{
|
||||
// Counted, so a file that died mid-session shows in the stats instead of losing lines silently
|
||||
if (_file is null)
|
||||
{
|
||||
_linesDiscarded++;
|
||||
return;
|
||||
}
|
||||
|
||||
var line = FormatLine(entry);
|
||||
try
|
||||
{
|
||||
// One UTF-8 pass per line: encode into a reusable buffer, and the same pass yields the byte stat
|
||||
var maxBytes = Encoding.UTF8.GetMaxByteCount(line.Length) + NewLineBytes.Length;
|
||||
if (_lineBuffer.Length < maxBytes)
|
||||
{
|
||||
var doubled = (int)Math.Min((long)_lineBuffer.Length * 2, Array.MaxLength);
|
||||
_lineBuffer = new byte[Math.Max(maxBytes, doubled)];
|
||||
}
|
||||
|
||||
var byteCount = Encoding.UTF8.GetBytes(line.AsSpan(), _lineBuffer);
|
||||
NewLineBytes.CopyTo(_lineBuffer.AsSpan(byteCount));
|
||||
byteCount += NewLineBytes.Length;
|
||||
_file.Write(_lineBuffer, 0, byteCount);
|
||||
|
||||
// Only this thread writes these; readers take a whole 64-bit value via Interlocked.Read
|
||||
_linesWritten++;
|
||||
_bytesWritten += byteCount;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A full or disconnected disk gives up the file, not the process
|
||||
FailWriter();
|
||||
}
|
||||
}
|
||||
|
||||
private string FormatLine(in Entry entry)
|
||||
{
|
||||
// A custom formatter runs here so its strings never cost a game thread
|
||||
var formatter = LogFormatter;
|
||||
if (entry.Category is null || formatter is null)
|
||||
return entry.Message;
|
||||
|
||||
try
|
||||
{
|
||||
// A formatter returning null would otherwise disable the log file for good
|
||||
return formatter(entry.Level, entry.Category, entry.Message) ?? entry.Message;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A broken formatter costs its decoration, not the log
|
||||
return entry.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private void Flush()
|
||||
{
|
||||
try
|
||||
{
|
||||
_file?.Flush();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
FailWriter();
|
||||
}
|
||||
}
|
||||
|
||||
// A failure gives up the file like a normal close does, but leaves a mark the stats can show
|
||||
private void FailWriter()
|
||||
{
|
||||
_writerFailed = true;
|
||||
DisableWriter();
|
||||
}
|
||||
|
||||
// Give up on the log file and keep draining, so producers never block or throw
|
||||
private void DisableWriter()
|
||||
{
|
||||
var file = Interlocked.Exchange(ref _file, null);
|
||||
if (file is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
file.Dispose();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
// True when a report was written, since that line needs flushing like any other
|
||||
private bool ReportDrops()
|
||||
{
|
||||
var dropped = Interlocked.Read(ref _totalDropped) - _reportedDropped;
|
||||
if (dropped <= 0)
|
||||
return false;
|
||||
|
||||
WriteLine(new Entry(LogLevel.None, null, $"[Brutal.Monitor] dropped {dropped} log messages (queue overflow)"));
|
||||
_reportedDropped += dropped;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Idempotent - reached from both Monitor disposal and the ProcessExit hook
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
|
||||
_queue.Writer.TryComplete();
|
||||
|
||||
// Bounded so a stuck disk can't stall process exit; the writer thread closes the file either way
|
||||
if (_thread is null)
|
||||
DisableWriter();
|
||||
else
|
||||
_thread.Join(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a finished log into an Archives folder as <archive name>.yyMMdd.n.log,
|
||||
/// keeping at most maxArchives per name (zero keeps all).
|
||||
/// </summary>
|
||||
internal static class LogArchiver
|
||||
{
|
||||
// FileShare.None maps to an exclusive flock on Unix, so a live holder conflicts on every platform
|
||||
internal static bool IsUnheld(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var probe = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
return true;
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
// Deleted between the caller's existence check and this probe: no file, no holder
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns false when the log could not be archived, so the caller can move on.</summary>
|
||||
public static bool TryRotate(string logFilePath, string archiveName, int maxArchives)
|
||||
{
|
||||
try
|
||||
{
|
||||
Rotate(logFilePath, archiveName, maxArchives);
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Rotate(string logFilePath, string archiveName, int maxArchives)
|
||||
{
|
||||
if (!File.Exists(logFilePath))
|
||||
return;
|
||||
|
||||
// Unix happily renames an open file, so a held log must be refused here, not by the move
|
||||
if (!IsUnheld(logFilePath))
|
||||
throw new IOException($"{logFilePath} is held open by a live instance");
|
||||
|
||||
var directory = Path.GetDirectoryName(logFilePath)!;
|
||||
var currentFile = new FileInfo(logFilePath);
|
||||
var currentFileTimeStamp = currentFile.LastWriteTime.ToString("yyMMdd", CultureInfo.InvariantCulture);
|
||||
var archiveDirectory = Path.Combine(directory, "Archives");
|
||||
var extension = Path.GetExtension(logFilePath);
|
||||
|
||||
if (!Directory.Exists(archiveDirectory))
|
||||
Directory.CreateDirectory(archiveDirectory);
|
||||
|
||||
// Only this name's own archives, so names sharing a folder keep separate histories
|
||||
var archives = new List<(string Path, int TimeStamp, int Index)>();
|
||||
foreach (var path in Directory.GetFiles(archiveDirectory, $"{archiveName}.*{extension}"))
|
||||
{
|
||||
if (MonitorFileNames.TryParseArchive(path, archiveName, out var timeStamp, out var index))
|
||||
archives.Add((path, timeStamp, index));
|
||||
}
|
||||
archives.Sort((a, b) => a.TimeStamp != b.TimeStamp ? a.TimeStamp - b.TimeStamp : a.Index - b.Index);
|
||||
|
||||
// Suffix an index when today already has an archive
|
||||
var archiveIndex = 0;
|
||||
foreach (var archive in archives)
|
||||
{
|
||||
if (archive.TimeStamp.ToString("D6") == currentFileTimeStamp)
|
||||
archiveIndex = Math.Max(archiveIndex, archive.Index + 1);
|
||||
}
|
||||
|
||||
// Another instance sweeping the same folder can claim an index first, so a collision retries the next
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
var archivePath = Path.Combine(
|
||||
archiveDirectory,
|
||||
$"{archiveName}.{currentFileTimeStamp}.{archiveIndex}{extension}"
|
||||
);
|
||||
try
|
||||
{
|
||||
currentFile.MoveTo(archivePath);
|
||||
break;
|
||||
}
|
||||
catch (IOException) when (attempt < 5 && File.Exists(archivePath))
|
||||
{
|
||||
archiveIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
if (maxArchives <= 0)
|
||||
return;
|
||||
|
||||
// Counts the archive just added, so the folder settles at maxArchives
|
||||
var toDelete = archives.Count + 1 - maxArchives;
|
||||
for (int i = 0; i < toDelete && i < archives.Count; i++)
|
||||
{
|
||||
// A stale archive we cannot delete is not worth failing startup over
|
||||
try
|
||||
{
|
||||
File.Delete(archives[i].Path);
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
243
brutal.monitor/Brutal.Monitor.Host/Logging/MonitorLogger.cs
Normal file
243
brutal.monitor/Brutal.Monitor.Host/Logging/MonitorLogger.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
using Brutal.Monitor.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Monitor.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Provides the MonitorLogger. Messages are queued for the background writer and mirrored
|
||||
/// into the crash-tail ring, so a log call only ever touches memory.
|
||||
/// </summary>
|
||||
public class MonitorLoggerProvider : ILoggerProvider
|
||||
{
|
||||
private readonly BackgroundLogWriter _writer = new();
|
||||
private CrashTailRing? _tailRing;
|
||||
private volatile bool _disposed;
|
||||
|
||||
// Backed by an int so the hot-path read is a plain load rather than a property call on an enum field
|
||||
private volatile int _minimumLevel = (int)LogLevel.Trace;
|
||||
|
||||
public MonitorLoggerProvider() { }
|
||||
|
||||
public MonitorLoggerProvider(LogLevel minimumLevel)
|
||||
{
|
||||
MinimumLevel = minimumLevel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Messages below this level are dropped before anything is formatted, so trace spam
|
||||
/// costs a compare instead of a string, a ring write and a queue slot. Defaults to Trace.
|
||||
/// </summary>
|
||||
public LogLevel MinimumLevel
|
||||
{
|
||||
get => (LogLevel)_minimumLevel;
|
||||
set => _minimumLevel = (int)value;
|
||||
}
|
||||
|
||||
/// <summary>True when this level is worth building a message for.</summary>
|
||||
public bool IsEnabled(LogLevel level)
|
||||
{
|
||||
return level != LogLevel.None && (int)level >= _minimumLevel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optional formatter for log file lines, given the level, category and message. Runs on
|
||||
/// the background writer thread, so its strings never cost a game thread, and the
|
||||
/// crash-tail ring always gets the plain message. Set it before logging starts.
|
||||
/// </summary>
|
||||
public Func<LogLevel, string, string, string>? LogFormatter
|
||||
{
|
||||
get => _writer.LogFormatter;
|
||||
set => _writer.LogFormatter = value;
|
||||
}
|
||||
|
||||
/// <summary>Crash-tail ring path, once file logging is configured.</summary>
|
||||
public string? CrashTailPath => _tailRing?.FilePath;
|
||||
|
||||
/// <summary>This run's log file path, once file logging is configured.</summary>
|
||||
public string? LogFilePath => _writer.LogFilePath;
|
||||
|
||||
/// <summary>Counters for the logging pipeline, cheap enough to poll every frame.</summary>
|
||||
public MonitorLoggingStats GetStats()
|
||||
{
|
||||
return new MonitorLoggingStats
|
||||
{
|
||||
QueueDepth = _writer.QueueDepth,
|
||||
QueueCapacity = _writer.Capacity,
|
||||
LinesWritten = _writer.LinesWritten,
|
||||
BytesWritten = _writer.BytesWritten,
|
||||
LinesDropped = _writer.LinesDropped,
|
||||
LinesDiscarded = _writer.LinesDiscarded,
|
||||
WriterFailed = _writer.WriterFailed,
|
||||
RingSequence = _tailRing?.Sequence ?? 0,
|
||||
RingSlotCount = _tailRing?.SlotCount ?? 0,
|
||||
RingSlotSize = _tailRing?.SlotSize ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Open the log file and start the background writer, flushing anything already queued.
|
||||
/// Call once, during startup.
|
||||
/// </summary>
|
||||
public void Configure(LoggerOptions options, string name)
|
||||
{
|
||||
_writer.Open(options, name);
|
||||
|
||||
// The ring carries the log file's name, so the subprocess can match the two
|
||||
var logFilePath = _writer.LogFilePath;
|
||||
if (logFilePath is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
_tailRing = new CrashTailRing(logFilePath + ".ring");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Any unusable path or mapping loses the crash tail; none of it may fail startup
|
||||
_tailRing = null;
|
||||
}
|
||||
|
||||
// A host that exits without disposing must still retire the ring, or a clean exit reads as a crash next run
|
||||
if (_tailRing is not null)
|
||||
{
|
||||
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
|
||||
|
||||
// A crash unwinds through Dispose even without last-chance dumps, so the ring is preserved here too
|
||||
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnProcessExit(object? sender, EventArgs e)
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
// The subscription cannot be exercised in-process without dying, so tests call this directly
|
||||
internal void OnUnhandledException(object? sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
PreserveCrashTail();
|
||||
}
|
||||
|
||||
/// <summary>Keep this run's crash tail for the next run; a dying host unwinds through this disposal.</summary>
|
||||
internal void PreserveCrashTail()
|
||||
{
|
||||
_tailRing?.Preserve();
|
||||
}
|
||||
|
||||
public ILogger CreateLogger(string categoryName)
|
||||
{
|
||||
return new MonitorLogger(categoryName, this);
|
||||
}
|
||||
|
||||
public void AddMessage(string message)
|
||||
{
|
||||
AddMessage(LogLevel.None, null, message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queue a log message. The ring gets the plain message; formatting happens at the writer.
|
||||
/// </summary>
|
||||
public void AddMessage(LogLevel level, string? category, string message)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
// Raw lines (null category) are markers and recovery notes, so they are never filtered
|
||||
if (category is not null && !IsEnabled(level))
|
||||
return;
|
||||
|
||||
// Threads can still be logging while another disposes, and ILogger.Log must not throw
|
||||
try
|
||||
{
|
||||
_tailRing?.Write(message);
|
||||
if (category is null)
|
||||
_writer.Add(message);
|
||||
else
|
||||
_writer.Add(level, category, message);
|
||||
}
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
|
||||
AppDomain.CurrentDomain.UnhandledException -= OnUnhandledException;
|
||||
_writer.Dispose();
|
||||
_tailRing?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Counters describing the logging pipeline's current state.</summary>
|
||||
public struct MonitorLoggingStats
|
||||
{
|
||||
public int QueueDepth;
|
||||
public int QueueCapacity;
|
||||
public long LinesWritten;
|
||||
public long BytesWritten;
|
||||
public long LinesDropped;
|
||||
|
||||
// Lines drained with no usable log file, and whether the file was lost to a write failure
|
||||
public long LinesDiscarded;
|
||||
public bool WriterFailed;
|
||||
|
||||
public long RingSequence;
|
||||
public int RingSlotCount;
|
||||
public int RingSlotSize;
|
||||
|
||||
public MonitorLoggingStats() { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This logger queues messages for the background writer and crash-tail ring
|
||||
/// </summary>
|
||||
internal sealed class MonitorLogger : ILogger
|
||||
{
|
||||
private readonly string _categoryName;
|
||||
private readonly MonitorLoggerProvider _provider;
|
||||
|
||||
public MonitorLogger(string categoryName, MonitorLoggerProvider provider)
|
||||
{
|
||||
_provider = provider;
|
||||
_categoryName = categoryName;
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
public void Log<TState>(
|
||||
LogLevel logLevel,
|
||||
EventId eventId,
|
||||
TState state,
|
||||
Exception? exception,
|
||||
Func<TState, Exception?, string> formatter
|
||||
)
|
||||
{
|
||||
// Gated before the formatter runs, so a filtered-out call allocates nothing at all
|
||||
if (!_provider.IsEnabled(logLevel))
|
||||
return;
|
||||
|
||||
// A throwing ToString in the state or exception costs its line, never the game thread
|
||||
try
|
||||
{
|
||||
var message = formatter(state, exception);
|
||||
|
||||
// The default formatter leaves the exception out, and a crash log without the stack is useless
|
||||
if (exception is not null)
|
||||
message = $"{message}{Environment.NewLine}{exception}";
|
||||
|
||||
_provider.AddMessage(logLevel, _categoryName, message);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel)
|
||||
{
|
||||
return _provider.IsEnabled(logLevel);
|
||||
}
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
447
brutal.monitor/Brutal.Monitor.Host/Monitor.cs
Normal file
447
brutal.monitor/Brutal.Monitor.Host/Monitor.cs
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Brutal.Logging;
|
||||
using Brutal.Monitor.Common;
|
||||
using Brutal.Monitor.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.Monitor
|
||||
{
|
||||
public class Monitor : IDisposable
|
||||
{
|
||||
private const int ThrottleExpirationMs = 10000; // Minimum milliseconds between first-chance collections
|
||||
private const int TimeOutMs = 1000; // Timeout for subprocess command acknowledgements
|
||||
private const int DefaultDumpTimeOutMs = 60000; // Matches CollectorOptions.DumpTimeoutMs
|
||||
|
||||
// Bounded, so a best-effort dump still writing cannot make shutdown look hung
|
||||
private const int ShutdownGraceMs = 2000;
|
||||
|
||||
private Process? _monitorProcess;
|
||||
private ProcessResponseReader? _responses;
|
||||
private long _nextFirstChance; // Earliest TickCount64 the next first-chance collection may start
|
||||
private volatile bool _firstChancePending;
|
||||
private volatile bool _subprocessExited;
|
||||
|
||||
// Set before the subprocess is told to stop, so a crash handler already past its guard turns back
|
||||
private volatile bool _stopping;
|
||||
|
||||
// Captured the moment the subprocess exits, so reading it later cannot race or throw
|
||||
private volatile int _subprocessExitCode = -1;
|
||||
private readonly LogCategory _monitorLog;
|
||||
private readonly string _name;
|
||||
|
||||
/// <summary>The ILoggerProvider this Monitor logs through, owned and disposed by it.</summary>
|
||||
public MonitorLoggerProvider LogProvider { get; }
|
||||
|
||||
private CollectorOptions? _collectorOptions = null;
|
||||
|
||||
// Tracked via the Exited event so the first-chance path checks a field, not the process
|
||||
public bool SubprocessRunning => _monitorProcess != null && !_subprocessExited;
|
||||
|
||||
/// <summary>Exit code of the subprocess once it has exited, or -1 while it is still running.</summary>
|
||||
public int SubprocessExitCode => _subprocessExitCode;
|
||||
|
||||
/// <summary>
|
||||
/// The name (like "Gruntz.client") plus this run's start time and pid names every
|
||||
/// file this run produces, so instances sharing a folder never collide. It must be
|
||||
/// usable as a plain file name. Messages below minimumLevel are dropped before
|
||||
/// anything is formatted, which is where trace spam gets expensive.
|
||||
/// </summary>
|
||||
public Monitor(string name, LogLevel minimumLevel = LogLevel.Trace)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(name);
|
||||
|
||||
// The name seeds file names and retention globs, so wildcards or separators could sweep others' files
|
||||
if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name.IndexOfAny(['*', '?', '/', '\\']) >= 0)
|
||||
throw new ArgumentException(
|
||||
$"Monitor name '{name}' must be usable as a plain file name, without wildcards or separators.",
|
||||
nameof(name)
|
||||
);
|
||||
|
||||
_name = name;
|
||||
_monitorLog = LogCategory.Make("Monitor");
|
||||
LogProvider = new MonitorLoggerProvider(minimumLevel);
|
||||
|
||||
Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
|
||||
LogProvider.Dispose();
|
||||
}
|
||||
|
||||
public void AddLogger(LoggerOptions loggerOptions)
|
||||
{
|
||||
// In-process logging, so this works with or without the subprocess
|
||||
LogProvider.Configure(loggerOptions, _name);
|
||||
|
||||
// An unusable path disables file logging rather than failing, so it is reported here
|
||||
if (LogProvider.LogFilePath is null)
|
||||
_monitorLog.Warning(
|
||||
$"Monitor could not open a log file in '{loggerOptions.LogDirectory}'. "
|
||||
+ "File logging is disabled for this session."
|
||||
);
|
||||
|
||||
// Read once: Stop can null the field between this and the write
|
||||
var process = _monitorProcess;
|
||||
if (process != null && !_subprocessExited && LogProvider.CrashTailPath is not null)
|
||||
{
|
||||
process.WriteLineSync($"LogTail\t{LogProvider.CrashTailPath}");
|
||||
_monitorLog.Info($"Monitor subprocess log tail: {WaitFor("LogTail", TimeOutMs) ?? "no response"}.");
|
||||
}
|
||||
}
|
||||
|
||||
public void AddCollector(CollectorOptions collectorOptions)
|
||||
{
|
||||
// The game creates the directory; resolved to a full path so the subprocess's own cwd never matters
|
||||
collectorOptions.DumpPath = Path.GetFullPath(collectorOptions.DumpPath);
|
||||
if (!Directory.Exists(collectorOptions.DumpPath))
|
||||
throw new DirectoryNotFoundException($"Dump directory '{collectorOptions.DumpPath}' does not exist.");
|
||||
|
||||
_collectorOptions = collectorOptions;
|
||||
|
||||
// Detach first, so configuring twice replaces the handlers instead of doubling them
|
||||
DetachCollectorHandlers();
|
||||
if (_collectorOptions.Value.FirstChance != DumpType.None)
|
||||
AppDomain.CurrentDomain.FirstChanceException += OnFirstChance;
|
||||
if (_collectorOptions.Value.LastChance != DumpType.None)
|
||||
AppDomain.CurrentDomain.UnhandledException += OnLastChance;
|
||||
|
||||
// Read once: Stop can null the field between this and the write
|
||||
var process = _monitorProcess;
|
||||
if (process == null || _subprocessExited)
|
||||
return;
|
||||
|
||||
// Tab-separated because dump paths contain spaces
|
||||
process.WriteLineSync(
|
||||
$"AddCollector\t{collectorOptions.DumpPath}\t{(int)collectorOptions.FirstChance}"
|
||||
+ $"\t{(int)collectorOptions.LastChance}\t{collectorOptions.KeepCount}"
|
||||
+ $"\t{collectorOptions.DumpTimeoutMs}"
|
||||
);
|
||||
_monitorLog.Info($"Monitor subprocess collector: {WaitFor("AddCollector", TimeOutMs) ?? "no response"}.");
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
var rid = "win-x64";
|
||||
if (OperatingSystem.IsLinux())
|
||||
rid = "linux-x64";
|
||||
else if (OperatingSystem.IsMacOS())
|
||||
rid = "osx-arm64";
|
||||
|
||||
var thisDirectory = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory);
|
||||
var subprocessName = "Brutal.Monitor.Subprocess";
|
||||
var extension = OperatingSystem.IsWindows() ? ".exe" : "";
|
||||
|
||||
var monitorExe = FindSubprocessExecutable(thisDirectory, rid, subprocessName + extension);
|
||||
if (monitorExe is null)
|
||||
{
|
||||
_monitorLog.Error(
|
||||
$"Brutal.Monitor subprocess was not found beside the application or in "
|
||||
+ $"runtimes/{rid}/native. Crash dump collection is disabled."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_monitorLog.Info($"Running Monitor subprocess from {thisDirectory}.");
|
||||
var startInfo = new ProcessStartInfo()
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
FileName = monitorExe,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardInput = true,
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
WindowStyle = ProcessWindowStyle.Hidden,
|
||||
WorkingDirectory = thisDirectory,
|
||||
};
|
||||
|
||||
// The subprocess names its dumps and tails from these, matching this run's log
|
||||
startInfo.ArgumentList.Add($"{Environment.ProcessId}");
|
||||
startInfo.ArgumentList.Add(_name);
|
||||
startInfo.ArgumentList.Add(MonitorFileNames.ProcessStamp);
|
||||
|
||||
try
|
||||
{
|
||||
_monitorProcess = Process.Start(startInfo);
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
_monitorProcess = null;
|
||||
}
|
||||
|
||||
if (_monitorProcess == null)
|
||||
{
|
||||
_monitorLog.Warning(
|
||||
$"Monitor subprocess ({monitorExe}) could not be started. "
|
||||
+ "Falling back to logging and crash handling from the main process."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Subscribed before events are enabled, or an already-dead subprocess fires Exited into no handler
|
||||
_subprocessExited = false;
|
||||
_monitorProcess.Exited += OnMonitorExit;
|
||||
_monitorProcess.EnableRaisingEvents = true;
|
||||
|
||||
// Owns the only reader of the subprocess's stdout
|
||||
_responses = new ProcessResponseReader(_monitorProcess);
|
||||
|
||||
_monitorLog.Info("Monitor subprocess started successfully");
|
||||
|
||||
// Redirect the error stream to Log as Errors instead
|
||||
_monitorProcess
|
||||
.StandardError.ReadToEndAsync()
|
||||
.ContinueWith(task =>
|
||||
{
|
||||
// Touching Exception observes a torn-down stream instead of raising UnobservedTaskException
|
||||
if (task.Exception is not null || !task.IsCompletedSuccessfully)
|
||||
return;
|
||||
|
||||
var errorOutput = task.Result;
|
||||
if (!string.IsNullOrEmpty(errorOutput))
|
||||
{
|
||||
_monitorLog.Warning($"Monitor subprocess error output: {errorOutput}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
// Closes the collect paths first, so a handler that entered before this cannot
|
||||
// write a command to a subprocess that is already on its way out
|
||||
_stopping = true;
|
||||
|
||||
// Even when no subprocess started, or the handlers would root this Monitor for the process lifetime
|
||||
DetachCollectorHandlers();
|
||||
|
||||
var process = _monitorProcess;
|
||||
if (process != null)
|
||||
{
|
||||
process.Exited -= OnMonitorExit;
|
||||
|
||||
// This runs from Dispose, so shutting the subprocess down must always finish
|
||||
try
|
||||
{
|
||||
if (!_subprocessExited)
|
||||
{
|
||||
process.WriteLineSync("Stop");
|
||||
_monitorLog.Info($"Monitor subprocess stop: {WaitFor("Stop", TimeOutMs) ?? "no response"}.");
|
||||
}
|
||||
|
||||
// A first-chance dump still writing is best effort, so shutdown abandons it
|
||||
// rather than waiting out its whole budget and looking hung
|
||||
if (process.WaitForExit(ShutdownGraceMs))
|
||||
RecordExit(process);
|
||||
else
|
||||
Terminate(process);
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally
|
||||
{
|
||||
_responses?.Dispose();
|
||||
_responses = null;
|
||||
process.Dispose();
|
||||
_monitorProcess = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RecordExit(Process process)
|
||||
{
|
||||
// Safe to read here: the wait returning means it has exited
|
||||
_subprocessExitCode = process.ExitCode;
|
||||
if (_subprocessExitCode != 0)
|
||||
_monitorLog.Error($"Monitor process {process.Id} exited with error {_subprocessExitCode}");
|
||||
else
|
||||
_monitorLog.Info($"Monitor process {process.Id} exited successfully.");
|
||||
}
|
||||
|
||||
// The subprocess can exit before the kill lands, so Kill throwing is normal and the wait is bounded
|
||||
private void Terminate(Process process)
|
||||
{
|
||||
_monitorLog.Info($"Monitor process {process.Id} exit timeout. Force termination.");
|
||||
|
||||
try
|
||||
{
|
||||
process.Kill(true);
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
// Kill is asynchronous, and touching ExitCode before it lands throws
|
||||
try
|
||||
{
|
||||
if (process.WaitForExit(TimeOutMs))
|
||||
RecordExit(process);
|
||||
else
|
||||
_monitorLog.Warning($"Monitor process {process.Id} did not exit after being terminated.");
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
// Removing a handler that was never added is a no-op, so this is safe to call any time
|
||||
private void DetachCollectorHandlers()
|
||||
{
|
||||
AppDomain.CurrentDomain.FirstChanceException -= OnFirstChance;
|
||||
AppDomain.CurrentDomain.UnhandledException -= OnLastChance;
|
||||
}
|
||||
|
||||
private void OnMonitorExit(object? sender, EventArgs e)
|
||||
{
|
||||
_subprocessExited = true;
|
||||
|
||||
// Nothing may escape a runtime callback; a dead subprocess costs crash dumps, not the application
|
||||
try
|
||||
{
|
||||
// The sender is the process that just exited, so this never races Stop for the field
|
||||
if (sender is Process exited)
|
||||
_subprocessExitCode = exited.ExitCode;
|
||||
|
||||
_monitorLog.Warning(
|
||||
$"Monitor subprocess exited early with exit code {_subprocessExitCode}. "
|
||||
+ "Crash dump collection is disabled for the rest of this session."
|
||||
);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
private void OnFirstChance(object? sender, FirstChanceExceptionEventArgs e)
|
||||
{
|
||||
// Runs on every exception in the process, so the throttled path is a read and a compare
|
||||
var now = Environment.TickCount64;
|
||||
var next = Volatile.Read(ref _nextFirstChance);
|
||||
if (now < next)
|
||||
return;
|
||||
|
||||
// One winner per window; a loser was beaten by a concurrent exception this same instant
|
||||
if (Interlocked.CompareExchange(ref _nextFirstChance, now + ThrottleExpirationMs, next) != next)
|
||||
return;
|
||||
|
||||
if (_collectorOptions == null || _collectorOptions.Value.FirstChance == DumpType.None)
|
||||
return;
|
||||
|
||||
if (!SubprocessRunning)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
CollectFirstChanceDump(e.Exception);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
private void OnLastChance(object? sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
// A main-thread crash runs this Monitor's Dispose on the way out, which would retire the ring
|
||||
LogProvider.PreserveCrashTail();
|
||||
|
||||
if (_collectorOptions == null || _collectorOptions.Value.LastChance == DumpType.None)
|
||||
return;
|
||||
|
||||
// Guarded so a throwing ToString on the dying exception cannot suppress the dump
|
||||
try
|
||||
{
|
||||
_monitorLog.Error($"Unhandled exception {e.ExceptionObject}.");
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
if (!SubprocessRunning)
|
||||
return;
|
||||
|
||||
// Unthrottled: sharing the first-chance permit let a benign throw skip the real dump
|
||||
try
|
||||
{
|
||||
CollectLastChanceDump();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>Commands are serial, so the budget covers a first-chance dump ahead of us, if enabled.</summary>
|
||||
internal static int LastChanceWait(CollectorOptions? collectorOptions)
|
||||
{
|
||||
var dumpTimeOut = collectorOptions?.DumpTimeoutMs ?? DefaultDumpTimeOutMs;
|
||||
var firstChanceCanQueue = collectorOptions is { } options && options.FirstChance != DumpType.None;
|
||||
|
||||
return firstChanceCanQueue ? dumpTimeOut * 2 + TimeOutMs : dumpTimeOut + TimeOutMs;
|
||||
}
|
||||
|
||||
private int LastChanceWaitMs => LastChanceWait(_collectorOptions);
|
||||
|
||||
private string? WaitFor(string command, int timeOut) => _responses?.WaitFor(command, timeOut);
|
||||
|
||||
private void CollectFirstChanceDump(Exception exception)
|
||||
{
|
||||
// Read once: Stop can null the field between this and the write
|
||||
var process = _monitorProcess;
|
||||
if (_stopping || process == null || _subprocessExited)
|
||||
return;
|
||||
|
||||
// One dump in flight at a time, or a burst of throws pushes the fatal dump past its wait budget
|
||||
if (_firstChancePending)
|
||||
{
|
||||
if (WaitFor("FirstChance", 0) is null)
|
||||
return;
|
||||
_firstChancePending = false;
|
||||
}
|
||||
|
||||
// Never wait: the throwing thread is not dying, so blocking it is a frame hitch for nothing
|
||||
process.WriteLineSync("FirstChance");
|
||||
_firstChancePending = true;
|
||||
|
||||
// Formatted only for the exception being dumped, and a throwing ToString costs the line, not the dump
|
||||
try
|
||||
{
|
||||
_monitorLog.Error($"First chance dump requested for {exception}.");
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
private void CollectLastChanceDump()
|
||||
{
|
||||
// Read once: Stop can null the field between the check and the write
|
||||
var process = _monitorProcess;
|
||||
|
||||
// A subprocess already told to stop will never answer, and waiting on it would stall the dying process
|
||||
if (_stopping || process == null || _subprocessExited)
|
||||
{
|
||||
_monitorLog.Warning("Last chance dump: the monitor subprocess is shutting down or gone.");
|
||||
return;
|
||||
}
|
||||
|
||||
// This wait is what keeps the dying process alive long enough to be dumped
|
||||
process.WriteLineSync("LastChance");
|
||||
LogCollectResponse("Last chance dump", WaitFor("LastChance", LastChanceWaitMs));
|
||||
}
|
||||
|
||||
private void LogCollectResponse(string kind, string? response)
|
||||
{
|
||||
if (string.IsNullOrEmpty(response))
|
||||
{
|
||||
_monitorLog.Warning($"{kind}: no response from the monitor subprocess.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.StartsWith("Failed", StringComparison.Ordinal) || response == "timed out")
|
||||
_monitorLog.Warning($"{kind}: {response}.");
|
||||
else
|
||||
_monitorLog.Info($"{kind}: {response}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locate the subprocess executable: beside the app for local builds, or under
|
||||
/// runtimes/<rid>/native as the package delivers it. Returns null if neither exists.
|
||||
/// </summary>
|
||||
private static string? FindSubprocessExecutable(string baseDirectory, string rid, string fileName)
|
||||
{
|
||||
var beside = Path.Combine(baseDirectory, fileName);
|
||||
if (File.Exists(beside))
|
||||
return beside;
|
||||
|
||||
var packaged = Path.Combine(baseDirectory, "runtimes", rid, "native", fileName);
|
||||
return File.Exists(packaged) ? packaged : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<Project>
|
||||
<!-- NuGet extraction does not preserve executable permissions for the NativeAOT watchdog. -->
|
||||
<Target
|
||||
Name="MakeMonitorBuildExecutable"
|
||||
AfterTargets="CopyFilesToOutputDirectory"
|
||||
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(TargetDir)' != ''"
|
||||
>
|
||||
<ItemGroup>
|
||||
<_MonitorBuildExecutable Include="$(TargetDir)Brutal.Monitor.Subprocess;$(TargetDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
|
||||
</ItemGroup>
|
||||
<Exec
|
||||
Command="chmod +x "%(_MonitorBuildExecutable.Identity)""
|
||||
Condition="Exists('%(_MonitorBuildExecutable.Identity)')"
|
||||
/>
|
||||
</Target>
|
||||
<Target
|
||||
Name="MakeMonitorPublishExecutable"
|
||||
AfterTargets="Publish"
|
||||
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(PublishDir)' != ''"
|
||||
>
|
||||
<ItemGroup>
|
||||
<_MonitorPublishExecutable Include="$(PublishDir)Brutal.Monitor.Subprocess;$(PublishDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
|
||||
</ItemGroup>
|
||||
<Exec
|
||||
Command="chmod +x "%(_MonitorPublishExecutable.Identity)""
|
||||
Condition="Exists('%(_MonitorPublishExecutable.Identity)')"
|
||||
/>
|
||||
</Target>
|
||||
</Project>
|
||||
Loading…
Reference in a new issue