-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFunctions.cs
230 lines (205 loc) · 11.2 KB
/
Functions.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using azman_v2.Model;
using Alexa.NET.Request;
using Alexa.NET.Request.Type;
using Alexa.NET;
using Alexa.NET.Response;
using System.Text;
namespace azman_v2
{
public class Functions
{
private readonly IScanner _scanner;
private readonly IResourceManagementService _resourceManager;
private readonly ILogger<Functions> _log;
private readonly INotifier _notifier;
public Functions(IScanner scanner, IResourceManagementService manager, ILoggerFactory loggerFactory, INotifier notifier)
{
_scanner = scanner;
_resourceManager = manager;
_log = loggerFactory.CreateLogger<Functions>();
_notifier = notifier;
}
[FunctionName("OnResourceGroupCreate")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[Queue("%ResourceGroupCreatedQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<TagSuiteModel> outboundQueue)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
_log.LogTrace($"Received payload: {requestBody}");
dynamic alert = JsonSerializer.Deserialize<dynamic>(requestBody);
var tagRequest = _resourceManager.ProcessAlert(alert);
if (tagRequest.HasValue)
{
await outboundQueue.AddAsync(tagRequest.Value);
}
// ready to do work
return new OkObjectResult(new { });
}
[FunctionName("TagResourceGroup")]
public async Task TagResourceGroup(
[QueueTrigger("%ResourceGroupCreatedQueueName%", Connection = "MainStorageConnection")] TagSuiteModel request
)
{
await _resourceManager.AddTagSuite(request);
}
[FunctionName("ScannerUntagged")]
public async Task FindUntaggedResources([TimerTrigger("0 */5 * * * *")] TimerInfo timer,
[Queue("%ResourceGroupCreatedQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<TagSuiteModel> outboundQueue
)
{
_log.LogTrace($"ScannerUntagged timer past due: {timer.IsPastDue}; next run: {timer.Schedule.GetNextOccurrence(DateTime.UtcNow)}");
var untaggedResources = await _scanner.ScanForUntaggedResources();
// output to tag queue -->
var resourcesToTag = untaggedResources.Select(x => new TagSuiteModel(
subscriptionId: x.SubscriptionId,
groupName: x.ResourceId,
managementDate: DateTime.UtcNow,
user: "thrazman"
));
await outboundQueue.AddRangeAsync(resourcesToTag);
}
[FunctionName("ScannerExpired")]
public async Task FindExpired(
[TimerTrigger("0 11 * * *")] TimerInfo timer,
[Queue("%ResourceGroupExpiredQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<ResourceSearchResult> outboundQueue
)
{
_log.LogTrace($"ScannerExpired timer past due: {timer.IsPastDue}; next run: {timer.Schedule.GetNextOccurrence(DateTime.UtcNow)}");
var resourcesPastExpirationDate = await _scanner.ScanForExpiredResources(DateTime.UtcNow);
// output to expired queue -->
var resourcesToTag = resourcesPastExpirationDate.Select(x => new ResourceSearchResult(
subscriptionId: x.SubscriptionId,
resourceId: x.ResourceId
));
await outboundQueue.AddRangeAsync(resourcesToTag);
}
[FunctionName("ScannerUpcomingDeletion")]
public async Task FindUpcoming(
[TimerTrigger("%FindUpcomingSchedule%")] TimerInfo timer,
[Queue("%ResourceGroupNotifyQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<ResourceSearchResult> outboundQueue
)
{
_log.LogTrace($"ScannerUpcomingDeletion timer past due: {timer.IsPastDue}; next run: {timer.Schedule.GetNextOccurrence(DateTime.UtcNow)}");
var resourcesNearDeletion = await _scanner.ScanForExpiredResources(DateTime.UtcNow);
// output to notification queue -->
var resourcesToTag = resourcesNearDeletion.Select(x => new ResourceSearchResult(
subscriptionId: x.SubscriptionId,
resourceId: x.ResourceId
));
await outboundQueue.AddRangeAsync(resourcesToTag);
}
[FunctionName("NotifyExpiration")]
public async Task Notify([QueueTrigger("%ResourceGroupNotifyQueueName%", Connection = "MainStorageConnection")] ResourceSearchResult request)
{
// query for resource
var group = await _resourceManager.GetResourceGroup(request.SubscriptionId, request.ResourceId);
var expirationDate = group.Tags.FirstOrDefault(x => x.Key == "expires").Value;
var hasExpired = DateTime.TryParse(expirationDate, out var exp) && exp < DateTime.UtcNow;
var previouslyNotified = await _resourceManager.GetTagValue(request.SubscriptionId, request.ResourceId, "notified", x => bool.Parse(x), () => false);
_log.LogTrace($"{request.ResourceId} in {request.SubscriptionId} has been notified of impending deletion previously: {previouslyNotified}");
if (previouslyNotified) return;
var message = new StringBuilder();
message.Append("THRAZMAN HERE. ");
message.Append(group.Name);
if (hasExpired)
{
message.Append($" expired on {exp.ToShortDateString()} and will be deleted shortly.");
}
else
{
message.Append($" will expire on {exp.ToShortDateString()}. Extend the date before then to keep the resources.");
}
// build message
await _notifier.Notify(new NotificationMessage()
{
Message = message.ToString()
});
// prevent duplicates
await _resourceManager.AddTags(request.ResourceId, request.SubscriptionId, new KeyValuePair<string, string>("notified", "true"));
}
// todo: best candidate for durable functions
[FunctionName("ResourceGroupExpired")]
public async Task ResourceGroupExpired(
[QueueTrigger("%ResourceGroupExpiredQueueName%", Connection = "MainStorageConnection")] ResourceSearchResult request,
[Queue("%ResourceGroupPersistQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<ResourceSearchResult> persistQueue,
[Queue("%ResourceGroupNotifyQueueName%", Connection = "MainStorageConnection")] IAsyncCollector<ResourceSearchResult> notifyQueue
) // at this point, the deletion is committed and will happen
{
// notify deletion --> this
await notifyQueue.AddAsync(request);
// persist resource group template to storage --> that
await persistQueue.AddAsync(request);
// queue up for deletion --> don't do this until this and that are done
}
[FunctionName("PersistResourceGroupToStorage")]
public async Task PersistResourceGroupToStorage([QueueTrigger("%ResourceGroupPersistQueueName%", Connection = "MainStorageConnection")] ResourceSearchResult request, Binder binder)
{
_log.LogTrace($"Exporting template for {request.ResourceId} in {request.SubscriptionId}");
// get template from ARM
var previouslyExported = await _resourceManager.GetTagValue(request.SubscriptionId, request.ResourceId, "exported", x => bool.Parse(x), () => false);
_log.LogTrace($"Template for {request.ResourceId} in {request.SubscriptionId} has been exported previously: {previouslyExported}");
if (previouslyExported) return;
var templateData = await _resourceManager.ExportResourceGroupTemplateByName(request.SubscriptionId, request.ResourceId);
if (string.IsNullOrWhiteSpace(templateData)) return;
var exportFilename = $"thrazman-export/{DateTime.UtcNow:yyyy-MM-dd}/{request.ResourceId}-{Guid.NewGuid().ToString().Substring(0, 8)}.json";
_log.LogTrace($"Got template data, writing to {exportFilename}");
var attributes = new Attribute[]
{
new BlobAttribute(exportFilename),
new StorageAccountAttribute("MainStorageConnection")
};
using var writer = await binder.BindAsync<TextWriter>(attributes).ConfigureAwait(false);
writer.Write(templateData);
await _resourceManager.AddTags(request.ResourceId, request.SubscriptionId, new KeyValuePair<string, string>("exported", "true"));
}
[FunctionName("AlexaEndpoint")]
public async Task<IActionResult> AlexaEndpoint([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
{
_log.LogTrace($"Recieved alexa request");
string json = await req.ReadAsStringAsync();
_log.LogTrace($"request: {json}");
var input = Newtonsoft.Json.JsonConvert.DeserializeObject<SkillRequest>(json);
//var input = JsonSerializer.Deserialize<SkillRequest>(json);
var requestType = input.GetRequestType();
if (requestType == typeof(LaunchRequest))
{
return new OkObjectResult(ResponseBuilder.Ask("THE THRAZ MAN COMES.", null));
}
var defaultResponse = ResponseBuilder.Ask("Do not anger thraz man with unclear instructions.", null);
if (!(input.Request is IntentRequest intentRequest)) return new OkObjectResult(defaultResponse);
switch (intentRequest.Intent.Name)
{
case "check_expiring":
{
var expiring = await _scanner.ScanForExpiredResources("now() + 3d");
var expiringNames = expiring.Select(x => x.ResourceId);
var response = ResponseBuilder.Tell($"You have {expiring.Count()} resources being nuked into orbit in the next three days: {string.Join(',', expiringNames)}. Why aren't these running in AWS?");
return new OkObjectResult(response);
}
case "whats_running":
{
return new OkObjectResult(ResponseBuilder.Tell("Thraz man knows when thraz man knows. Trust the process"));
}
case "delete_resource":
{
return new OkObjectResult(ResponseBuilder.Tell("Deleting your entire Azure subscription...J.K. Thraz man isn't ready to delete stuff yet.", null));
}
default:
{
return new OkObjectResult(defaultResponse);
}
}
//return new OkObjectResult(defaultResponse);
}
}
}