Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1680:

  • Storage service operations added:
  • list storage services
  • get keys for storage service
File size: 24.9 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 List<StorageService> ListStorageServices(string subscriptionId, string thumbprint) {
113      string uri = string.Format(Constants.URIStorageServiceFormat, subscriptionId);
114      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
115      XDocument response = operation.Invoke(uri);
116      List<StorageService> result = null;
117      if (response.Root.HasElements) {
118        result = (from s in response.Elements()
119                  select new StorageService() {
120                    Url = s.Descendants(wa + "Url").Single().Value,
121                    ServiceName = s.Descendants(wa + "ServiceName").Single().Value
122                  }).ToList();
123      }
124      if (result != null)
125        return result;
126      else
127        return new List<StorageService>();
128    }
129
130    public static HostedService GetHostedService(string subscriptionId, string thumbprint, string serviceName) {
131      string uri = String.Format(Constants.URISpecificHostedServiceFormat, subscriptionId, serviceName);
132      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
133      XDocument response = operation.Invoke(uri);
134      HostedService service = new HostedService();
135      service.ServiceName = response.Descendants(wa + "ServiceName").Single().Value;
136      service.Url = response.Descendants(wa + "Url").Single().Value;
137      return service;
138    }
139
140    public static HostedService GetHostedServiceDetailed(string subscriptionId, string thumbprint, string serviceName) {
141      string uri = String.Format(Constants.URISpecificHostedServiceFormat + "?embed-detail=true", subscriptionId, serviceName);
142      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
143      XDocument response = operation.Invoke(uri);
144      HostedService service = new HostedService();
145      service.ServiceName = response.Descendants(wa + "ServiceName").Single().Value;
146      service.Url = response.Descendants(wa + "Url").First().Value;
147      if (response.Root.Elements(wa + "HostedServiceProperties").Any()) {
148        XElement xHostedServiceProperties = response.Descendants(wa + "HostedServiceProperties").Single();
149        string loc = string.Empty, affgroup = string.Empty;
150        if (xHostedServiceProperties.HasElements) {
151          string desc = xHostedServiceProperties.Descendants(wa + "Description").Single().Value;
152          if (xHostedServiceProperties.Descendants(wa + "Location").Any()) {
153            loc = xHostedServiceProperties.Descendants(wa + "Location").Single().Value;
154          } else {
155            affgroup = xHostedServiceProperties.Descendants(wa + "AffinityGroup").Single().Value;
156          }
157          string lbl = Utils.ConvertFromBase64String(xHostedServiceProperties.Descendants(wa + "Label").Single().Value);
158          HostedServiceProperties props = new HostedServiceProperties() {
159            Description = desc,
160            Location = loc,
161            AffinityGroup = affgroup,
162            Label = lbl
163          };
164          service.HostedServiceProperties = props;
165        }
166      }
167
168      if (response.Root.Elements(wa + "Deployments").Any()) {
169        XElement xDeployments = response.Descendants(wa + "Deployments").Single();
170        if (xDeployments.HasElements) {
171          IEnumerable<Deployment> deps = (from s in xDeployments.Elements()
172                                          select GetDeploymentFromXml(s)).ToList();
173          service.Deployments = new List<Deployment>(deps);
174        } else {
175          service.Deployments = new List<Deployment>();
176        }
177      }
178
179      return service;
180    }
181
182    public static Deployment GetDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName) {
183      string uri = String.Format(Constants.URISpecificDeploymentFormat, subscriptionId, serviceName, deploymentName);
184      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
185      XDocument response = operation.Invoke(uri);
186      Deployment deployment = GetDeploymentFromXml(response.Root);
187      return deployment;
188    }
189
190    public static StorageServiceKeys GetStorageKeys(string subscriptionId, string thumbprint, string serviceName) {
191      string uri = string.Format(Constants.URIStorageServiceKeys, subscriptionId, serviceName);
192      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
193      XDocument response = operation.Invoke(uri);
194      StorageServiceKeys keys = new StorageServiceKeys();
195      keys.Primary = response.Descendants(wa + "Primary").Single().Value;
196      keys.Secondary = response.Descendants(wa + "Secondary").Single().Value;
197      return keys;
198    }
199
200    public static string AddCertificate(string subscriptionId, string thumbprint, string serviceName, string certificateFilePath, string password) {
201      string uri = String.Format(Constants.URICertificateFormat, subscriptionId, serviceName);
202      XDocument payload = CreateAddCertificatePayload(certificateFilePath, password);
203      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
204      string requestId = operation.Invoke(uri, payload);
205      return requestId;
206    }
207
208    public static string CreateHostedServiceWithLocation(string subscriptionId, string thumbprint, string serviceName, string label, string description, string location) {
209      return CreateHostedService(subscriptionId, thumbprint, serviceName, label, description, location, String.Empty);
210    }
211
212    public static string CreateHostedServiceWithAffinityGroup(string subscriptionId, string thumbprint, string serviceName, string label, string description, string affinityGroup) {
213      return CreateHostedService(subscriptionId, thumbprint, serviceName, label, description, String.Empty, affinityGroup);
214    }
215
216    public static string CreateDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName, string deploymentSlot, string packageUrl, string configuration, string label, int instanceCount) {
217      string uri = String.Format(Constants.URIDeploymentFormat, subscriptionId, serviceName, deploymentSlot);
218      XElement xConfig = XElement.Parse(configuration);
219      SetInstanceCount(xConfig, Constants.HLSlaveRoleName, instanceCount);
220
221      XDocument payload = CreateDeploymentPayload(deploymentName, packageUrl, xConfig, label);
222      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
223      string requestId = operation.Invoke(uri, payload);
224      return requestId;
225    }
226
227    public static string DownloadBlobAsString(Uri uri) {
228      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
229      request.Headers.Add(Constants.HeaderVersionName, Constants.APIVersion20110818);
230      request.Method = Constants.HttpMethodGET;
231      request.ContentType = Constants.ContentTypeAppXml;
232      string result = string.Empty;
233      WebResponse response = request.GetResponse();
234      using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
235        result = reader.ReadToEnd();
236      }
237      return result;
238    }
239
240    public static List<HostedService> DiscoverSlaveService(string subscriptionId, string thumbprint) {
241      List<HostedService> hostedServices = new List<HostedService>();
242      foreach (HostedService hostedService in ListHostedServices(subscriptionId, thumbprint)) {
243        HostedService hs = GetHostedServiceDetailed(subscriptionId, thumbprint, hostedService.ServiceName);
244        foreach (Deployment deployment in hs.Deployments) {
245          if (ContainsRoleNameInConfiguration(XDocument.Parse(deployment.Configuration), Constants.HLSlaveRoleName)) {
246            if (!hostedServices.Contains(hs)) {
247              hostedServices.Add(hs);
248            }
249          }
250        }
251      }
252      return hostedServices;
253    }
254
255    public static string DeleteHostedService(string subscriptionId, string thumbprint, string serviceName) {
256      string uri = String.Format(Constants.URISpecificHostedServiceFormat, subscriptionId, serviceName);
257      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
258      string requestId = operation.Invoke(uri, Constants.HttpMethodDELETE);
259      return requestId;
260    }
261
262    public static string ChangeInstanceCount(string subscriptionId, string thumbprint, string serviceName, string deploymentSlot, string roleName, int instanceCount) {
263      string requestId = string.Empty;
264      XElement configuration = LoadConfiguration(subscriptionId, thumbprint, serviceName, deploymentSlot);
265      if (instanceCount != GetInstanceCount(configuration, roleName)) {
266        SetInstanceCount(configuration, roleName, instanceCount);
267        requestId = SaveConfiguration(subscriptionId, thumbprint, serviceName, deploymentSlot, configuration);
268      }
269      return requestId;
270    }
271
272    public static string GetOperationStatus(string subscriptionId, string thumbprint, string requestId) {
273      string uri = string.Format(Constants.URIGetOperationStatusFormat, subscriptionId, requestId);
274      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
275      XDocument operationStatus = operation.Invoke(uri);
276      string status = operationStatus.Element(wa + "Operation").Element(wa + "Status").Value;
277      return status;
278    }
279
280    #endregion
281
282    #region Private Methods
283
284    private static int GetInstanceCount(XElement configuration, string roleName) {
285      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
286                                  where s.Attribute("name").Value == roleName
287                                  select s.Element(sh + "Instances")).First();
288      int instanceCount = Convert.ToInt32(instanceElement.Attribute("count").Value);
289      return instanceCount;
290    }
291
292    private static void SetInstanceCount(XElement configuration, string roleName, int value) {
293      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
294                                  where s.Attribute("name").Value == roleName
295                                  select s.Element(sh + "Instances")).First();
296      instanceElement.SetAttributeValue("count", value);
297    }
298
299    private static string CreateHostedService(string subscriptionId, string thumbprint, string serviceName, string label, string description, string location, string affinityGroup) {
300      string uri = string.Format(Constants.URIHostedServiceFormat, subscriptionId);
301      XDocument payload = CreateHostedServicePayload(serviceName, label, description, location, affinityGroup);
302      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
303      string requestId = operation.Invoke(uri, payload);
304      return requestId;
305    }
306
307    private static XDocument CreateHostedServicePayload(string serviceName, string label, string description, string location, string affinityGroup) {
308      string base64LabelName = Utils.ConvertToBase64String(label);
309      XElement xServiceName = new XElement(wa + "ServiceName", serviceName);
310      XElement xLabel = new XElement(wa + "Label", base64LabelName);
311      XElement xDescription = new XElement(wa + "Description", description);
312      XElement createHostedService = new XElement(wa + "CreateHostedService");
313      createHostedService.Add(xServiceName);
314      createHostedService.Add(xLabel);
315      createHostedService.Add(xDescription);
316
317      if (location != String.Empty) {
318        XElement xLocation = new XElement(wa + "Location", location);
319        createHostedService.Add(xLocation);
320      } else {
321        XElement xAffinityGroup = new XElement(wa + "AffinityGroup", affinityGroup);
322        createHostedService.Add(xAffinityGroup);
323      }
324
325      XDocument payload = new XDocument();
326      payload.Add(createHostedService);
327      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
328
329      return payload;
330    }
331
332    private static XDocument CreateAddCertificatePayload(string certificateFilePath, string password) {
333      XElement xData = new XElement(wa + "Data", Convert.ToBase64String(File.ReadAllBytes(certificateFilePath)));
334      XElement xCertificateFormat = new XElement(wa + "CertificateFormat", "pfx");
335      XElement xPassword = new XElement(wa + "Password", password);
336
337      XElement addcert = new XElement(wa + "CertificateFile");
338      addcert.Add(xData);
339      addcert.Add(xCertificateFormat);
340      addcert.Add(xPassword);
341
342      XDocument payload = new XDocument();
343      payload.Add(addcert);
344      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
345
346      return payload;
347    }
348
349    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, string pathToConfigurationFile, string label) {
350      string configurationFile = File.ReadAllText(pathToConfigurationFile);
351      XElement xConfig = XElement.Parse(configurationFile);
352      return CreateDeploymentPayload(deploymentName, packageUrl, xConfig, label);
353    }
354
355    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, XElement configuration, string label) {
356      string base64ConfigurationFile = Utils.ConvertToBase64String(configuration.ToString());
357      string base64Label = Utils.ConvertToBase64String(label);
358
359      XElement xName = new XElement(wa + "Name", deploymentName);
360      XElement xPackageUrl = new XElement(wa + "PackageUrl", packageUrl);
361      XElement xLabel = new XElement(wa + "Label", base64Label);
362      XElement xConfiguration = new XElement(wa + "Configuration", base64ConfigurationFile);
363      XElement xStartDeployment = new XElement(wa + "StartDeployment", "true");
364      XElement xTreatWarningsAsError = new XElement(wa + "TreatWarningsAsError", "false");
365
366      XElement createDeployment = new XElement(wa + "CreateDeployment");
367      createDeployment.Add(xName);
368      createDeployment.Add(xPackageUrl);
369      createDeployment.Add(xLabel);
370      createDeployment.Add(xConfiguration);
371      createDeployment.Add(xStartDeployment);
372      createDeployment.Add(xTreatWarningsAsError);
373
374      XDocument payload = new XDocument();
375      payload.Add(createDeployment);
376      payload.Declaration =
377      new XDeclaration("1.0", "UTF-8", "no");
378      return payload;
379    }
380
381    private static XElement LoadConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot) {
382      string uri = string.Format(Constants.URIDeploymentFormat, subscriptionId, serviceName, deploymentSlot);
383      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
384      XDocument deployment = operation.Invoke(uri);
385      string base64Configuration = deployment.Element(wa + "Deployment").Element(wa + "Configuration").Value;
386      string stringConfiguration = Utils.ConvertFromBase64String(base64Configuration);
387      XElement configuration = XElement.Parse(stringConfiguration);
388      return configuration;
389    }
390
391    private static string SaveConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot, XElement configuration) {
392      string uri = string.Format(Constants.URIDeploymentConfigurationFormat, subscriptionId, serviceName, deploymentSlot);
393      XDocument payload = CreateConfigurationPayload(configuration);
394      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
395      string requestId = operation.Invoke(uri, payload);
396      return requestId;
397    }
398
399    private static XDocument CreateConfigurationPayload(XElement configuration) {
400      string configurationString = configuration.ToString();
401      string base64Configuration = Utils.ConvertToBase64String(configurationString);
402
403      XElement xConfiguration = new XElement(wa + "Configuration", base64Configuration);
404      XElement xChangeConfiguration = new XElement(wa + "ChangeConfiguration", xConfiguration);
405
406      XDocument payload = new XDocument();
407      payload.Add(xChangeConfiguration);
408      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
409
410      return payload;
411    }
412
413    private static XDocument GetConfigurationFromDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName) {
414      Deployment deployment = GetDeployment(subscriptionId, thumbprint, serviceName, deploymentName);
415      XDocument config = XDocument.Parse(deployment.Configuration);
416      return config;
417    }
418
419    private static bool ContainsRoleNameInConfiguration(XDocument configuration, string roleName) {
420      if (configuration.Root.Name != sh + "ServiceConfiguration")
421        throw new ArgumentException("No valid configuration", "configuration");
422
423
424      IEnumerable<XElement> role = (from s in configuration.Root.Elements(sh + "Role")
425                                    where s.Attribute("name").Value == roleName
426                                    select s);
427      return role.Count() > 0;
428    }
429
430    private static Deployment GetDeploymentFromXml(XElement xDeployment) {
431      Deployment deployment = new Deployment();
432      deployment.Name = xDeployment.Descendants(wa + "Name").Single().Value;
433      deployment.DeploymentSlot = xDeployment.Descendants(wa + "DeploymentSlot").Single().Value;
434      deployment.PrivateID = xDeployment.Descendants(wa + "PrivateID").Single().Value;
435      deployment.Status = xDeployment.Descendants(wa + "Status").Single().Value;
436      deployment.Label = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Label").Single().Value);
437      if (xDeployment.Descendants(wa + "Url").Any()) {
438        deployment.Url = xDeployment.Descendants(wa + "Url").Single().Value;
439      }
440      deployment.Configuration = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Configuration").Single().Value);
441
442      XElement xRoleInstanceList = xDeployment.Descendants(wa + "RoleInstanceList").Single();
443      if (xRoleInstanceList.HasElements) {
444        IEnumerable<RoleInstance> instances = (from s in xRoleInstanceList.Elements()
445                                               select new RoleInstance() {
446                                                 RoleName = s.Descendants(wa + "RoleName").Single().Value,
447                                                 InstanceName = s.Descendants(wa + "InstanceName").Single().Value,
448                                                 InstanceStatus = s.Descendants(wa + "InstanceStatus").Single().Value,
449                                                 InstanceSize = s.Descendants(wa + "InstanceSize").Single().Value,
450                                                 InstanceStateDetails = s.Descendants(wa + "InstanceStateDetails").Single().Value
451                                               }).ToList();
452        deployment.RoleInstanceList = new List<RoleInstance>(instances);
453      }
454      if (xDeployment.Descendants(wa + "RoleList").Any()) {
455        XElement xRoleList = xDeployment.Descendants(wa + "RoleList").Single();
456        if (xRoleList.HasElements) {
457
458          IEnumerable<Role> roles = (from s in xRoleList.Elements()
459                                     select new Role() {
460                                       RoleName = s.Descendants(wa + "RoleName").Single().Value,
461                                       OsVersion = s.Descendants(wa + "OsVersion").Single().Value
462                                     }).ToList();
463          deployment.RoleList = new List<Role>(roles);
464        }
465      }
466
467      if (xDeployment.Descendants(wa + "UpgradeDomainCount").Any()) {
468        deployment.UpgradeDomainCount = Convert.ToInt32(xDeployment.Descendants(wa + "UpgradeDomainCount").Single().Value);
469      }
470
471      if (xDeployment.Elements("UpgradeStatus").Any()) {
472        XElement xUpgradeStatus = xDeployment.Descendants(wa + "UpgradeStatus").Single();
473        if (xUpgradeStatus.HasElements) {
474          UpgradeStatus upgradestatus = new UpgradeStatus() {
475            UpgradeType = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value,
476            CurrentUpgradeDomain = Convert.ToInt32(xUpgradeStatus.Descendants(wa + "RoleName").Single().Value),
477            CurrentUpgradeDomainState = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value
478          };
479          deployment.UpgradeStatus = upgradestatus;
480        }
481      }
482      return deployment;
483    }
484
485    #endregion
486  }
487}
Note: See TracBrowser for help on using the repository browser.