forked from Inedo/bmx-azurelegacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAzureAction.cs
222 lines (202 loc) · 9.59 KB
/
AzureAction.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
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Threading;
using System.Text;
using System.IO;
using System.Linq;
using Inedo.BuildMaster;
using Inedo.BuildMaster.Extensibility.Actions;
using Inedo.BuildMaster.Extensibility.Agents;
using Inedo.BuildMaster.Data;
namespace Inedo.BuildMasterExtensions.Azure
{
public abstract class AzureAction : RemoteActionBase
{
internal protected enum RequestType { Get, Post, Delete };
internal AzureConfigurer TestConfigurer { get; set; }
protected static string OperationVersion = "2012-03-01";
protected static XNamespace ns = "http://schemas.microsoft.com/windowsazure";
[Persistent]
public AzureAuthentication ActionCredentials {get;set;}
protected AzureConfigurer Configurer
{
get
{
if (this.IsExecuting)
{
return this.GetExtensionConfigurer() as AzureConfigurer;
}
else
{
var typ = typeof(AzureConfigurer);
var profiles = StoredProcs
.ExtensionConfiguration_GetConfigurations(typ.FullName + "," + typ.Assembly.GetName().Name)
.Execute();
var configurer =
profiles.FirstOrDefault(p => p.Default_Indicator.Equals(Domains.YN.Yes)) ?? profiles.FirstOrDefault();
if (configurer == null)
return null;
return (AzureConfigurer)Util.Persistence.DeserializeFromPersistedObjectXml(configurer.Extension_Configuration);
}
}
}
protected AzureAuthentication Credentials
{
get
{
// use local first
if (null != ActionCredentials)
return ActionCredentials;
return Configurer.Credentials;
}
}
protected string ResolveDirectory(string FilePath)
{
using (var sourceAgent2 = Util.Agents.CreateLocalAgent())
{
var sourceAgent = sourceAgent2.GetService<IFileOperationsExecuter>();
char srcSeparator = sourceAgent.GetDirectorySeparator();
var srcPath = sourceAgent.GetWorkingDirectory(this.Context.ApplicationId, this.Context.DeployableId ?? 0, FilePath);
LogInformation("Source Path: " + srcPath);
return srcPath;
}
}
internal protected IDictionary<string, string> ListLocations()
{
Dictionary<string,string> retVal = new Dictionary<string,string>();
var resp = AzureRequest(RequestType.Get, null, "https://management.core.windows.net/{0}/locations");
if (HttpStatusCode.OK == resp.StatusCode)
{
XElement locations = resp.Document.Element(ns + "Locations");
foreach (XElement location in locations.Elements(ns + "Location"))
{
retVal.Add(location.Element(ns + "Name").Value, location.Element(ns + "DisplayName").Value);
}
}
return retVal;
}
internal protected IDictionary<string, string> ListAffinityGroups()
{
Dictionary<string, string> retVal = new Dictionary<string, string>();
var resp = AzureRequest(RequestType.Get, null, "https://management.core.windows.net/{0}/affinitygroups");
if (HttpStatusCode.OK == resp.StatusCode)
{
XElement groups = resp.Document.Element(ns + "AffinityGroups");
foreach (XElement group in groups.Elements(ns + "AffinityGroup"))
{
retVal.Add(group.Element(ns + "Name").Value, group.Element(ns + "Description").Value);
}
}
return retVal;
}
internal protected AzureResponse WaitForRequestCompletion(string RequestID)
{
AzureResponse retVal = new AzureResponse() { OperationStatus = AzureResponse.OperationStatusResult.Failed, ErrorCode = "-1", ErrorMessage = "General Failure" };
try
{
bool done = false;
var startTime = DateTime.Now;
while (!done)
{
if (DateTime.Now.Subtract(startTime) > TimeSpan.FromHours(24))
throw new Exception(string.Format("Wait For Completion timeout error. The build has taken more than 24 hours."));
var resp = AzureRequest(RequestType.Get, null, "https://management.core.windows.net/{0}/operations/{1}",RequestID);
if (HttpStatusCode.OK != resp.StatusCode)
{
LogError("HTTP Error {0} waiting for the completion of request {1}", resp.StatusCode, RequestID);
retVal.ErrorMessage = string.Format("HTTP Error {0} waiting for the completion of request {1}", resp.StatusCode, RequestID);
done = true;
}
else
{
var result = (AzureResponse.OperationStatusResult)Enum.Parse(typeof(AzureResponse.OperationStatusResult), resp.Document.Root.Element(ns + "Status").Value);
if (AzureResponse.OperationStatusResult.InProgress == result)
Thread.Sleep(2000);
else
{
retVal.OperationStatus = result;
retVal.Document = resp.Document;
retVal.StatusCode = (HttpStatusCode) Enum.Parse(typeof(HttpStatusCode), resp.Document.Root.Element(ns + "HttpStatusCode").Value);
if (AzureResponse.OperationStatusResult.Succeeded == result)
{
retVal.ErrorCode = string.Empty;
retVal.ErrorMessage = string.Empty;
LogInformation("Succeeded waiting for request {0}",RequestID);
}
else
{
retVal.ErrorCode = resp.Document.Root.Element(ns + "Code").Value;
retVal.ErrorMessage = resp.Document.Root.Element(ns + "Message").Value;
LogInformation("Failed waiting for request {0}. Error code is {1} and message is: {2}",RequestID,retVal.ErrorCode,retVal.ErrorMessage);
}
done = true;
}
}
}
}
catch (Exception ex)
{
LogError("Unable to wait for the completion of request {0}. Error is: {1}", RequestID, ex.ToString());
}
return retVal;
}
internal AzureResponse AzureRequest(RequestType RequestType, string Payload, string UriFormat, params object[] args)
{
AzureResponse retval = new AzureResponse();
var newargs = new List<object>();
newargs.Add(Credentials.SubscriptionID);
var uri = new Uri(string.Format(UriFormat,newargs.Concat(args).ToArray<object>()));
var req = (HttpWebRequest)HttpWebRequest.Create(uri);
switch (RequestType)
{
case AzureAction.RequestType.Get :
req.Method = "GET";
break;
case AzureAction.RequestType.Post :
req.Method = "POST";
break;
case AzureAction.RequestType.Delete :
req.Method = "DELETE";
break;
default :
req.Method = "GET";
break;
}
req.Headers.Add("x-ms-version", OperationVersion);
req.ClientCertificates.Add(this.Credentials.Certificate);
req.ContentType = "application/xml";
if(!string.IsNullOrEmpty(Payload))
{
var buffer = Encoding.UTF8.GetBytes(Payload);
req.ContentLength = buffer.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException ex)
{
resp = (HttpWebResponse)ex.Response;
}
retval.StatusCode = resp.StatusCode;
retval.Headers = resp.Headers;
if (resp.ContentLength > 0)
{
using (XmlReader reader = XmlReader.Create(resp.GetResponseStream()))
{
retval.Document = XDocument.Load(reader);
retval.ErrorMessage = (string)retval.Document.Descendants(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")).FirstOrDefault();
retval.ErrorCode = (string)retval.Document.Descendants(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")).FirstOrDefault();
}
}
return retval;
}
}
}