-
Notifications
You must be signed in to change notification settings - Fork 0
/
HealthHistoryCrawler.cs
296 lines (244 loc) · 11.4 KB
/
HealthHistoryCrawler.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace CeruleanSurprise
{
public class TableStatusHistory : TableEntity
{
public TableStatusHistory(Value historyValue)
{
// '/' is a reserved character in azure table rows
this.PartitionKey = System.Text.RegularExpressions.Regex.Replace(historyValue.Id, "/", "|");
this.RowKey = historyValue.Properties.OccuredTime.ToString("u");
this.Resource = historyValue.Id.Split('/')[8];
this.AvailabilityState = historyValue.Properties.AvailabilityState;
this.DetailedStatus = historyValue.Properties.DetailedStatus;
this.ReasonChronicity = historyValue.Properties.ReasonChronicity;
this.ReasonType = historyValue.Properties.ReasonType;
this.ResolutionEta = historyValue.Properties.ResolutionEta;
this.Summary = historyValue.Properties.Summary;
}
public TableStatusHistory() { }
public string Resource { get; set; }
public string AvailabilityState { get; set; }
public string ReasonChronicity { get; set; }
public string DetailedStatus { get; set; }
public string ReasonType { get; set; }
public DateTimeOffset? ResolutionEta { get; set; }
public string Summary { get; set; }
}
public partial class StatusHistory
{
[JsonProperty("value")]
public List<Value> Value { get; set; }
}
public partial class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("properties")]
public Properties Properties { get; set; }
}
public partial class Properties
{
[JsonProperty("availabilityState")]
public string AvailabilityState { get; set; }
[JsonProperty("summary")]
public string Summary { get; set; }
[JsonProperty("reasonType", NullValueHandling = NullValueHandling.Ignore)]
public string ReasonType { get; set; }
[JsonProperty("reasonChronicity")]
public string ReasonChronicity { get; set; }
[JsonProperty("detailedStatus")]
public string DetailedStatus { get; set; }
[JsonProperty("occuredTime")]
public DateTimeOffset OccuredTime { get; set; }
[JsonProperty("reportedTime", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? ReportedTime { get; set; }
[JsonProperty("rootCauseAttributionTime", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? RootCauseAttributionTime { get; set; }
[JsonProperty("resolutionETA", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? ResolutionEta { get; set; }
[JsonProperty("serviceImpactingEvents", NullValueHandling = NullValueHandling.Ignore)]
public List<ServiceImpactingEvent> ServiceImpactingEvents { get; set; }
}
public partial class ServiceImpactingEvent
{
[JsonProperty("eventStartTime")]
public DateTimeOffset EventStartTime { get; set; }
[JsonProperty("eventStatusLastModifiedTime")]
public DateTimeOffset EventStatusLastModifiedTime { get; set; }
[JsonProperty("correlationId")]
public Guid CorrelationId { get; set; }
[JsonProperty("status")]
public Status Status { get; set; }
[JsonProperty("incidentProperties")]
public IncidentProperties IncidentProperties { get; set; }
}
public partial class IncidentProperties
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("service")]
public string Service { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("incidentType")]
public string IncidentType { get; set; }
}
public partial class Status
{
[JsonProperty("value")]
public string Value { get; set; }
}
internal static class Utilities
{
internal static HttpClient client = new HttpClient();
internal static Tuple<string, AzureCredentials, IConfigurationRoot> InitializeApiObjects(Microsoft.Azure.WebJobs.ExecutionContext context)
{
var tokenProvider = new AzureServiceTokenProvider();
var accessToken = tokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
var credentials = new Microsoft.Rest.TokenCredentials(accessToken, "Bearer");
var azureCreds = new AzureCredentials(credentials, credentials, credentials.TenantId, AzureEnvironment.AzureGlobalCloud);
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
return new Tuple<string, AzureCredentials, IConfigurationRoot>(accessToken, azureCreds, config);
}
internal static async Task<HttpResponseMessage> GetHttpAsyncWithRetry(string url, string bearerToken, TraceWriter log, int retries = 5)
{
while (true)
{
var result = await client.GetAsync(url);
if (result.IsSuccessStatusCode)
{
return result;
}
else if ((int)result.StatusCode == 429) // We have performed too many requests
{
//Microsoft often returns Retry-After values upwards of twenty minutes, so we ignore it.
retries--;
await Task.Delay(60000);
}
else
{
retries--;
await Task.Delay(5000);
}
if (retries == 0) { return result; }
}
}
}
[StorageAccount("AzureWebJobsStorage")]
public static class HealthHistoryCrawler
{
private const string ApiVersion = "2015-01-01";
private static List<Task<HttpResponseMessage>> GetHealthStatuses(AzureCredentials azureCredentials, string bearerToken, TraceWriter log)
{
var azure = Azure.Configure()
.Authenticate(azureCredentials)
.WithDefaultSubscription();
var healthTasks = new List<Task<HttpResponseMessage>>();
foreach (var subscription in azure.Subscriptions.List())
{
log.Info($"Fetching subscripiton: {subscription.SubscriptionId}");
azure = Azure.Configure()
.Authenticate(azureCredentials)
.WithSubscription(subscription.SubscriptionId);
var vms = azure.VirtualMachines.List();
foreach (var vm in vms)
{
string url = $"https://management.azure.com/{vm.Id}/Providers/Microsoft.ResourceHealth/availabilityStatuses?api-version={ApiVersion}";
healthTasks.Add(Utilities.GetHttpAsyncWithRetry(url, bearerToken, log));
}
}
return healthTasks;
}
private static List<Task<TableResult>> InsertHealthStatuses(List<Task<HttpResponseMessage>> healthTasks, CloudTable table, TraceWriter log)
{
var insertTasks = new List<Task<TableResult>>();
foreach (Task<HttpResponseMessage> task in healthTasks)
{
var response = task.Result;
if (!response.IsSuccessStatusCode) { continue; }
var payload = response.Content.ReadAsStringAsync().Result;
StatusHistory history = JsonConvert.DeserializeObject<StatusHistory>(payload);
foreach (var value in history.Value)
{
//Current statuses have variable timestamps and result in large numbers of duplicate entries
if (value.Id.ToLower().Contains("current")) { continue; }
TableStatusHistory tableHistory = new TableStatusHistory(value);
TableOperation insert = TableOperation.Insert(tableHistory);
insertTasks.Add(table.ExecuteAsync(insert));
}
}
return insertTasks;
}
[FunctionName("HealthHistoryCrawler")]
public static void Run([TimerTrigger("0 30 9 * * *", RunOnStartup = false)]TimerInfo myTimer, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext context)
{
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
var clock = new Stopwatch();
clock.Start();
var apiObjects = Utilities.InitializeApiObjects(context);
string bearerToken = apiObjects.Item1;
AzureCredentials azureCredentials = apiObjects.Item2;
IConfigurationRoot configuration = apiObjects.Item3;
var azure = Azure.Configure()
.Authenticate(azureCredentials)
.WithDefaultSubscription();
log.Info($"Instantiating table client: {clock.ElapsedMilliseconds}ms");
var storage = CloudStorageAccount.Parse(configuration["AzureWebJobsStorage"]);
var tableClient = storage.CreateCloudTableClient();
var table = tableClient.GetTableReference("ResourceHealthHistory");
var tableTask = table.CreateIfNotExistsAsync();
log.Info($"Fetching health statuses: {clock.ElapsedMilliseconds}ms");
var healthTasks = GetHealthStatuses(azureCredentials, bearerToken, log);
Task.WaitAll(healthTasks.ToArray());
log.Info($"Fetched health statuses: {clock.ElapsedMilliseconds}ms");
tableTask.Wait();
log.Info($"Inserting statuses: {clock.ElapsedMilliseconds}ms");
var insertTasks = InsertHealthStatuses(healthTasks, table, log);
try
{
Task.WaitAll(insertTasks.ToArray());
log.Info($"Inserted: {clock.ElapsedMilliseconds}ms");
}
catch (Microsoft.WindowsAzure.Storage.StorageException err)
{
log.Info(err.RequestInformation.ExtendedErrorInformation.ToString());
}
catch (Exception err)
{
log.Info(err.InnerException.ToString());
}
}
}
}