-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathHostPerformanceManager.cs
More file actions
209 lines (182 loc) · 8.4 KB
/
Copy pathHostPerformanceManager.cs
File metadata and controls
209 lines (182 loc) · 8.4 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Azure.WebJobs.Script.Extensions;
using Microsoft.Azure.WebJobs.Script.Workers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Microsoft.Azure.WebJobs.Script.Scale
{
public class HostPerformanceManager : IDisposable
{
private readonly IEnvironment _environment;
private readonly IOptions<HostHealthMonitorOptions> _healthMonitorOptions;
private readonly IServiceProvider _serviceProvider;
private bool _disposed = false;
public HostPerformanceManager(IEnvironment environment, IOptions<HostHealthMonitorOptions> healthMonitorOptions, IServiceProvider serviceProvider)
{
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
if (healthMonitorOptions == null)
{
throw new ArgumentNullException(nameof(healthMonitorOptions));
}
_environment = environment;
_healthMonitorOptions = healthMonitorOptions;
_serviceProvider = serviceProvider;
}
/// <summary>
/// Check sandbox enforced performance counters
/// </summary>
public virtual bool PerformanceCountersExceeded(Collection<string> exceededCounters = null, ILogger logger = null)
{
var counters = GetPerformanceCounters(logger);
if (counters != null)
{
return PerformanceCounterThresholdsExceeded(counters, exceededCounters, _healthMonitorOptions.Value.CounterThreshold);
}
return false;
}
/// <summary>
/// Check both sandbox enforced performance counters as well as process level thresholds
/// like CPU, memory, etc.
/// </summary>
public virtual async Task<bool> IsUnderHighLoadAsync(ILogger logger = null)
{
return PerformanceCountersExceeded(logger: logger) || await ProcessThresholdsExceeded(logger: logger);
}
public async Task<IActionResult> TryHandleHealthPingAsync(HttpRequest request, ILogger logger)
{
var healthPingEnabled = _environment.GetEnvironmentVariableOrDefault(EnvironmentSettingNames.HealthPingEnabled, "1");
if (healthPingEnabled.Equals("0"))
{
// disabled at app level
return null;
}
bool checkHealth = false;
var userAgent = request.GetHeaderValueOrDefault("User-Agent");
if (!string.IsNullOrEmpty(userAgent) &&
(userAgent.IndexOf(ScriptConstants.HttpScaleUserAgent, StringComparison.OrdinalIgnoreCase) != -1 ||
userAgent.IndexOf(ScriptConstants.ScaleControllerUserAgent, StringComparison.OrdinalIgnoreCase) != -1))
{
// for these user agents, we default to true
checkHealth = true;
}
var query = request.GetQueryCollectionAsDictionary();
if (query.TryGetValue(ScriptConstants.HealthCheckQueryParam, out string value))
{
// header overrides user agent
checkHealth = value.Equals("1");
}
if (checkHealth)
{
// check host + worker health
int statusCode = (int)HttpStatusCode.OK;
if (await IsUnderHighLoadAsync(logger: logger))
{
statusCode = 429;
}
return new StatusCodeResult(statusCode);
}
return null;
}
internal async Task<bool> ProcessThresholdsExceeded(ILogger logger = null)
{
var workerManager = _serviceProvider.GetScriptHostServiceOrNull<IScriptHostWorkerManager>();
if (workerManager != null)
{
// TEMP: This call pings all the OOP workers, to ensure we include any channel latency
// in the upstream ping result.
// Once the WorkerChannelThrottleProvider is fully implemented, this call can be removed.
await workerManager.GetWorkerStatusesAsync();
}
// ThrottleManager internally consults various throttle providers that check
// Host/Worker CPU health, ThreadPool health, as well as OOP worker channel health.
// ThrottleManager is a ScriptHost level service, so may not be available if the host
// is not running.
var throttleManager = _serviceProvider.GetScriptHostServiceOrNull<IConcurrencyThrottleManager>();
if (throttleManager != null)
{
var status = throttleManager.GetStatus();
return status.State == ThrottleState.Enabled;
}
return false;
}
internal static bool PerformanceCounterThresholdsExceeded(ApplicationPerformanceCounters counters, Collection<string> exceededCounters = null, float threshold = HostHealthMonitorOptions.DefaultCounterThreshold)
{
bool exceeded = false;
// determine all counters whose limits have been exceeded
exceeded |= ThresholdExceeded("ActiveConnections", counters.ActiveConnections, counters.ActiveConnectionLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("Connections", counters.Connections, counters.ConnectionLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("Threads", counters.Threads, counters.ThreadLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("Processes", counters.Processes, counters.ProcessLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("NamedPipes", counters.NamedPipes, counters.NamedPipeLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("Sections", counters.Sections, counters.SectionLimit, threshold, exceededCounters);
exceeded |= ThresholdExceeded("RemoteDirMonitors", counters.RemoteDirMonitors, counters.RemoteDirMonitorLimit, threshold, exceededCounters);
return exceeded;
}
internal static bool ThresholdExceeded(string name, long currentValue, long limit, float threshold, Collection<string> exceededCounters = null)
{
if (limit <= 0)
{
// no limit to apply
return false;
}
float currentUsage = (float)currentValue / limit;
bool exceeded = currentUsage > threshold;
if (exceeded && exceededCounters != null)
{
exceededCounters.Add(name);
}
return exceeded;
}
internal ApplicationPerformanceCounters GetPerformanceCounters(ILogger logger = null)
{
string json = _environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteAppCountersName);
if (!string.IsNullOrEmpty(json))
{
try
{
// TEMP: need to parse this specially to work around bug where
// sometimes an extra garbage character occurs after the terminal
// brace
int idx = json.LastIndexOf('}');
if (idx > 0)
{
json = json.Substring(0, idx + 1);
}
return JsonConvert.DeserializeObject<ApplicationPerformanceCounters>(json);
}
catch (JsonReaderException ex)
{
logger.LogError(ex, "Failed to deserialize application performance counters. JSON Content: \"{json}\"", json);
}
}
return null;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}