-
Notifications
You must be signed in to change notification settings - Fork 853
/
ResourceMetricsManager.cs
360 lines (290 loc) Β· 13.8 KB
/
ResourceMetricsManager.cs
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker.Telemetry;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
[ServiceLocator(Default = typeof(ResourceMetricsManager))]
public interface IResourceMetricsManager : IAgentService, IDisposable
{
Task RunDebugResourceMonitor();
Task RunMemoryUtilizationMonitor();
Task RunDiskSpaceUtilizationMonitor();
Task RunCpuUtilizationMonitor(string taskId);
void Setup(IExecutionContext context);
void SetContext(IExecutionContext context);
}
public sealed class ResourceMetricsManager : AgentService, IResourceMetricsManager
{
const int ACTIVE_MODE_INTERVAL = 5000;
const int WARNING_MESSAGE_INTERVAL = 5000;
const int AVAILABLE_DISK_SPACE_PERCENTAGE_THRESHOLD = 5;
const int AVAILABLE_MEMORY_PERCENTAGE_THRESHOLD = 5;
const int CPU_UTILIZATION_PERCENTAGE_THRESHOLD = 95;
IExecutionContext _context;
public void Setup(IExecutionContext context)
{
//initial context
ArgUtil.NotNull(context, nameof(context));
_context = context;
_currentProcess = Process.GetCurrentProcess();
}
public void SetContext(IExecutionContext context)
{
ArgUtil.NotNull(context, nameof(context));
_context = context;
}
public async Task RunDebugResourceMonitor()
{
while (!_context.CancellationToken.IsCancellationRequested)
{
_context.Debug(StringUtil.Loc("ResourceMonitorAgentEnvironmentResource", GetDiskInfoString(), GetMemoryInfoString(), GetCpuInfoString()));
await Task.Delay(ACTIVE_MODE_INTERVAL, _context.CancellationToken);
}
}
private void PublishTelemetry(string message, string taskId)
{
try
{
Dictionary<string, string> telemetryData = new Dictionary<string, string>
{
{ "TaskId", taskId },
{ "JobId", _context.Variables.System_JobId.ToString() },
{ "PlanId", _context.Variables.Get(Constants.Variables.System.PlanId) },
{ "Warning", message }
};
var cmd = new Command("telemetry", "publish")
{
Data = JsonConvert.SerializeObject(telemetryData, Formatting.None)
};
cmd.Properties.Add("area", "AzurePipelinesAgent");
cmd.Properties.Add("feature", "ResourceUtilization");
var publishTelemetryCmd = new TelemetryCommandExtension();
publishTelemetryCmd.Initialize(HostContext);
publishTelemetryCmd.ProcessCommand(_context, cmd);
}
catch (Exception ex)
{
Trace.Warning($"Unable to publish resource utilization telemetry data. Exception: {ex.Message}");
}
}
public async Task RunDiskSpaceUtilizationMonitor()
{
while (!_context.CancellationToken.IsCancellationRequested)
{
try
{
var diskInfo = GetDiskInfo();
var freeDiskSpacePercentage = Math.Round(((diskInfo.FreeDiskSpaceMB / (double)diskInfo.TotalDiskSpaceMB) * 100.0), 2);
var usedDiskSpacePercentage = 100.0 - freeDiskSpacePercentage;
if (freeDiskSpacePercentage <= AVAILABLE_DISK_SPACE_PERCENTAGE_THRESHOLD)
{
_context.Warning(StringUtil.Loc("ResourceMonitorFreeDiskSpaceIsLowerThanThreshold", diskInfo.VolumeRoot, AVAILABLE_DISK_SPACE_PERCENTAGE_THRESHOLD, $"{usedDiskSpacePercentage:0.00}"));
break;
}
}
catch (Exception ex)
{
Trace.Warning($"Unable to get disk info. Exception: {ex.Message}");
break;
}
await Task.Delay(WARNING_MESSAGE_INTERVAL, _context.CancellationToken);
}
}
public async Task RunMemoryUtilizationMonitor()
{
while (!_context.CancellationToken.IsCancellationRequested)
{
try
{
var memoryInfo = GetMemoryInfo();
var usedMemoryPercentage = Math.Round(((memoryInfo.UsedMemoryMB / (double)memoryInfo.TotalMemoryMB) * 100.0), 2);
var freeMemoryPercentage = 100.0 - usedMemoryPercentage;
if (freeMemoryPercentage <= AVAILABLE_MEMORY_PERCENTAGE_THRESHOLD)
{
_context.Warning(StringUtil.Loc("ResourceMonitorMemorySpaceIsLowerThanThreshold", AVAILABLE_MEMORY_PERCENTAGE_THRESHOLD, $"{usedMemoryPercentage:0.00}"));
break;
}
}
catch (Exception ex)
{
Trace.Warning($"Unable to get memory info. Exception: {ex.Message}");
break;
}
await Task.Delay(WARNING_MESSAGE_INTERVAL, _context.CancellationToken);
}
}
public async Task RunCpuUtilizationMonitor(string taskId)
{
while (!_context.CancellationToken.IsCancellationRequested)
{
try
{
var usedCpuPercentage = GetCpuInfo();
if (usedCpuPercentage >= CPU_UTILIZATION_PERCENTAGE_THRESHOLD)
{
string message = $"CPU utilization is higher than {CPU_UTILIZATION_PERCENTAGE_THRESHOLD}%; currently used: {usedCpuPercentage:0.00}%";
PublishTelemetry(message, taskId);
break;
}
}
catch (Exception ex)
{
Trace.Warning($"Unable to get CPU info. Exception: {ex.Message}");
break;
}
await Task.Delay(WARNING_MESSAGE_INTERVAL, _context.CancellationToken);
}
}
private struct DiskInfo
{
public long TotalDiskSpaceMB;
public long FreeDiskSpaceMB;
public string VolumeRoot;
}
private DiskInfo GetDiskInfo()
{
DiskInfo diskInfo = new();
string root = Path.GetPathRoot(_context.GetVariableValueOrDefault(Constants.Variables.Agent.WorkFolder));
var driveInfo = new DriveInfo(root);
diskInfo.TotalDiskSpaceMB = driveInfo.TotalSize / 1048576;
diskInfo.FreeDiskSpaceMB = driveInfo.AvailableFreeSpace / 1048576;
diskInfo.VolumeRoot = root;
return diskInfo;
}
private string GetDiskInfoString()
{
try
{
var diskInfo = GetDiskInfo();
return StringUtil.Loc("ResourceMonitorDiskInfo", diskInfo.VolumeRoot, $"{diskInfo.FreeDiskSpaceMB:0.00}", $"{diskInfo.TotalDiskSpaceMB:0.00}");
}
catch (Exception ex)
{
return StringUtil.Loc("ResourceMonitorDiskInfoError", ex.Message);
}
}
private Process _currentProcess;
private double GetCpuInfo()
{
TimeSpan totalCpuTime = _currentProcess.TotalProcessorTime;
TimeSpan elapsedTime = DateTime.Now - _currentProcess.StartTime;
double cpuUsage = (totalCpuTime.TotalMilliseconds / elapsedTime.TotalMilliseconds) * 100.0;
return cpuUsage;
}
private string GetCpuInfoString()
{
try
{
return StringUtil.Loc("ResourceMonitorCPUInfo", $"{GetCpuInfo():0.00}");
}
catch (Exception ex)
{
return StringUtil.Loc("ResourceMonitorCPUInfoError", ex.Message);
}
}
public struct MemoryInfo
{
public long TotalMemoryMB;
public long UsedMemoryMB;
}
private MemoryInfo GetMemoryInfo()
{
MemoryInfo memoryInfo = new();
ProcessStartInfo processStartInfo = new ProcessStartInfo();
var processStartInfoOutput = "";
if (PlatformUtil.RunningOnWindows)
{
processStartInfo.FileName = "wmic";
processStartInfo.Arguments = "OS GET FreePhysicalMemory,TotalVisibleMemorySize /Value";
processStartInfo.RedirectStandardOutput = true;
using (var process = Process.Start(processStartInfo))
{
processStartInfoOutput = process.StandardOutput.ReadToEnd();
}
var processStartInfoOutputString = processStartInfoOutput.Trim().Split("\n");
var freeMemory = Int32.Parse(processStartInfoOutputString[0].Split("=", StringSplitOptions.RemoveEmptyEntries)[1]);
var totalMemory = Int32.Parse(processStartInfoOutputString[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1]);
memoryInfo.TotalMemoryMB = totalMemory / 1024;
memoryInfo.UsedMemoryMB = (totalMemory - freeMemory) / 1024;
}
if (PlatformUtil.RunningOnLinux)
{
// Some compact Linux distributions like UBI may not have "free" utility installed, or it may have a custom output
// We don't want to break currently existing pipelines with ADO warnings
// so related errors thrown here will be sent to the trace or debug logs by caller methods
try
{
processStartInfo.FileName = "free";
processStartInfo.Arguments = "-m";
processStartInfo.RedirectStandardOutput = true;
using (var process = Process.Start(processStartInfo))
{
processStartInfoOutput = process.StandardOutput.ReadToEnd();
}
var processStartInfoOutputString = processStartInfoOutput.Split("\n");
var memoryInfoString = processStartInfoOutputString[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
if (memoryInfoString.Length != 7)
{
throw new Exception("\"free\" utility has non-default output");
}
memoryInfo.TotalMemoryMB = Int32.Parse(memoryInfoString[1]);
memoryInfo.UsedMemoryMB = Int32.Parse(memoryInfoString[2]);
}
catch (Win32Exception ex)
{
throw new Exception($"\"free\" utility is unavailable. Exception: {ex.Message}");
}
}
if (PlatformUtil.RunningOnMacOS)
{
// vm_stat allows to get the most detailed information about memory usage on MacOS
// but unfortunately it returns values in pages and has no built-in arguments for custom output
// so we need to parse and cast the output manually
processStartInfo.FileName = "vm_stat";
processStartInfo.RedirectStandardOutput = true;
using (var process = Process.Start(processStartInfo))
{
processStartInfoOutput = process.StandardOutput.ReadToEnd();
}
var processStartInfoOutputString = processStartInfoOutput.Split("\n");
var pageSize = Int32.Parse(processStartInfoOutputString[0].Split(" ", StringSplitOptions.RemoveEmptyEntries)[7]);
var pagesFree = Int64.Parse(processStartInfoOutputString[1].Split(" ", StringSplitOptions.RemoveEmptyEntries)[2].Trim('.'));
var pagesActive = Int64.Parse(processStartInfoOutputString[2].Split(" ", StringSplitOptions.RemoveEmptyEntries)[2].Trim('.'));
var pagesInactive = Int64.Parse(processStartInfoOutputString[3].Split(" ", StringSplitOptions.RemoveEmptyEntries)[2].Trim('.'));
var pagesSpeculative = Int64.Parse(processStartInfoOutputString[4].Split(" ", StringSplitOptions.RemoveEmptyEntries)[2].Trim('.'));
var pagesWiredDown = Int64.Parse(processStartInfoOutputString[6].Split(" ", StringSplitOptions.RemoveEmptyEntries)[3].Trim('.'));
var pagesOccupied = Int64.Parse(processStartInfoOutputString[16].Split(" ", StringSplitOptions.RemoveEmptyEntries)[4].Trim('.'));
var freeMemory = (pagesFree + pagesInactive) * pageSize;
var usedMemory = (pagesActive + pagesSpeculative + pagesWiredDown + pagesOccupied) * pageSize;
memoryInfo.TotalMemoryMB = (freeMemory + usedMemory) / 1048576;
memoryInfo.UsedMemoryMB = usedMemory / 1048576;
}
return memoryInfo;
}
private string GetMemoryInfoString()
{
try
{
var memoryInfo = GetMemoryInfo();
return StringUtil.Loc("ResourceMonitorMemoryInfo", $"{memoryInfo.UsedMemoryMB:0.00}", $"{memoryInfo.TotalMemoryMB:0.00}");
}
catch (Exception ex)
{
return StringUtil.Loc("ResourceMonitorMemoryInfoError", ex.Message);
}
}
public void Dispose()
{
_currentProcess?.Dispose();
}
}
}