-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathGenericMonitoringArea.cs
More file actions
399 lines (360 loc) · 14.7 KB
/
GenericMonitoringArea.cs
File metadata and controls
399 lines (360 loc) · 14.7 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using PmcReader.Interop;
namespace PmcReader
{
public class GenericMonitoringArea : MonitoringArea
{
private delegate void SafeSetMonitoringListViewItems(MonitoringUpdateResults results, ListView monitoringListView);
private delegate void SafeSetMonitoringListViewColumns(string[] columns, ListView monitoringListView);
public MonitoringConfig[] monitoringConfigs;
protected int threadCount = 0, coreCount = 0, targetLogCoreIndex = -1;
protected string architectureName = "Generic";
private Dictionary<int, Stopwatch> lastUpdateTimers;
private string logFilePath = null;
private Object logFileLock = new object();
private bool logFileHeadersWritten = false;
public GenericMonitoringArea()
{
threadCount = Environment.ProcessorCount;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount += int.Parse(item["NumberOfCores"].ToString());
}
}
public int GetThreadCount()
{
return threadCount;
}
public MonitoringConfig[] GetMonitoringConfigs()
{
return monitoringConfigs;
}
public string GetArchitectureName()
{
return architectureName;
}
/// <summary>
/// Start logging to file
/// </summary>
/// <param name="filePath">File to log to</param>
/// <returns>null if successful, error string if something went wrong</returns>
public string StartLogToFile(string filePath, int targetCoreIndex)
{
if (string.IsNullOrEmpty(filePath))
{
return "No file path to log to";
}
if (!File.Exists(filePath))
{
try
{
File.WriteAllText(filePath, "");
}
catch (Exception e)
{
return e.Message;
}
}
else
{
try
{
// just do this to check permissions
File.WriteAllText(filePath, "");
}
catch (Exception e)
{
return e.Message;
}
}
if (targetCoreIndex >= coreCount)
{
// Ignore parameter if a nonexistent core index is specified
targetCoreIndex = -1;
}
else
{
this.targetLogCoreIndex = targetCoreIndex;
}
logFileHeadersWritten = false;
lock (logFileLock)
{
logFilePath = filePath;
}
return null;
}
public void StopLoggingToFile()
{
lock (logFileLock)
{
logFilePath = null;
}
}
/// <summary>
/// Starts background monitoring thread that periodically updates monitoring list view
/// with new results
/// </summary>
/// <param name="configId">Monitoring config to use</param>
/// <param name="listView">List view to update</param>
/// <param name="cancelToken">Cancellation token - since perf counters are limited,
/// this thread has to be cancelled before one for a new config is started</param>
public void MonitoringThread(int configId, ListView listView, CancellationToken cancelToken)
{
CultureInfo ci = new CultureInfo("en-US");
MonitoringConfig selectedConfig = monitoringConfigs[configId];
lastUpdateTimers = null;
if (cancelToken.IsCancellationRequested) return;
selectedConfig.Initialize();
SafeSetMonitoringListViewColumns cd = new SafeSetMonitoringListViewColumns(SetMonitoringListViewColumns);
listView.Invoke(cd, selectedConfig.GetColumns(), listView);
while (!cancelToken.IsCancellationRequested)
{
MonitoringUpdateResults updateResults = selectedConfig.Update();
// update list box with results (and we're always on a different thread)
SafeSetMonitoringListViewItems d = new SafeSetMonitoringListViewItems(SetMonitoringListView);
listView.Invoke(d, updateResults, listView);
// log to file, if we're doing that
lock (logFileLock)
{
if (!string.IsNullOrEmpty(logFilePath))
{
// log raw counter values if available. otherwise log metrics
// eventually I want to move everything over to log raw counter values
bool first;
if (updateResults.overallCounterValues != null)
{
if (!logFileHeadersWritten)
{
string csvHeader = "";
first = true;
foreach(Tuple<string, float> counterValue in updateResults.overallCounterValues)
{
if (first) csvHeader += counterValue.Item1;
else csvHeader += "," + counterValue.Item1;
first = false;
}
csvHeader += "\n";
File.AppendAllText(logFilePath, csvHeader);
logFileHeadersWritten = true;
}
string csvLine = "";
first = true;
foreach(Tuple<string, float> counterValue in updateResults.overallCounterValues)
{
if (first) csvLine += counterValue.Item2.ToString("G", ci);
else csvLine += "," + counterValue.Item2.ToString("G", ci);
first = false;
}
csvLine += "\n";
File.AppendAllText(logFilePath, csvLine);
}
else if (updateResults.overallMetrics != null)
{
if (!logFileHeadersWritten)
{
string csvHeader = "";
first = true;
foreach(string columnHeader in selectedConfig.GetColumns())
{
if (first) csvHeader += columnHeader;
else csvHeader += "," + columnHeader;
first = false;
}
csvHeader += "\n";
File.AppendAllText(logFilePath, csvHeader);
logFileHeadersWritten = true;
}
string csvLine = "";
first = true;
foreach(string value in updateResults.overallMetrics)
{
if (first) csvLine += value;
else csvLine += "," + value;
first = false;
}
csvLine += "\n";
File.AppendAllText(logFilePath, csvLine);
}
}
}
Thread.Sleep(1000);
}
}
/// <summary>
/// Init monitoring list view with new columns
/// </summary>
/// <param name="columns">New cols</param>
/// <param name="monitoringListView">List view to update</param>
public void SetMonitoringListViewColumns(string[] columns, ListView monitoringListView)
{
monitoringListView.Columns.Clear();
monitoringListView.Items.Clear();
foreach (string column in columns)
{
monitoringListView.Columns.Add(column);
}
foreach (ColumnHeader column in monitoringListView.Columns)
{
// nasty heuristic
if (column.Text.Length < 10) column.Width = 65;
else column.Width = -2;
}
}
/// <summary>
/// Apply updated results to monitoring list view
/// </summary>
/// <param name="updateResults">New perf counter metrics</param>
/// <param name="monitoringListView">List view to update</param>
public void SetMonitoringListView(MonitoringUpdateResults updateResults, ListView monitoringListView)
{
if (updateResults.unitMetrics != null && monitoringListView.Items.Count == updateResults.unitMetrics.Length + 1)
{
UpdateListViewItem(updateResults.overallMetrics, monitoringListView.Items[0]);
if (updateResults.unitMetrics != null)
{
for (int unitIdx = 0; unitIdx < updateResults.unitMetrics.Length; unitIdx++)
{
UpdateListViewItem(updateResults.unitMetrics[unitIdx], monitoringListView.Items[unitIdx + 1]);
}
}
}
else
{
monitoringListView.Items.Clear();
monitoringListView.Items.Add(new ListViewItem(updateResults.overallMetrics));
if (updateResults.unitMetrics != null)
{
for (int unitIdx = 0; unitIdx < updateResults.unitMetrics.Length; unitIdx++)
{
monitoringListView.Items.Add(new ListViewItem(updateResults.unitMetrics[unitIdx]));
}
}
}
}
/// <summary>
/// Update text in existing ListViewItem
/// darn it, it still flashes
/// </summary>
/// <param name="newFields">updated values</param>
/// <param name="listViewItem">list view item to update</param>
public static void UpdateListViewItem(string[] newFields, ListViewItem listViewItem)
{
for (int subItemIdx = 0; subItemIdx < listViewItem.SubItems.Count && subItemIdx < newFields.Length; subItemIdx++)
{
listViewItem.SubItems[subItemIdx].Text = newFields[subItemIdx];
}
}
/// <summary>
/// Make big number readable
/// </summary>
/// <param name="n">stupidly big number</param>
/// <returns>Formatted string, with G/M/K suffix if big</returns>
public static string FormatLargeNumber(ulong n)
{
if (n > 2000000000000UL)
{
return string.Format("{0:F2} T", (float)n / 1000000000000);
}
else if (n > 1000000000)
{
return string.Format("{0:F2} G", (float)n / 1000000000);
}
else if (n > 1000000)
{
return string.Format("{0:F2} M", (float)n / 1000000);
}
else if (n > 500)
{
return string.Format("{0:F2} K", (float)n / 1000);
}
return string.Format("{0} ", n);
}
public static string FormatLargeNumber(float n)
{
if (n > 2000000000000)
{
return string.Format("{0:F2} T", (float)n / 1000000000000);
}
else if (n > 1000000000)
{
return string.Format("{0:F2} G", n / 1000000000);
}
else if (n > 1000000)
{
return string.Format("{0:F2} M", n / 1000000);
}
else if (n > 500)
{
return string.Format("{0:F2} K", n / 1000);
}
return string.Format("{0:F2} ", n);
}
public static string FormatPercentage(float n, float total)
{
return string.Format("{0:F2}%", 100 * n / total);
}
/// <summary>
/// Read and zero a MSR
/// Useful for reading PMCs over a set interval
/// Terrifyingly dangerous everywhere else
/// </summary>
/// <param name="msrIndex">MSR index</param>
/// <returns>value read from MSR</returns>
public static ulong ReadAndClearMsr(uint msrIndex)
{
ulong retval;
Ring0.ReadMsr(msrIndex, out retval);
Ring0.WriteMsr(msrIndex, 0);
return retval;
}
/// <summary>
/// Get normalization factor assuming 1000 ms interval
/// </summary>
/// <param name="lastUpdateTime">last updated time in unix ms, will be updated</param>
/// <returns>normalization factor</returns>
public float GetNormalizationFactor(ref long lastUpdateTime)
{
long currentTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
float timeNormalization = (float)1000 / (currentTime - lastUpdateTime);
lastUpdateTime = currentTime;
return timeNormalization;
}
/// <summary>
/// Get normalization factor (for 1000 ms interval) given stopwatch index
/// also resets stopwatch
/// </summary>
/// <param name="index">Item index</param>
/// <returns>normalization factor</returns>
public float GetNormalizationFactor(int index)
{
if (lastUpdateTimers == null) lastUpdateTimers = new Dictionary<int, Stopwatch>();
Stopwatch sw;
if (! lastUpdateTimers.TryGetValue(index, out sw))
{
sw = new Stopwatch();
sw.Start();
lastUpdateTimers.Add(index, sw);
return 1;
}
sw.Stop();
float retval = 1000 / (float)sw.ElapsedMilliseconds;
sw.Restart();
return retval;
}
public virtual void InitializeCrazyControls(FlowLayoutPanel flowLayoutPanel, Label errorLabel) {}
protected Button CreateButton(string buttonText, EventHandler handler)
{
Button button = new Button();
button.Text = buttonText;
button.AutoSize = true;
button.Click += handler;
return button;
}
}
}