Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7429 was 7429, checked in by spimming, 12 years ago

#1680:

  • ChangeInstanceCount method added
  • Deployment: added properties to indicate modification and the new instance count
  • Textbox validation
  • Form resized
File size: 23.6 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 ChangeInstanceCount(string subscriptionId, string thumbprint, string serviceName, string deploymentSlot, string roleName, int instanceCount) {
235      string requestId = string.Empty;
236      XElement configuration = LoadConfiguration(subscriptionId, thumbprint, serviceName, deploymentSlot);
237      if (instanceCount != GetInstanceCount(configuration, roleName)) {
238        SetInstanceCount(configuration, roleName, instanceCount);
239        requestId = SaveConfiguration(subscriptionId, thumbprint, serviceName, deploymentSlot, configuration);
240      }
241      return requestId;
242    }
243
244    public static string GetOperationStatus(string subscriptionId, string thumbprint, string requestId) {
245      string uri = string.Format(Constants.URIGetOperationStatusFormat, subscriptionId, requestId);
246      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
247      XDocument operationStatus = operation.Invoke(uri);
248      string status = operationStatus.Element(wa + "Operation").Element(wa + "Status").Value;
249      return status;
250    }
251
252    #endregion
253
254    #region Private Methods
255
256    private static int GetInstanceCount(XElement configuration, string roleName) {
257      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
258                                  where s.Attribute("name").Value == roleName
259                                  select s.Element(sh + "Instances")).First();
260      int instanceCount = Convert.ToInt32(instanceElement.Attribute("count").Value);
261      return instanceCount;
262    }
263
264    private static void SetInstanceCount(XElement configuration, string roleName, int value) {
265      XElement instanceElement = (from s in configuration.Elements(sh + "Role")
266                                  where s.Attribute("name").Value == roleName
267                                  select s.Element(sh + "Instances")).First();
268      instanceElement.SetAttributeValue("count", value);
269    }
270
271    private static string CreateHostedService(string subscriptionId, string thumbprint, string serviceName, string label, string description, string location, string affinityGroup) {
272      string uri = string.Format(Constants.URIHostedServiceFormat, subscriptionId);
273      XDocument payload = CreateHostedServicePayload(serviceName, label, description, location, affinityGroup);
274      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
275      string requestId = operation.Invoke(uri, payload);
276      return requestId;
277    }
278
279    private static XDocument CreateHostedServicePayload(string serviceName, string label, string description, string location, string affinityGroup) {
280      string base64LabelName = Utils.ConvertToBase64String(label);
281      XElement xServiceName = new XElement(wa + "ServiceName", serviceName);
282      XElement xLabel = new XElement(wa + "Label", base64LabelName);
283      XElement xDescription = new XElement(wa + "Description", description);
284      XElement createHostedService = new XElement(wa + "CreateHostedService");
285      createHostedService.Add(xServiceName);
286      createHostedService.Add(xLabel);
287      createHostedService.Add(xDescription);
288
289      if (location != String.Empty) {
290        XElement xLocation = new XElement(wa + "Location", location);
291        createHostedService.Add(xLocation);
292      } else {
293        XElement xAffinityGroup = new XElement(wa + "AffinityGroup", affinityGroup);
294        createHostedService.Add(xAffinityGroup);
295      }
296
297      XDocument payload = new XDocument();
298      payload.Add(createHostedService);
299      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
300
301      return payload;
302    }
303
304    private static XDocument CreateAddCertificatePayload(string certificateFilePath, string password) {
305      XElement xData = new XElement(wa + "Data", Convert.ToBase64String(File.ReadAllBytes(certificateFilePath)));
306      XElement xCertificateFormat = new XElement(wa + "CertificateFormat", "pfx");
307      XElement xPassword = new XElement(wa + "Password", password);
308
309      XElement addcert = new XElement(wa + "CertificateFile");
310      addcert.Add(xData);
311      addcert.Add(xCertificateFormat);
312      addcert.Add(xPassword);
313
314      XDocument payload = new XDocument();
315      payload.Add(addcert);
316      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
317
318      return payload;
319    }
320
321    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, string pathToConfigurationFile, string label) {
322      string configurationFile = File.ReadAllText(pathToConfigurationFile);
323      XElement xConfig = XElement.Parse(configurationFile);
324      return CreateDeploymentPayload(deploymentName, packageUrl, xConfig, label);
325    }
326
327    private static XDocument CreateDeploymentPayload(string deploymentName, string packageUrl, XElement configuration, string label) {
328      string base64ConfigurationFile = Utils.ConvertToBase64String(configuration.ToString());
329      string base64Label = Utils.ConvertToBase64String(label);
330
331      XElement xName = new XElement(wa + "Name", deploymentName);
332      XElement xPackageUrl = new XElement(wa + "PackageUrl", packageUrl);
333      XElement xLabel = new XElement(wa + "Label", base64Label);
334      XElement xConfiguration = new XElement(wa + "Configuration", base64ConfigurationFile);
335      XElement xStartDeployment = new XElement(wa + "StartDeployment", "true");
336      XElement xTreatWarningsAsError = new XElement(wa + "TreatWarningsAsError", "false");
337
338      XElement createDeployment = new XElement(wa + "CreateDeployment");
339      createDeployment.Add(xName);
340      createDeployment.Add(xPackageUrl);
341      createDeployment.Add(xLabel);
342      createDeployment.Add(xConfiguration);
343      createDeployment.Add(xStartDeployment);
344      createDeployment.Add(xTreatWarningsAsError);
345
346      XDocument payload = new XDocument();
347      payload.Add(createDeployment);
348      payload.Declaration =
349      new XDeclaration("1.0", "UTF-8", "no");
350      return payload;
351    }
352
353    private static XElement LoadConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot) {
354      string uri = string.Format(Constants.URIDeploymentFormat, subscriptionId, serviceName, deploymentSlot);
355      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
356      XDocument deployment = operation.Invoke(uri);
357      string base64Configuration = deployment.Element(wa + "Deployment").Element(wa + "Configuration").Value;
358      string stringConfiguration = Utils.ConvertFromBase64String(base64Configuration);
359      XElement configuration = XElement.Parse(stringConfiguration);
360      return configuration;
361    }
362
363    private static string SaveConfiguration(String subscriptionId, String thumbprint, String serviceName, String deploymentSlot, XElement configuration) {
364      string uri = string.Format(Constants.URIDeploymentConfigurationFormat, subscriptionId, serviceName, deploymentSlot);
365      XDocument payload = CreateConfigurationPayload(configuration);
366      ServiceWebRequest operation = new ServiceWebRequest(thumbprint);
367      string requestId = operation.Invoke(uri, payload);
368      return requestId;
369    }
370
371    private static XDocument CreateConfigurationPayload(XElement configuration) {
372      string configurationString = configuration.ToString();
373      string base64Configuration = Utils.ConvertToBase64String(configurationString);
374
375      XElement xConfiguration = new XElement(wa + "Configuration", base64Configuration);
376      XElement xChangeConfiguration = new XElement(wa + "ChangeConfiguration", xConfiguration);
377
378      XDocument payload = new XDocument();
379      payload.Add(xChangeConfiguration);
380      payload.Declaration = new XDeclaration("1.0", "UTF-8", "no");
381
382      return payload;
383    }
384
385    private static XDocument GetConfigurationFromDeployment(string subscriptionId, string thumbprint, string serviceName, string deploymentName) {
386      Deployment deployment = GetDeployment(subscriptionId, thumbprint, serviceName, deploymentName);
387      XDocument config = XDocument.Parse(deployment.Configuration);
388      return config;
389    }
390
391    private static bool ContainsRoleNameInConfiguration(XDocument configuration, string roleName) {
392      if (configuration.Root.Name != sh + "ServiceConfiguration")
393        throw new ArgumentException("No valid configuration", "configuration");
394
395
396      IEnumerable<XElement> role = (from s in configuration.Root.Elements(sh + "Role")
397                                    where s.Attribute("name").Value == roleName
398                                    select s);
399      return role.Count() > 0;
400    }
401
402    private static Deployment GetDeploymentFromXml(XElement xDeployment) {
403      Deployment deployment = new Deployment();
404      deployment.Name = xDeployment.Descendants(wa + "Name").Single().Value;
405      deployment.DeploymentSlot = xDeployment.Descendants(wa + "DeploymentSlot").Single().Value;
406      deployment.PrivateID = xDeployment.Descendants(wa + "PrivateID").Single().Value;
407      deployment.Status = xDeployment.Descendants(wa + "Status").Single().Value;
408      deployment.Label = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Label").Single().Value);
409      if (xDeployment.Descendants(wa + "Url").Any()) {
410        deployment.Url = xDeployment.Descendants(wa + "Url").Single().Value;
411      }
412      deployment.Configuration = Utils.ConvertFromBase64String(xDeployment.Descendants(wa + "Configuration").Single().Value);
413
414      XElement xRoleInstanceList = xDeployment.Descendants(wa + "RoleInstanceList").Single();
415      if (xRoleInstanceList.HasElements) {
416        IEnumerable<RoleInstance> instances = (from s in xRoleInstanceList.Elements()
417                                               select new RoleInstance() {
418                                                 RoleName = s.Descendants(wa + "RoleName").Single().Value,
419                                                 InstanceName = s.Descendants(wa + "InstanceName").Single().Value,
420                                                 InstanceStatus = s.Descendants(wa + "InstanceStatus").Single().Value,
421                                                 InstanceSize = s.Descendants(wa + "InstanceSize").Single().Value,
422                                                 InstanceStateDetails = s.Descendants(wa + "InstanceStateDetails").Single().Value
423                                               }).ToList();
424        deployment.RoleInstanceList = new List<RoleInstance>(instances);
425      }
426      if (xDeployment.Descendants(wa + "RoleList").Any()) {
427        XElement xRoleList = xDeployment.Descendants(wa + "RoleList").Single();
428        if (xRoleList.HasElements) {
429
430          IEnumerable<Role> roles = (from s in xRoleList.Elements()
431                                     select new Role() {
432                                       RoleName = s.Descendants(wa + "RoleName").Single().Value,
433                                       OsVersion = s.Descendants(wa + "OsVersion").Single().Value
434                                     }).ToList();
435          deployment.RoleList = new List<Role>(roles);
436        }
437      }
438
439      if (xDeployment.Descendants(wa + "UpgradeDomainCount").Any()) {
440        deployment.UpgradeDomainCount = Convert.ToInt32(xDeployment.Descendants(wa + "UpgradeDomainCount").Single().Value);
441      }
442
443      if (xDeployment.Elements("UpgradeStatus").Any()) {
444        XElement xUpgradeStatus = xDeployment.Descendants(wa + "UpgradeStatus").Single();
445        if (xUpgradeStatus.HasElements) {
446          UpgradeStatus upgradestatus = new UpgradeStatus() {
447            UpgradeType = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value,
448            CurrentUpgradeDomain = Convert.ToInt32(xUpgradeStatus.Descendants(wa + "RoleName").Single().Value),
449            CurrentUpgradeDomainState = xUpgradeStatus.Descendants(wa + "RoleName").Single().Value
450          };
451          deployment.UpgradeStatus = upgradestatus;
452        }
453      }
454      return deployment;
455    }
456
457    #endregion
458  }
459}
Note: See TracBrowser for help on using the repository browser.