0.2.0-dev Download ZIP
146 lines ·4.4 KB Raw
| 1 | using System.Diagnostics; |
| 2 | using System.Globalization; |
| 3 | |
| 4 | namespace EvilEngine.Host; |
| 5 | |
| 6 | public sealed record MemoryBudget(long Soft, long Hard) |
| 7 | { |
| 8 | public const string SoftVariable = "EVIL_MEMORY_SOFT_GB"; |
| 9 | public const string HardVariable = "EVIL_MEMORY_HARD_GB"; |
| 10 | |
| 11 | public static readonly MemoryBudget Default = new(Gigabytes(6), Gigabytes(8)); |
| 12 | |
| 13 | public static MemoryBudget Read(Func<string, string?> variable) |
| 14 | { |
| 15 | var soft = Parse(variable(SoftVariable)) ?? Default.Soft; |
| 16 | var hard = Parse(variable(HardVariable)) ?? Math.Max(Default.Hard, soft); |
| 17 | return new MemoryBudget(Math.Min(soft, hard), hard); |
| 18 | } |
| 19 | |
| 20 | private static long? Parse(string? text) |
| 21 | { |
| 22 | return double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var gigabytes) && |
| 23 | gigabytes > 0 |
| 24 | ? (long)(gigabytes * Gigabytes(1)) |
| 25 | : null; |
| 26 | } |
| 27 | |
| 28 | private static long Gigabytes(long count) |
| 29 | { |
| 30 | return count * 1024 * 1024 * 1024; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | public sealed class MemoryGuard( |
| 35 | MemoryBudget budget, |
| 36 | Func<long> resident, |
| 37 | Action<TranscriptTag, string> line, |
| 38 | Action<string> fail) : IDisposable |
| 39 | { |
| 40 | private readonly List<(string Name, Func<long> Bytes)> _holders = []; |
| 41 | private readonly Lock _lock = new(); |
| 42 | private readonly List<Func<long>> _trimmers = []; |
| 43 | private bool _failed; |
| 44 | private Timer? _timer; |
| 45 | private bool _warned; |
| 46 | |
| 47 | public MemoryBudget Budget { get; } = budget; |
| 48 | |
| 49 | public void Dispose() |
| 50 | { |
| 51 | _timer?.Dispose(); |
| 52 | } |
| 53 | |
| 54 | public void Hold(string name, Func<long> bytes) |
| 55 | { |
| 56 | lock (_lock) |
| 57 | { |
| 58 | _holders.Add((name, bytes)); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | public void Trim(Func<long> release) |
| 63 | { |
| 64 | lock (_lock) |
| 65 | { |
| 66 | _trimmers.Add(release); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public void Start(TimeSpan every) |
| 71 | { |
| 72 | _timer ??= new Timer(_ => Check(), null, every, every); |
| 73 | } |
| 74 | |
| 75 | public void Check() |
| 76 | { |
| 77 | if (!_lock.TryEnter()) |
| 78 | return; |
| 79 | try |
| 80 | { |
| 81 | if (_failed) |
| 82 | return; |
| 83 | var now = resident(); |
| 84 | if (now >= Budget.Hard) |
| 85 | { |
| 86 | _failed = true; |
| 87 | fail( |
| 88 | $"Memory reached {Size(now)}, over the {Size(Budget.Hard)} hard budget, so the engine quit rather than take the desktop down with it.{Holders(now)}"); |
| 89 | return; |
| 90 | } |
| 91 | |
| 92 | if (now < Budget.Soft) |
| 93 | { |
| 94 | if (now < Budget.Soft * 9 / 10) |
| 95 | _warned = false; |
| 96 | return; |
| 97 | } |
| 98 | |
| 99 | var released = _trimmers.Sum(trim => trim()); |
| 100 | if (released > 0) |
| 101 | GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); |
| 102 | if (_warned) |
| 103 | return; |
| 104 | _warned = true; |
| 105 | line(TranscriptTag.Warn, |
| 106 | $"Memory reached {Size(now)}, over the {Size(Budget.Soft)} soft budget; released {Size(released)} of cached content.{Holders(now)}"); |
| 107 | } |
| 108 | finally |
| 109 | { |
| 110 | _lock.Exit(); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | public static long Resident() |
| 115 | { |
| 116 | try |
| 117 | { |
| 118 | var fields = File.ReadAllText("/proc/self/statm").Split(' '); |
| 119 | return long.Parse(fields[1], CultureInfo.InvariantCulture) * Environment.SystemPageSize; |
| 120 | } |
| 121 | catch (Exception error) when (error is IOException or UnauthorizedAccessException or FormatException |
| 122 | or IndexOutOfRangeException) |
| 123 | { |
| 124 | using var process = Process.GetCurrentProcess(); |
| 125 | return process.WorkingSet64; |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | public static string Size(long bytes) |
| 130 | { |
| 131 | return bytes >= 1L << 30 |
| 132 | ? $"{(bytes / (double)(1L << 30)).ToString("0.0", CultureInfo.InvariantCulture)} GB" |
| 133 | : $"{(bytes / (double)(1L << 20)).ToString("0", CultureInfo.InvariantCulture)} MB"; |
| 134 | } |
| 135 | |
| 136 | private string Holders(long resident) |
| 137 | { |
| 138 | if (_holders.Count == 0) |
| 139 | return ""; |
| 140 | var held = _holders.Select(holder => (holder.Name, Bytes: holder.Bytes())).ToList(); |
| 141 | held.Add(("everything else", Math.Max(0, resident - held.Sum(holder => holder.Bytes)))); |
| 142 | var named = held.OrderByDescending(holder => holder.Bytes) |
| 143 | .Select(holder => $"{holder.Name} {Size(holder.Bytes)}"); |
| 144 | return $" Largest holders: {string.Join(", ", named)}."; |
| 145 | } |
| 146 | } |