| 1 | using System.Diagnostics; |
| 2 | using System.Runtime.CompilerServices; |
| 3 | using System.Runtime.InteropServices; |
| 4 | using System.Text.Json.Nodes; |
| 5 | |
| 6 | namespace Cage.GuestClipboard; |
| 7 | |
| 8 | internal static class ResourcesRpc |
| 9 | { |
| 10 | [ModuleInitializer] |
| 11 | internal static void Register() { if (GuestOperations.Names.Contains("resources")) GuestOperations.Register("resources", Run); } |
| 12 | internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) |
| 13 | { |
| 14 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 15 | var input = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); |
| 16 | if (input["action"]?.GetValue<string>() != "sample") throw new InvalidDataException("resource_operation_invalid"); |
| 17 | if (!GetSystemTimes(out var idleBefore, out var kernelBefore, out var userBefore)) throw new InvalidDataException("resource_sample_failed"); |
| 18 | await Task.Delay(150, token); |
| 19 | if (!available() || !GetSystemTimes(out var idle, out var kernel, out var user)) throw new InvalidDataException("requires_gui_login"); |
| 20 | var state = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() }; |
| 21 | if (!GlobalMemoryStatusEx(ref state) || state.AvailablePhysical > state.TotalPhysical) throw new InvalidDataException("resource_sample_failed"); |
| 22 | var total = kernel + user - kernelBefore - userBefore; |
| 23 | var idleDelta = idle - idleBefore; |
| 24 | var cpu = total == 0 ? 0 : Math.Clamp(100.0 * (total - Math.Min(total, idleDelta)) / total, 0, 100); |
| 25 | var now = DateTimeOffset.UtcNow; |
| 26 | await Protocol.Write(stream, new() |
| 27 | { |
| 28 | ["version"] = 1, ["pid"] = Environment.ProcessId, ["cpus"] = Environment.ProcessorCount, |
| 29 | ["updated_at"] = now.ToString("O"), ["observed_at"] = now.ToString("O"), ["cpu_percent"] = cpu, |
| 30 | ["guest"] = new JsonObject { ["total_bytes"] = state.TotalPhysical, ["available_bytes"] = state.AvailablePhysical }, |
| 31 | ["unavailable_observations"] = new JsonArray("oom_kills", "memory_stall_percent", "swap_total_bytes", "swap_free_bytes", "host_pressure") |
| 32 | }, token); |
| 33 | } |
| 34 | [StructLayout(LayoutKind.Sequential)] private struct MemoryStatus |
| 35 | { |
| 36 | internal uint Length, Load; |
| 37 | internal ulong TotalPhysical, AvailablePhysical, TotalPageFile, AvailablePageFile, TotalVirtual, AvailableVirtual, AvailableExtendedVirtual; |
| 38 | } |
| 39 | [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status); |
| 40 | [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetSystemTimes(out ulong idle, out ulong kernel, out ulong user); |
| 41 | } |