Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive.Azure/HeuristicLab.Clients.Hive.CloudManager/3.3/Azure/ServiceManagementOperation.cs @ 7424

Last change on this file since 7424 was 7421, checked in by spimming, 13 years ago

#1680:

  • GetOperationStatus method added
  • Check if affinity group is not null
File size: 23.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
26using System.Net;
27using System.Xml.Linq;
28using HeuristicLab.Clients.Hive.CloudManager.Model;
29
30namespace HeuristicLab.Clients.Hive.CloudManager.Azure {
31  public static class ServiceManagementOperation {
32
33    #region Namespaces
34
35    private static XNamespace wa = Constants.NSWindowsAzure;
36    private static XNamespace sc = Constants.NSSchemaMicrosoft;
37    private static XNamespace sh = Constants.NSServiceConfiguration;
38
39    #endregion
40
41    #region Public Methods
42
43    public static Subscription GetSubscriptionInfo(string subscriptionId, string thumbprint) {
44      string uri = string.Format(Constants.URISubscriptionFormat, subscriptionId);
45      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
46      XDocument response = operation.Invoke(uri);
47
48      Subscription subscription = new Subscription();
49      subscription.SubscriptionID = response.Descendants(wa + "SubscriptionID").Single().Value;
50      subscription.SubscriptionName = response.Descendants(wa + "SubscriptionName").Single().Value;
51      subscription.SubscriptionStatus = response.Descendants(wa + "SubscriptionStatus").Single().Value;
52      subscription.MaxCoreCount = Convert.ToInt32(response.Descendants(wa + "MaxCoreCount").Single().Value);
53      subscription.MaxHostedServices = Convert.ToInt32(response.Descendants(wa + "MaxHostedServices").Single().Value);
54      subscription.MaxStorageAccounts = Convert.ToInt32(response.Descendants(wa + "MaxStorageAccounts").Single().Value);
55      subscription.CurrentCoreCount = Convert.ToInt32(response.Descendants(wa + "CurrentCoreCount").Single().Value);
56      subscription.CurrentHostedServices = Convert.ToInt32(response.Descendants(wa + "CurrentHostedServices").Single().Value);
57      subscription.CurrentStorageAccounts = Convert.ToInt32(response.Descendants(wa + "CurrentStorageAccounts").Single().Value);
58      subscription.CertificateThumbprint = thumbprint;
59
60      return subscription;
61    }
62
63    public static List<string> ListLocations(string subscriptionId, string thumbprint) {
64      string uri = string.Format(Constants.URILocationsFormat, subscriptionId);
65      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
66      XDocument response = operation.Invoke(uri);
67      List<string> result = null;
68      if (response.Root.HasElements) {
69        result = (from s in response.Descendants(wa + "Name")
70                  select s.Value).ToList();
71      }
72      return result;
73    }
74
75    public static List<AffinityGroup> ListAffinityGroups(string subscriptionId, string thumbprint) {
76      string uri = String.Format(Constants.URIAffinityGroupFormat, subscriptionId);
77      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
78      XDocument response = operation.Invoke(uri);
79      List<AffinityGroup> result = null;
80      if (response.Root.HasElements) {
81        result = (from s in response.Elements()
82                  select new AffinityGroup() {
83                    Name = s.Descendants(wa + "Name").Single().Value,
84                    Label = Utils.ConvertFromBase64String(s.Descendants(wa + "Label").Single().Value),
85                    Description = s.Descendants(wa + "Description").Single().Value,
86                    Location = s.Descendants(wa + "Location").Single().Value
87                  }).ToList();
88      }
89      return result;
90    }
91
92    public static List<HostedService> ListHostedServices(string subscriptionId, string thumbprint) {
93      string uri = String.Format(Constants.URIHostedServiceFormat, subscriptionId);
94      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
95      XDocument response = operation.Invoke(uri);
96      List<HostedService> result = null;
97      if (response.Root.HasElements) {
98
99        result = (from s in response.Elements()
100                  select new HostedService() {
101                    ServiceName = s.Descendants(wa + "ServiceName").Single().Value,
102                    Url = s.Descendants(wa + "Url").Single().Value
103                  }).ToList();
104      }
105
106      if (result != null)
107        return result;
108      else
109        return new List<HostedService>();
110    }
111
112    public static HostedService GetHostedService(string subscriptionId, string thumbprint, string serviceName) {
113      string uri = String.Format(Constants.URISpecificHostedServiceFormat, subscriptionId, serviceName);
114      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
115      XDocument response = operation.Invoke(uri);
116      HostedService service = new HostedService();
117      service.ServiceName = response.Descendants(wa + "ServiceName").Single().Value;
118      service.Url = response.Descendants(wa + "Url").Single().Value;
119      return service;
120    }
121
122    public static HostedService GetHostedServiceDetailed(string subscriptionId, string thumbprint, string serviceName) {
123      string uri = String.Format(Constants.URISpecificHostedServiceFormat + "?embed-detail=true", subscriptionId, serviceName);
124      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
125      XDocument response = operation.Invoke(uri);
126      HostedService service = new HostedService();
127      service.ServiceName = response.Descendants(wa + "ServiceName").Single().Value;
128      service.Url = response.Descendants(wa + "Url").First().Value;
129      if (response.Root.Elements(wa + "HostedServiceProperties").Any()) {
130        XElement xHostedServiceProperties = response.Descendants(wa + "HostedServiceProperties").Single();
131        string loc = string.Empty, affgroup = string.Empty;
132        if (xHostedServiceProperties.HasElements) {
133          string desc = xHostedServiceProperties.Descendants(wa + "Description").Single().Value;
134          if (xHostedServiceProperties.Descendants(wa + "Location").Any()) {
135            loc = xHostedServiceProperties.Descendants(wa + "Location").Single().Value;
136          } else {
137            affgroup = xHostedServiceProperties.Descendants(wa + "AffinityGroup").Single().Value;
138          }
139          string lbl = Utils.ConvertFromBase64String(xHostedServiceProperties.Descendants(wa + "Label").Single().Value);
140          HostedServiceProperties props = new HostedServiceProperties() {
141            Description = desc,
142            Location = loc,
143            AffinityGroup = affgroup,
144            Label = lbl
145          };
146          service.HostedServiceProperties = props;
147        }
148      }
149
150      if (response.Root.Elements(wa + "Deployments").Any()) {
151        XElement xDeployments = response.Descendants(wa + "Deployments").Single();
152        if (xDeployments.HasElements) {
153          IEnumerable<Deployment> deps = (from s in xDeployments.Elements()
154                                          select GetDeploymentFromXml(s)).ToList();
155          service.Deployments = new List<Deployment>(deps);
156        } else {
157          service.Deployments = new List<Deployment>();
158        }
159      }
160
161      return service;
162    }
163
164    public static Deployment GetDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName) {
165      string uri = String.Format(Constants.URISpecificDeploymentFormat, subscriptionId, serviceName, deploymentName);
166      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
167      XDocument response = operation.Invoke(uri);
168      Deployment deployment = GetDeploymentFromXml(response.Root);
169      return deployment;
170    }
171
172    public static string AddCertificate(string subscriptionId, string thumbprint, string serviceName, string certificateFilePath, string password) {
173      string uri = String.Format(Constants.URICertificateFormat, subscriptionId, serviceName);
174      XDocument payload = CreateAddCertificatePayload(certificateFilePath, password);
175      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
176      string requestId = operation.Invoke(uri, payload);
177      return requestId;
178    }
179
180    public static string CreateHostedServiceWithLocation(string subscriptionId, string thumbprint, string serviceName, string label, string description, string location) {
181      return CreateHostedService(subscriptionId, thumbprint, serviceName, label, description, location, String.Empty);
182    }
183
184    public static string CreateHostedServiceWithAffinityGroup(string subscriptionId, string thumbprint, string serviceName, string label, string description, string affinityGroup) {
185      return CreateHostedService(subscriptionId, thumbprint, serviceName, label, description, String.Empty, affinityGroup);
186    }
187
188    public static string CreateDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName, string deploymentSlot, string packageUrl, string configuration, string label, int instanceCount) {
189      string uri = String.Format(Constants.URIDeploymentFormat, subscriptionId, serviceName, deploymentSlot);
190      XElement xConfig = XElement.Parse(configuration);
191      SetInstanceCount(xConfig, Constants.HLSlaveRoleName, instanceCount);
192
193      XDocument payload = CreateDeploymentPayload(deploymentName, packageUrl, xConfig, label);
194      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
195      string requestId = operation.Invoke(uri, payload);
196      return requestId;
197    }
198
199    public static string DownloadBlobAsString(Uri uri) {
200      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
201      request.Headers.Add(Constants.HeaderVersionName, Constants.APIVersion20110818);
202      request.Method = Constants.HttpMethodGET;
203      request.ContentType = Constants.ContentTypeAppXml;
204      string result = string.Empty;
205      WebResponse response = request.GetResponse();
206      using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
207        result = reader.ReadToEnd();
208      }
209      return result;
210    }
211
212    public static List<HostedService> DiscoverSlaveService(string subscriptionId, string thumbprint) {
213      List<HostedService> hostedServices = new List<HostedService>();
214      foreach (HostedService hostedService in ListHostedServices(subscriptionId, thumbprint)) {
215        HostedService hs = GetHostedServiceDetailed(subscriptionId, thumbprint, hostedService.ServiceName);
216        foreach (Deployment deployment in hs.Deployments) {
217          if (ContainsRoleNameInConfiguration(XDocument.Parse(deployment.Configuration), Constants.HLSlaveRoleName)) {
218            if (!hostedServices.Contains(hs)) {
219              hostedServices.Add(hs);
220            }
221          }
222        }
223      }
224      return hostedServices;
225    }
226
227    public static string DeleteHostedService(string subscriptionId, string thumbprint, string serviceName) {
228      string uri = String.Format(Constants.URISpecificHostedServiceFormat, subscriptionId, serviceName);
229      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
230      string requestId = operation.Invoke(uri, Constants.HttpMethodDELETE);
231      return requestId;
232    }
233
234    public static string GetOperationStatus(string subscriptionId, string thumbprint, string requestId) {
235      string uri = string.Format(Constants.URIGetOperationStatusFormat, subscriptionId, requestId);
236      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
237      XDocument operationStatus = operation.Invoke(uri);
238      string status = operationStatus.Element(wa + "Operation").Element(wa + "Status").Value;
239      return status;
240    }
241
242    #endregion
243
244    #region Private Methods
245
246    private static int GetInstanceCount(XElement configuration, string roleName) {
247      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
248                                  where s.Attribute("name").Value == roleName
249                                  select s.Element(sh + "Instances")).First();
250      int instanceCount = Convert.ToInt32(instanceElement.Attribute("count").Value);
251      return instanceCount;
252    }
253
254    private static void SetInstanceCount(XElement configuration, string roleName, int value) {
255      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
256                                  where s.Attribute("name").Value == roleName
257                                  select s.Element(sh + "Instances")).First();
258      instanceElement.SetAttributeValue("count", value);
259    }
260
261    private static string CreateHostedService(string subscriptionId, string thumbprint, string serviceName, string label, string description, string location, string affinityGroup) {
262      string uri = string.Format(Constants.URIHostedServiceFormat, subscriptionId);
263      XDocument payload = CreateHostedServicePayload(serviceName, label, description, location, affinityGroup);
264      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
265      string requestId = operation.Invoke(uri, payload);
266      return requestId;
267    }
268
269    private static XDocument CreateHostedServicePayload(string serviceName, string label, string description, string location, string affinityGroup) {
270      string base64LabelName = Utils.ConvertToBase64String(label);
271      XElement xServiceName = new XElement(wa + "ServiceName", serviceName);
272      XElement xLabel = new XElement(wa + "Label", base64LabelName);
273      XElement xDescription = new XElement(wa + "Description", description);
274      XElement createHostedService = new XElement(wa + "CreateHostedService");
275      createHostedService.Add(xServiceName);
276      createHostedService.Add(xLabel);
277      createHostedService.Add(xDescription);
278
279      if (location != String.Empty) {
280        XElement xLocation = new XElement(wa + "Location", location);
281        createHostedService.Add(xLocation);
282      } else {
283        XElement xAffinityGroup = new XElement(wa + "AffinityGroup", affinityGroup);
284        createHostedService.Add(xAffinityGroup);
285      }
286
287      XDocument payload = new XDocument();
288      payload.Add(createHostedService);
289      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
290
291      return payload;
292    }
293
294    private static XDocument CreateAddCertificatePayload(string certificateFilePath, string password) {
295      XElement xData = new XElement(wa + "Data", Convert.ToBase64String(File.ReadAllBytes(certificateFilePath)));
296      XElement xCertificateFormat = new XElement(wa + "CertificateFormat", "pfx");
297      XElement xPassword = new XElement(wa + "Password", password);
298
299      XElement addcert = new XElement(wa + "CertificateFile");
300      addcert.Add(xData);
301      addcert.Add(xCertificateFormat);
302      addcert.Add(xPassword);
303
304      XDocument payload = new XDocument();
305      payload.Add(addcert);
306      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
307
308      return payload;
309    }
310
311    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, string pathToConfigurationFile, string label) {
312      string configurationFile = File.ReadAllText(pathToConfigurationFile);
313      XElement xConfig = XElement.Parse(configurationFile);
314      return CreateDeploymentPayload(deploymentName, packageUrl, xConfig, label);
315    }
316
317    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, XElement configuration, string label) {
318      string base64ConfigurationFile = Utils.ConvertToBase64String(configuration.ToString());
319      string base64Label = Utils.ConvertToBase64String(label);
320
321      XElement xName = new XElement(wa + "Name", deploymentName);
322      XElement xPackageUrl = new XElement(wa + "PackageUrl", packageUrl);
323      XElement xLabel = new XElement(wa + "Label", base64Label);
324      XElement xConfiguration = new XElement(wa + "Configuration", base64ConfigurationFile);
325      XElement xStartDeployment = new XElement(wa + "StartDeployment", "true");
326      XElement xTreatWarningsAsError = new XElement(wa + "TreatWarningsAsError", "false");
327
328      XElement createDeployment = new XElement(wa + "CreateDeployment");
329      createDeployment.Add(xName);
330      createDeployment.Add(xPackageUrl);
331      createDeployment.Add(xLabel);
332      createDeployment.Add(xConfiguration);
333      createDeployment.Add(xStartDeployment);
334      createDeployment.Add(xTreatWarningsAsError);
335
336      XDocument payload = new XDocument();
337      payload.Add(createDeployment);
338      payload.Declaration =
339      new XDeclaration("1.0", "UTF-8", "no");
340      return payload;
341    }
342
343    private static XElement LoadConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot) {
344      string uri = string.Format(Constants.URIDeploymentFormat, subscriptionId, serviceName, deploymentSlot);
345      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
346      XDocument deployment = operation.Invoke(uri);
347      string base64Configuration = deployment.Element(wa + "Deployment").Element(wa + "Configuration").Value;
348      string stringConfiguration = Utils.ConvertFromBase64String(base64Configuration);
349      XElement configuration = XElement.Parse(stringConfiguration);
350      return configuration;
351    }
352
353    private static string SaveConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot, XElement configuration) {
354      string uri = string.Format(Constants.URIDeploymentConfigurationFormat, subscriptionId, serviceName, deploymentSlot);
355      XDocument payload = CreateConfigurationPayload(configuration);
356      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
357      string requestId = operation.Invoke(uri, payload);
358      return requestId;
359    }
360
361    private static XDocument CreateConfigurationPayload(XElement configuration) {
362      string configurationString = configuration.ToString();
363      string base64Configuration = Utils.ConvertToBase64String(configurationString);
364
365      XElement xConfiguration = new XElement(wa + "Configuration", base64Configuration);
366      XElement xChangeConfiguration = new XElement(wa + "ChangeConfiguration", xConfiguration);
367
368      XDocument payload = new XDocument();
369      payload.Add(xChangeConfiguration);
370      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
371
372      return payload;
373    }
374
375    private static XDocument GetConfigurationFromDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName) {
376      Deployment deployment = GetDeployment(subscriptionId, thumbprint, serviceName, deploymentName);
377      XDocument config = XDocument.Parse(deployment.Configuration);
378      return config;
379    }
380
381    private static bool ContainsRoleNameInConfiguration(XDocument configuration, string roleName) {
382      if (configuration.Root.Name != sh + "ServiceConfiguration")
383        throw new ArgumentException("No valid configuration", "configuration");
384
385
386      IEnumerable<XElement> role = (from s in configuration.Root.Elements(sh + "Role")
387                                    where s.Attribute("name").Value == roleName
388                                    select s);
389      return role.Count() > 0;
390    }
391
392    private static Deployment GetDeploymentFromXml(XElement xDeployment) {
393      Deployment deployment = new Deployment();
394      deployment.Name = xDeployment.Descendants(wa + "Name").Single().Value;
395      deployment.DeploymentSlot = xDeployment.Descendants(wa + "DeploymentSlot").Single().Value;
396      deployment.PrivateID = xDeployment.Descendants(wa + "PrivateID").Single().Value;
397      deployment.Status = xDeployment.Descendants(wa + "Status").Single().Value;
398      deployment.Label = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Label").Single().Value);
399      if (xDeployment.Descendants(wa + "Url").Any()) {
400        deployment.Url = xDeployment.Descendants(wa + "Url").Single().Value;
401      }
402      deployment.Configuration = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Configuration").Single().Value);
403
404      XElement xRoleInstanceList = xDeployment.Descendants(wa + "RoleInstanceList").Single();
405      if (xRoleInstanceList.HasElements) {
406        IEnumerable<RoleInstance> instances = (from s in xRoleInstanceList.Elements()
407                                               select new RoleInstance() {
408                                                 RoleName = s.Descendants(wa + "RoleName").Single().Value,
409                                                 InstanceName = s.Descendants(wa + "InstanceName").Single().Value,
410                                                 InstanceStatus = s.Descendants(wa + "InstanceStatus").Single().Value,
411                                                 InstanceSize = s.Descendants(wa + "InstanceSize").Single().Value,
412                                                 InstanceStateDetails = s.Descendants(wa + "InstanceStateDetails").Single().Value
413                                               }).ToList();
414        deployment.RoleInstanceList = new List<RoleInstance>(instances);
415      }
416      if (xDeployment.Descendants(wa + "RoleList").Any()) {
417        XElement xRoleList = xDeployment.Descendants(wa + "RoleList").Single();
418        if (xRoleList.HasElements) {
419
420          IEnumerable<Role> roles = (from s in xRoleList.Elements()
421                                     select new Role() {
422                                       RoleName = s.Descendants(wa + "RoleName").Single().Value,
423                                       OsVersion = s.Descendants(wa + "OsVersion").Single().Value
424                                     }).ToList();
425          deployment.RoleList = new List<Role>(roles);
426        }
427      }
428
429      if (xDeployment.Descendants(wa + "UpgradeDomainCount").Any()) {
430        deployment.UpgradeDomainCount = Convert.ToInt32(xDeployment.Descendants(wa + "UpgradeDomainCount").Single().Value);
431      }
432
433      if (xDeployment.Elements("UpgradeStatus").Any()) {
434        XElement xUpgradeStatus = xDeployment.Descendants(wa + "UpgradeStatus").Single();
435        if (xUpgradeStatus.HasElements) {
436          UpgradeStatus upgradestatus = new UpgradeStatus() {
437            UpgradeType = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value,
438            CurrentUpgradeDomain = Convert.ToInt32(xUpgradeStatus.Descendants(wa + "RoleName").Single().Value),
439            CurrentUpgradeDomainState = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value
440          };
441          deployment.UpgradeStatus = upgradestatus;
442        }
443      }
444      return deployment;
445    }
446
447    #endregion
448  }
449}
Note: See TracBrowser for help on using the repository browser.