-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cs
More file actions
235 lines (209 loc) · 6.95 KB
/
Copy pathMain.cs
File metadata and controls
235 lines (209 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
using System;
using System.Collections.Generic;
using System.Threading;
using Spectre.Console;
namespace IoMonitor
{
/// <summary>
/// Application entry point and top-level lifecycle management.
/// </summary>
internal static partial class Program
{
/// <summary>
/// Entry point. Sets up security, ETW, sampling threads and runs the Spectre console UI.
/// </summary>
private static void Main()
{
bool shouldCleanup = false;
try
{
if (!OperatingSystem.IsWindows())
{
Console.WriteLine("DiskMonitor requires Windows because it reads Win32 process I/O counters and ETW events.");
return;
}
if (!AcquireSingleInstanceMutex())
{
Console.WriteLine("I/O Monitor is already running. Only one instance can run at a time.");
return;
}
shouldCleanup = true;
InitializeSecurityContext();
AttachCancelKeyHandler();
AnsiConsole.Clear();
if (_hasAdmin)
{
StartEtwMonitoring();
Thread.Sleep(1500);
}
StartDataCollectionThread();
RunUiLoop();
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
WaitForKeyIfInteractive();
}
finally
{
if (shouldCleanup)
{
Cleanup();
}
}
}
/// <summary>
/// Attempts to acquire the single-instance mutex. Returns false if another instance is already running.
/// </summary>
private static bool AcquireSingleInstanceMutex()
{
bool createdNew;
_singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\IoMonitorSingleton", out createdNew);
return createdNew;
}
/// <summary>
/// Populates fields that describe the current security context.
/// </summary>
private static void InitializeSecurityContext()
{
_hasAdmin = SecurityUtilities.IsAdministrator();
_hasDebug = _hasAdmin && SecurityUtilities.EnableDebugPrivilege();
_programStartTime = DateTime.Now;
}
/// <summary>
/// Installs a Ctrl+C handler that triggers a graceful shutdown.
/// </summary>
private static void AttachCancelKeyHandler()
{
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
_running = false;
};
}
/// <summary>
/// Starts the background sampling thread.
/// </summary>
private static void StartDataCollectionThread()
{
var dataThread = new Thread(DataCollectionLoop)
{
IsBackground = true,
Name = "IoMonitor.DataCollection"
};
dataThread.Start();
}
/// <summary>
/// Main UI loop that drives the live Spectre.Console layout.
/// </summary>
private static void RunUiLoop()
{
var layout = new Layout("Root").SplitRows(
new Layout("Header").Size(1),
new Layout("Status").Size(4),
new Layout("Table"));
AnsiConsole.Live(layout).AutoClear(false).Start(ctx =>
{
while (_running)
{
HandleInput();
List<ProcessIoSample> snapshot;
lock (_dataLock)
{
snapshot = new List<ProcessIoSample>(_cachedSamples);
}
layout["Header"].Update(CreateHeaderPanel());
layout["Status"].Update(CreateStatusPanel(snapshot));
layout["Table"].Update(CreateTable(snapshot));
ctx.Refresh();
Thread.Sleep(250);
}
});
}
/// <summary>
/// Performs best-effort cleanup of ETW resources, mutexes, and in-memory collections.
/// </summary>
private static void Cleanup()
{
AnsiConsole.MarkupLine("[yellow]Cleaning up resources...[/]");
_running = false;
StopEtwSession();
FlushPendingCsvLog();
try
{
_singleInstanceMutex?.ReleaseMutex();
_singleInstanceMutex?.Dispose();
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Mutex cleanup error: {ex.Message}[/]");
}
try
{
lock (_dataLock)
{
_history.Clear();
_etwTotals.Clear();
_etwLast.Clear();
_processIoByDrive.Clear();
_ioHistory.Clear();
_fileIoStats.Clear();
_cachedSamples.Clear();
}
}
catch (Exception ex)
{
AnsiConsole.MarkupLine($"[red]Collection cleanup error: {ex.Message}[/]");
}
AnsiConsole.MarkupLine("[green]Cleanup complete. Exiting...[/]");
Thread.Sleep(500);
}
/// <summary>
/// Forces a synchronous resample using a nominal one-second interval.
/// </summary>
private static void ForceResample()
{
try
{
var samples = SampleProcesses(1.0, _showClosedProcesses);
lock (_dataLock)
{
_cachedSamples = samples;
_lastSampleIntervalSeconds = 1.0;
}
}
catch
{
// Resample failures are ignored; the background loop will continue.
}
}
private static void WaitForKeyIfInteractive()
{
try
{
if (!Console.IsInputRedirected)
{
Console.ReadKey(intercept: true);
}
}
catch
{
// Nothing useful to do when no console is attached.
}
}
private static void FlushPendingCsvLog()
{
try
{
if (_csvLoggingOn)
{
CsvExporter.AppendLogEntries("io_monitor.csv", DrainLogEntries());
}
}
catch
{
// Shutdown logging is best effort.
}
}
}
}