-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_trigger.cs
More file actions
228 lines (200 loc) · 12 KB
/
Copy pathhttp_trigger.cs
File metadata and controls
228 lines (200 loc) · 12 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
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Azure.Identity;
using System.Net.Http;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Models;
using Azure.Storage.Files.Shares;
using Azure.Storage.Sas;
using System.Linq;
namespace CustomScript.Webhook
{
public static class http_trigger
{
[FunctionName("http_trigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
log.LogInformation("Recieved an HTTP post, starting the function");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic trigger = JsonConvert.DeserializeObject(requestBody);
// From webhook
string resourceId = trigger.resourceId;
string triggerAction = trigger.action;
string scriptArguments = trigger.arguments;
try
{
// Convert to resourceId Object
ResourceId resourceIdObject = ResourceId.FromString(resourceId);
// Uri
Uri azureManagementUri = new Uri("https://management.azure.com/");
// Get action <=> scriptUri mapping
string mappingFilePath = Path.Combine(context.FunctionAppDirectory, "scripts/mapping.json");
var mapppingContent = System.IO.File.ReadAllText(mappingFilePath);
Mapping mapping = JsonConvert.DeserializeObject<Mapping>(mapppingContent);
MappingProperties scriptMapping = mapping.Action.Single(x => x.Name == triggerAction);
// Get Authentication Token
var defaultAzureCredential = new DefaultAzureCredential();
var token = defaultAzureCredential.GetToken(
new Azure.Core.TokenRequestContext(
new[] { (azureManagementUri.AbsoluteUri + ".default") }));
// Create HTTP Client
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.Token);
// Get machine properties
Uri azureRestVmUri = new Uri(azureManagementUri, (resourceId + "?api-version=2021-05-20"));
var machineResponse = await httpClient.GetAsync(azureRestVmUri);
machineResponse.EnsureSuccessStatusCode();
var machineResponseContent = await machineResponse.Content.ReadAsStringAsync();
Machine machine = JsonConvert.DeserializeObject<Machine>(machineResponseContent);
// If machine is offline?
if (machine.Properties.Status != "Connected")
{
FunctionResponse responseOffline = new FunctionResponse()
{
Result = "cancelled",
Description = "Machine is offline, cancelled the operation.",
ResourceId = machine.Id,
ResourceStatus = machine.Properties.Status
};
return new OkObjectResult(responseOffline);
}
// Get extension name and timestamp
string extensionName = "CustomScript";
int timestamp = 1;
foreach (MachineResource existingExtension in machine.Resources)
{
// Test if OS is linux or windows and has existing vm extension
if (machine.Properties.OsName == "windows" && existingExtension.Properties.Type == "CustomScriptExtension")
{
extensionName = existingExtension.Name;
if (existingExtension.Properties.Settings.GetType().GetProperty("Timestamp") != null)
{
timestamp = int.Parse(existingExtension.Properties.Settings.Timestamp) + 1;
}
// If existing vm extension is still executing or in an error state
if (existingExtension.Properties.ProvisioningState != "Succeeded"
&& existingExtension.Properties.ProvisioningState != "Failed")
{
FunctionResponse responseNotReady = new FunctionResponse()
{
Result = "cancelled",
Description = "The VM Extension on the machine is not ready",
ResourceId = machine.Id,
ResourceStatus = machine.Properties.Status,
ExtensionResourceId = existingExtension.Id,
ExtensionResourceProvisioningState = existingExtension.Properties.ProvisioningState
};
return new OkObjectResult(responseNotReady);
}
}
else if (machine.Properties.OsName == "linux" && existingExtension.Properties.Type == "CustomScript")
{
extensionName = existingExtension.Name;
if (existingExtension.Properties.Settings.GetType().GetProperty("Timestamp") != null)
{
timestamp = int.Parse(existingExtension.Properties.Settings.Timestamp) + 1;
}
// If existing vm extension is still executing or in an error state
if (existingExtension.Properties.ProvisioningState != "Succeeded"
&& existingExtension.Properties.ProvisioningState != "Failed")
{
FunctionResponse responseNotReady = new FunctionResponse()
{
ResourceId = machine.Id,
ResourceStatus = machine.Properties.Status,
ExtensionResourceId = existingExtension.Id,
ExtensionResourceProvisioningState = existingExtension.Properties.ProvisioningState
};
return new OkObjectResult(responseNotReady);
}
}
else { }
}
// Get Script Uri
string scriptAbsoluteUri = "";
Uri scriptUri;
if (machine.Properties.OsName == "windows") { scriptAbsoluteUri = scriptMapping.WindowsScriptUri; }
else if (machine.Properties.OsName == "linux") { scriptAbsoluteUri = scriptMapping.LinuxScriptUri; }
// Get string file name
// If scriptUri is set to built-in, create SAS token for script.
string scriptFileName = "";
if (scriptAbsoluteUri == "built-in")
{
// SAS config
if (machine.Properties.OsName == "windows") { scriptFileName = triggerAction + ".ps1"; }
else if (machine.Properties.OsName == "linux") { scriptFileName = triggerAction + ".sh"; }
ShareFileClient shareFileClient = new ShareFileClient(Environment.GetEnvironmentVariable("WEBSITE_CONTENTAZUREFILECONNECTIONSTRING"), Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE"), $"site/wwwroot/scripts/{machine.Properties.OsName}/{scriptFileName}");
var sasUri = shareFileClient.GenerateSasUri(ShareFileSasPermissions.Read, DateTimeOffset.UtcNow.AddMinutes(10));
scriptUri = sasUri;
}
else
{
scriptUri = new Uri(scriptAbsoluteUri);
}
// Deployment
string templateFilePath = "";
if (machine.Properties.OsName == "windows") { templateFilePath = Path.Combine(context.FunctionAppDirectory, "vmextension-template/windows.json"); }
else if (machine.Properties.OsName == "linux") { templateFilePath = Path.Combine(context.FunctionAppDirectory, "vmextension-template/windows.json"); }
var templateContent = System.IO.File.ReadAllText(templateFilePath);
dynamic templateContentJObject = JsonConvert.DeserializeObject(templateContent);
DeploymentInner deploymentBody = new DeploymentInner
{
//Location = machine.Location,
Properties = new DeploymentProperties
{
Template = templateContentJObject, //templateContentObject.ToString(Formatting.None),
Mode = DeploymentMode.Incremental,
Parameters = new DeploymentParameters
{
VmName = new DeploymentParameter { Value = resourceIdObject.Name },
Location = new DeploymentParameter { Value = machine.Location },
VmExtensionName = new DeploymentParameter { Value = extensionName },
Timestamp = new DeploymentParameter { Value = timestamp.ToString() },
ScriptUri = new DeploymentParameter { Value = scriptUri.AbsoluteUri },
ScriptName = new DeploymentParameter { Value = Path.GetFileName(scriptUri.LocalPath) },
ScriptArguments = new DeploymentParameter { Value = scriptArguments }
}
}
};
var deplopymentBody = new StringContent(JsonConvert.SerializeObject(deploymentBody), System.Text.Encoding.UTF8, "application/json");
string deploymentName = "vm-extension-" + resourceIdObject.Name + "-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss");
Uri azureRestDeploymentUri = new Uri(azureManagementUri, $"/subscriptions/{resourceIdObject.SubscriptionId}/resourcegroups/{resourceIdObject.ResourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}?api-version=2021-04-01");
var deploymentResponse = await httpClient.PutAsync(azureRestDeploymentUri, deplopymentBody);
deploymentResponse.EnsureSuccessStatusCode();
var deploymentResponseContent = await deploymentResponse.Content.ReadAsStringAsync();
dynamic deploymentResponseJObject = JsonConvert.DeserializeObject(deploymentResponseContent);
string responseMessage = deploymentResponseContent;
FunctionResponse responseAccept = new FunctionResponse()
{
Result = "accepted",
Description = deploymentResponseContent,
ResourceId = machine.Id,
ResourceStatus = machine.Properties.Status
};
return new OkObjectResult(responseAccept);
}
catch (Exception ex)
{
log.LogError($"Caught exception: {ex.Message}");
FunctionResponse responseError = new FunctionResponse()
{
Result = "error",
Description = ex.Message,
ResourceId = resourceId
};
return new BadRequestObjectResult(responseError);
}
}
}
}