internal Deployment(DeploymentGetResponse response) : this() { if (response.PersistentVMDowntime != null) { PersistentVMDowntime = new PersistentVMDowntimeInfo(response.PersistentVMDowntime); } Name = response.Name; DeploymentSlot = response.DeploymentSlot == Management.Compute.Models.DeploymentSlot.Staging ? "Staging" : "Production"; PrivateID = response.PrivateId; Status = DeploymentStatusFactory.From(response.Status); Label = response.Label; Url = response.Uri; Configuration = response.Configuration; foreach (var roleInstance in response.RoleInstances.Select(ri => new RoleInstance(ri))) { RoleInstanceList.Add(roleInstance); } if (response.UpgradeStatus != null) { UpgradeStatus = new UpgradeStatus(response.UpgradeStatus); } UpgradeDomainCount = response.UpgradeDomainCount; if (response.Roles != null) { foreach (var role in response.Roles.Select(r => new Role(r))) { RoleList.Add(role); } } SdkVersion = response.SdkVersion; Locked = response.Locked; RollbackAllowed = response.RollbackAllowed; VirtualNetworkName = response.VirtualNetworkName; CreatedTime = response.CreatedTime; LastModifiedTime = response.LastModifiedTime; if (response.ExtendedProperties != null) { foreach (var prop in response.ExtendedProperties.Keys) { ExtendedProperties[prop] = response.ExtendedProperties[prop]; } } if (response.DnsSettings != null) { Dns = new DnsSettings(response.DnsSettings); } if (response.VirtualIPAddresses != null) { foreach (var vip in response.VirtualIPAddresses.Select(v => new VirtualIP(v))) { VirtualIPs.Add(vip); } } }
protected override void ExecuteCommand() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); if (string.IsNullOrEmpty(ServiceName)) { var roleContexts = new List <PersistentVMRoleListContext>(); foreach (var service in this.ComputeClient.HostedServices.List()) { DeploymentGetResponse deployment = null; try { deployment = this.ComputeClient.Deployments.GetBySlot( service.ServiceName, DeploymentSlot.Production); } catch (CloudException e) { if (e.Response.StatusCode != HttpStatusCode.NotFound) { throw; } } if (deployment != null) { roleContexts.AddRange( GetVMContextList <PersistentVMRoleListContext>( service.ServiceName, deployment).AsEnumerable()); } } WriteObject(roleContexts, true); } else if (CurrentDeploymentNewSM != null) { var roleContexts = GetVMContextList <PersistentVMRoleContext>( ServiceName, CurrentDeploymentNewSM); WriteObject(roleContexts, true); } else { WriteWarning( string.Format(Resources.NoDeploymentFoundInService, ServiceName)); } }
/// <summary> /// Publishes a service project on Microsoft Azure. /// </summary> /// <param name="name">The cloud service name</param> /// <param name="slot">The deployment slot</param> /// <param name="location">The deployment location</param> /// <param name="affinityGroup">The deployment affinity group</param> /// <param name="storageAccount">The storage account to store the package</param> /// <param name="deploymentName">The deployment name</param> /// <param name="launch">Launch the service after publishing</param> /// <param name="forceUpgrade">force the service upgrade even if this would result in loss of any local data on the vm (for example, changing the vm size)</param> /// <returns>The created deployment</returns> public Deployment PublishCloudService( string name = null, string slot = null, string location = null, string affinityGroup = null, string storageAccount = null, string deploymentName = null, bool launch = false, bool forceUpgrade = false) { CloudServiceProject cloudServiceProject = GetCurrentServiceProject(); // Initialize publish context PublishContext context = CreatePublishContext( name, slot, location, affinityGroup, storageAccount, deploymentName, cloudServiceProject); WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName)); // Set package runtime information WriteVerboseWithTimestamp(Resources.RuntimeDeploymentStart, context.ServiceName); PrepareCloudServicePackagesRuntime(context); // Verify storage account exists SetupStorageService(context); // Update cache worker roles configuration WriteVerboseWithTimestamp( Resources.PublishPreparingDeploymentMessage, context.ServiceName, Subscription.Id); UpdateCacheWorkerRolesCloudConfiguration(context); // Create cloud package AzureTool.Validate(); if (File.Exists(context.PackagePath)) { File.Delete(context.PackagePath); } cloudServiceProject.CreatePackage(DevEnv.Cloud); DeploymentGetResponse deployment = DeployPackage(launch, forceUpgrade, context); return(new Deployment(deployment)); }
public static DeploymentGetResponse AssertLogicalVipWithIPPresent(ComputeManagementClient computeClient, string serviceName, string deploymentName, string virtualIPName, int expectedVipCount) { DeploymentGetResponse deploymentResponse = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); var addedVip1 = deploymentResponse.VirtualIPAddresses.FirstOrDefault(vip => vip.Name == virtualIPName); Assert.NotNull(addedVip1); Assert.True(!string.IsNullOrEmpty(addedVip1.Address)); return(deploymentResponse); }
private DeploymentGetResponse GetCurrentDeployment(out OperationStatusResponse operation) { DeploymentSlot slot = string.IsNullOrEmpty(this.Slot) ? DeploymentSlot.Production : (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); WriteVerboseWithTimestamp(Resources.GetDeploymentBeginOperation); DeploymentGetResponse deploymentGetResponse = null; InvokeInOperationContext(() => deploymentGetResponse = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slot)); operation = GetOperationNewSM(deploymentGetResponse.RequestId); WriteVerboseWithTimestamp(Resources.GetDeploymentCompletedOperation); return(deploymentGetResponse); }
private DeploymentGetResponse GetCurrentDeployment(out OperationStatusResponse operation) { DeploymentSlot slot; if (!Enum.TryParse(this.Slot, out slot)) { throw new ArgumentOutOfRangeException("Slot"); } WriteVerboseWithTimestamp(Resources.GetDeploymentBeginOperation); DeploymentGetResponse deploymentGetResponse = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slot); operation = GetOperationNewSM(deploymentGetResponse.RequestId); WriteVerboseWithTimestamp(Resources.GetDeploymentCompletedOperation); return(deploymentGetResponse); }
public Deployment PublishCloudService( string package, string configuration, string slot = null, string location = null, string affinityGroup = null, string storageAccount = null, string deploymentName = null, bool launch = false, bool forceUpgrade = false) { string workingDirectory = GetCurrentDirectory(); string cloudConfigFullPath = configuration; if (!Path.IsPathRooted(configuration)) { cloudConfigFullPath = Path.Combine(workingDirectory, configuration); } CloudServiceProject cloudServiceProject = new CloudServiceProject(cloudConfigFullPath); // Initialize publish context PublishContext context = CreatePublishContext( cloudServiceProject.ServiceName, slot, location, affinityGroup, storageAccount, deploymentName, cloudServiceProject); context.ConfigPackageSettings(package, workingDirectory); // Verify storage account exists if (!context.PackageIsFromStorageAccount) { SetupStorageService(context); } WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName)); DeploymentGetResponse deployment = DeployPackage(launch, forceUpgrade, context); return(new Deployment(deployment)); }
internal static void LogObject(this TestEasyLog log, DeploymentGetResponse deployment) { if (deployment == null) { return; } log.Info(string.Format("Name:{0}", deployment.Name)); log.Info(string.Format("Label:{0}", Base64EncodingHelper.DecodeFromBase64String(deployment.Label))); log.Info(string.Format("Url:{0}", deployment.Uri)); log.Info(string.Format("Status:{0}", deployment.Status)); log.Info(string.Format("DeploymentSlot:{0}", deployment.DeploymentSlot)); log.Info(string.Format("PrivateID:{0}", deployment.PrivateId)); log.Info(string.Format("UpgradeDomainCount:{0}", deployment.UpgradeDomainCount)); LogObject(log, deployment.Roles); LogObject(log, deployment.RoleInstances); LogObject(log, deployment.UpgradeStatus); }
public ExtensionConfiguration Add(DeploymentGetResponse deployment, DeploymentGetResponse peerDeployment, ExtensionConfigurationInput[] inputs, string slot) { string errorConfigInput = null; if (!Validate(inputs, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } var oldExtConfig = deployment.ExtensionConfiguration; var oldPeerExtConfig = peerDeployment.ExtensionConfiguration; ExtensionConfigurationBuilder configBuilder = this.GetBuilder(); foreach (ExtensionConfigurationInput context in inputs) { if (context != null) { ExtensionConfiguration currentConfig = this.InstallExtension(context, slot, deployment, peerDeployment); foreach (var r in currentConfig.AllRoles) { if (!this.GetBuilder(oldExtConfig).ExistAny(r.Id)) { configBuilder.AddDefault(r.Id); } } foreach (var r in currentConfig.NamedRoles) { foreach (var e in r.Extensions) { if (!this.GetBuilder(oldExtConfig).ExistAny(e.Id)) { configBuilder.Add(r.RoleName, e.Id); } } } } } var extConfig = configBuilder.ToConfiguration(); return(extConfig); }
protected override void ExecuteCommand() { if (this.ShouldProcess(String.Format("Service: {0}, VM: {1}", this.ServiceName, this.Name), Resources.RemoveAzureVMShouldProcessAction)) { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); if (CurrentDeploymentNewSM == null) { return; } DeploymentGetResponse deploymentGetResponse = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, DeploymentSlot.Production); if (deploymentGetResponse.Roles.FirstOrDefault(r => r.RoleName.Equals(Name, StringComparison.InvariantCultureIgnoreCase)) == null) { throw new ArgumentOutOfRangeException(String.Format(Resources.RoleInstanceCanNotBeFoundWithName, Name)); } if (deploymentGetResponse.RoleInstances.Count > 1) { ExecuteClientActionNewSM( null, CommandRuntime.ToString(), () => this.ComputeClient.VirtualMachines.Delete(this.ServiceName, CurrentDeploymentNewSM.Name, Name, DeleteVHD.IsPresent)); } else { if (deploymentGetResponse != null && !string.IsNullOrEmpty(deploymentGetResponse.ReservedIPName)) { WriteVerboseWithTimestamp(string.Format(Resources.ReservedIPNameNoLongerInUseByDeletingLastVMButStillBeingReserved, deploymentGetResponse.ReservedIPName)); } ExecuteClientActionNewSM <AzureOperationResponse>( null, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.DeleteByName(this.ServiceName, CurrentDeploymentNewSM.Name, DeleteVHD.IsPresent)); } } }
protected DeploymentGetResponse GetDeployment(string slot) { var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), slot, true); DeploymentGetResponse d = null; InvokeInOperationContext(() => { try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteExceptionDetails(ex); } } }); return(d); }
private DeploymentGetResponse GetDeploymentBySlot(string slot) { var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), slot, true); DeploymentGetResponse prodDeployment = null; try { InvokeInOperationContext(() => prodDeployment = this.ComputeClient.Deployments.GetBySlot(ServiceName, slotType)); if (prodDeployment != null && prodDeployment.Roles != null) { if (string.Compare(prodDeployment.Roles[0].RoleType, "PersistentVMRole", StringComparison.OrdinalIgnoreCase) == 0) { throw new ArgumentException(String.Format(Resources.CanNotMoveDeploymentsWhileVMsArePresent, slot)); } } } catch (CloudException) { this.WriteDebug(String.Format(Resources.NoDeploymentFoundToMove, slot)); } return(prodDeployment); }
public Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration Add(DeploymentGetResponse deployment, ExtensionConfigurationInput[] inputs, string slot) { string errorConfigInput = null; if (!Validate(inputs, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } var oldExtConfig = deployment.ExtensionConfiguration; ExtensionConfigurationBuilder configBuilder = this.GetBuilder(); foreach (ExtensionConfigurationInput context in inputs) { if (context != null) { Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration currentConfig = this.InstallExtension(context, slot, oldExtConfig); foreach (var r in currentConfig.AllRoles) { if (!this.GetBuilder(oldExtConfig).ExistAny(r.Id)) { configBuilder.AddDefault(r.Id); } } foreach (var r in currentConfig.NamedRoles) { foreach (var e in r.Extensions) { if (!this.GetBuilder(oldExtConfig).ExistAny(e.Id)) { configBuilder.Add(r.RoleName, e.Id); } } } } } var extConfig = configBuilder.ToConfiguration(); return extConfig; }
public ExtensionConfiguration InstallExtension(ExtensionConfigurationInput context, string slot, DeploymentGetResponse deployment, DeploymentGetResponse peerDeployment) { Func <DeploymentGetResponse, ExtensionConfiguration> func = (d) => d == null ? null : d.ExtensionConfiguration; ExtensionConfiguration extConfig = func(deployment); ExtensionConfiguration secondSlotExtConfig = func(peerDeployment); return(InstallExtension(context, slot, extConfig, secondSlotExtConfig)); }
/// <summary> /// Publishes a service project on Windows Azure. /// </summary> /// <param name="name">The cloud service name</param> /// <param name="slot">The deployment slot</param> /// <param name="location">The deployment location</param> /// <param name="affinityGroup">The deployment affinity group</param> /// <param name="storageAccount">The storage account to store the package</param> /// <param name="deploymentName">The deployment name</param> /// <param name="launch">Launch the service after publishing</param> /// <param name="forceUpgrade">force the service upgrade even if this would result in loss of any local data on the vm (for example, changing the vm size)</param> /// <returns>The created deployment</returns> public Deployment PublishCloudService( string name = null, string slot = null, string location = null, string affinityGroup = null, string storageAccount = null, string deploymentName = null, bool launch = false, bool forceUpgrade = false) { // Initialize publish context PublishContext context = CreatePublishContext( name, slot, location, affinityGroup, storageAccount, deploymentName); WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName)); // Set package runtime information WriteVerboseWithTimestamp(Resources.RuntimeDeploymentStart, context.ServiceName); PrepareCloudServicePackagesRuntime(context); // Verify storage account exists WriteVerboseWithTimestamp( Resources.PublishVerifyingStorageMessage, context.ServiceSettings.StorageServiceName); CreateStorageServiceIfNotExist( context.ServiceSettings.StorageServiceName, context.ServiceName, context.ServiceSettings.Location, context.ServiceSettings.AffinityGroup); // Update cache worker roles configuration WriteVerboseWithTimestamp( Resources.PublishPreparingDeploymentMessage, context.ServiceName, Subscription.SubscriptionId); UpdateCacheWorkerRolesCloudConfiguration(context); // Create cloud package AzureTool.Validate(); if (File.Exists(context.PackagePath)) { File.Delete(context.PackagePath); } CloudServiceProject cloudServiceProject = new CloudServiceProject(context.RootPath, null); string unused; cloudServiceProject.CreatePackage(DevEnv.Cloud, out unused, out unused); // Publish cloud service WriteVerboseWithTimestamp(Resources.PublishConnectingMessage); CreateCloudServiceIfNotExist( context.ServiceName, affinityGroup: context.ServiceSettings.AffinityGroup, location: context.ServiceSettings.Location); if (DeploymentExists(context.ServiceName, context.ServiceSettings.Slot)) { // Upgrade the deployment UpgradeDeployment(context, forceUpgrade); } else { // Create new deployment CreateDeployment(context); } // Get the deployment id and show it. WriteVerboseWithTimestamp(Resources.PublishCreatedDeploymentMessage, GetDeploymentId(context)); // Verify the deployment succeeded by checking that each of the roles are running VerifyDeployment(context); // Get object of the published deployment DeploymentGetResponse deployment = ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot)); if (launch) { General.LaunchWebPage(deployment.Uri.ToString()); } return(new Deployment(deployment)); }
public void TestAssociateDisassociateOnMultivipIaaSDeployment() { using (var undoContext = AZT.UndoContext.Current) { undoContext.Start(); using (NetworkTestBase _testFixture = new NetworkTestBase()) { bool hostedServiceCreated = false; bool storageAccountCreated = false; string storageAccountName = HttpMockServer.GetAssetName("tststr1234", "tststr").ToLower(); string serviceName = AZT.TestUtilities.GenerateName("testser"); string deploymentName = AZT.TestUtilities.GenerateName("dep"); ComputeManagementClient computeClient = _testFixture.GetComputeManagementClient(); ManagementClient managementClient = _testFixture.ManagementClient; StorageManagementClient storageClient = _testFixture.GetStorageManagementClient(); List <string> createdRips = new List <string>(); try { string location = Utilities.GetTestLocation(managementClient); Assert.True(!string.IsNullOrEmpty(location)); // Create hosted service Utilities.CreateHostedService(location, computeClient, serviceName, out hostedServiceCreated); Assert.True(hostedServiceCreated); // Create storage account storageAccountName = HttpMockServer.GetAssetName("tststr1234", "tststr").ToLower(); Utilities.CreateStorageAccount(location, storageClient, storageAccountName, out storageAccountCreated); Assert.True(storageAccountCreated); List <string> vipNames = new List <string>() { AZT.TestUtilities.GenerateName("VipA"), AZT.TestUtilities.GenerateName("VipB"), AZT.TestUtilities.GenerateName("VipC"), AZT.TestUtilities.GenerateName("VipD"), AZT.TestUtilities.GenerateName("VipE") }; List <string> reservedIPNames = new List <string>() { AZT.TestUtilities.GenerateName("RipA"), AZT.TestUtilities.GenerateName("RipB"), AZT.TestUtilities.GenerateName("RipC"), AZT.TestUtilities.GenerateName("RipD"), AZT.TestUtilities.GenerateName("RipE") }; CreateMultivipDeploymentAndAssertSuccess(_testFixture.NetworkClient, computeClient, vipNames, serviceName, deploymentName, storageAccountName, location); // Associate 5 reserved IPs for (int i = 0; i < 5; i++) { string reserveIpName = reservedIPNames[i]; string vipName = vipNames[i]; NetworkReservedIPCreateParameters reservedIpCreatePars = new NetworkReservedIPCreateParameters { Name = reserveIpName, Location = location, Label = "SampleReserveIPLabel" }; OperationStatusResponse reserveIpCreate = _testFixture.NetworkClient.ReservedIPs.Create(reservedIpCreatePars); Assert.True(reserveIpCreate.StatusCode == HttpStatusCode.OK); createdRips.Add(reserveIpName); NetworkReservedIPGetResponse reserveIpCreationResponse = _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName); Assert.True(reserveIpCreationResponse.StatusCode == HttpStatusCode.OK); NetworkReservedIPMobilityParameters pars = new NetworkReservedIPMobilityParameters { ServiceName = serviceName, DeploymentName = deploymentName, VirtualIPName = vipName }; OperationStatusResponse responseAssociateRip = _testFixture.NetworkClient.ReservedIPs.Associate(reserveIpName, pars); Assert.True(responseAssociateRip.StatusCode == HttpStatusCode.OK); DeploymentGetResponse deploymentResponse = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); NetworkReservedIPGetResponse receivedReservedIpFromRdfe = _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName); Assert.True(receivedReservedIpFromRdfe.StatusCode == HttpStatusCode.OK); Assert.True(serviceName == receivedReservedIpFromRdfe.ServiceName); Assert.True(receivedReservedIpFromRdfe.InUse == true); Assert.True(deploymentName == receivedReservedIpFromRdfe.DeploymentName); Assert.True(reserveIpName == receivedReservedIpFromRdfe.Name); Assert.True(vipName == receivedReservedIpFromRdfe.VirtualIPName); var vipAssociated = deploymentResponse.VirtualIPAddresses.FirstOrDefault(vip => vip.Name == vipName); Assert.NotNull(vipAssociated); Assert.True(vipAssociated.ReservedIPName == reserveIpName); } // Disassociate the associated IPs for (int i = 0; i < 5; i++) { string reserveIpName = reservedIPNames[i]; string vipName = vipNames[i]; NetworkReservedIPMobilityParameters pars = new NetworkReservedIPMobilityParameters { ServiceName = serviceName, DeploymentName = deploymentName, VirtualIPName = vipName }; OperationStatusResponse responseDisassociateRip = _testFixture.NetworkClient.ReservedIPs.Disassociate(reserveIpName, pars); Assert.True(responseDisassociateRip.StatusCode == HttpStatusCode.OK); DeploymentGetResponse deploymentResponse = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); NetworkReservedIPGetResponse receivedReservedIpFromRdfe = _testFixture.NetworkClient.ReservedIPs.Get(reserveIpName); Assert.True(receivedReservedIpFromRdfe.StatusCode == HttpStatusCode.OK); Assert.True(string.IsNullOrEmpty(receivedReservedIpFromRdfe.ServiceName)); Assert.True(receivedReservedIpFromRdfe.InUse == false); Assert.True(string.IsNullOrEmpty(receivedReservedIpFromRdfe.DeploymentName)); Assert.True(reserveIpName == receivedReservedIpFromRdfe.Name); Assert.True(string.IsNullOrEmpty(receivedReservedIpFromRdfe.VirtualIPName)); var vipAssociated = deploymentResponse.VirtualIPAddresses.FirstOrDefault(vip => vip.Name == vipName); Assert.NotNull(vipAssociated); Assert.True(string.IsNullOrEmpty(vipAssociated.ReservedIPName)); } } finally { if (hostedServiceCreated) { computeClient.HostedServices.DeleteAll(serviceName); } if (createdRips.Any()) { foreach (var rip in createdRips) { // Clean up created Reserved IPs _testFixture.NetworkClient.ReservedIPs.Delete(rip); } } } } } }
public DeploymentInfoContext(DeploymentGetResponse deployment) { this.Slot = deployment.DeploymentSlot.ToString(); this.Name = deployment.Name; this.DeploymentName = deployment.Name; this.Url = deployment.Uri; this.Status = deployment.Status.ToString(); this.DeploymentId = deployment.PrivateId; this.VNetName = deployment.VirtualNetworkName; this.SdkVersion = deployment.SdkVersion; this.CreatedTime = deployment.CreatedTime; this.LastModifiedTime = deployment.LastModifiedTime; this.Locked = deployment.Locked; // IP Related this.ReservedIPName = deployment.ReservedIPName; this.VirtualIPs = deployment.VirtualIPAddresses == null ? null : new PVM.VirtualIPList( deployment.VirtualIPAddresses.Select(a => new PVM.VirtualIP { Address = a.Address, IsDnsProgrammed = a.IsDnsProgrammed, Name = a.Name, ReservedIPName = a.ReservedIPName })); // DNS if (deployment.DnsSettings != null) { this.DnsSettings = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.DnsSettings { DnsServers = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.DnsServerList() }; foreach (var dns in deployment.DnsSettings.DnsServers) { var newDns = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.DnsServer { Name = dns.Name, Address = dns.Address.ToString() }; this.DnsSettings.DnsServers.Add(newDns); } } this.RollbackAllowed = deployment.RollbackAllowed; if (deployment.UpgradeStatus != null) { this.CurrentUpgradeDomain = deployment.UpgradeStatus.CurrentUpgradeDomain; this.CurrentUpgradeDomainState = deployment.UpgradeStatus.CurrentUpgradeDomainState.ToString(); this.UpgradeType = deployment.UpgradeStatus.UpgradeType.ToString(); } this.Configuration = string.IsNullOrEmpty(deployment.Configuration) ? string.Empty : deployment.Configuration; this.Label = string.IsNullOrEmpty(deployment.Label) ? string.Empty : deployment.Label; this.RoleInstanceList = deployment.RoleInstances; if (!string.IsNullOrEmpty(deployment.Configuration)) { string xmlString = this.Configuration; XDocument doc; using (var stringReader = new StringReader(xmlString)) { XmlReader reader = XmlReader.Create(stringReader); doc = XDocument.Load(reader); } this.OSVersion = doc.Root.Attribute("osVersion") != null? doc.Root.Attribute("osVersion").Value: string.Empty; this.RolesConfiguration = new Dictionary <string, RoleConfiguration>(); var roles = doc.Root.Descendants(this.ns + "Role").Where(t => t.Parent == doc.Root); foreach (var role in roles) { this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role)); } } // ILB if (deployment.LoadBalancers != null) { this.LoadBalancers = new PVM.LoadBalancerList( from b in deployment.LoadBalancers select new PVM.LoadBalancer { Name = b.Name, FrontEndIpConfiguration = b.FrontendIPConfiguration == null ? null : new PVM.IpConfiguration { StaticVirtualNetworkIPAddress = b.FrontendIPConfiguration.StaticVirtualNetworkIPAddress, SubnetName = b.FrontendIPConfiguration.SubnetName, Type = string.Equals( b.FrontendIPConfiguration.Type, PVM.LoadBalancerType.Private.ToString(), StringComparison.OrdinalIgnoreCase) ? PVM.LoadBalancerType.Private : PVM.LoadBalancerType.Unknown } }); this.InternalLoadBalancerName = this.LoadBalancers == null || !this.LoadBalancers.Any() ? null : this.LoadBalancers.First().Name; } // ExtensionConfiguration if (deployment.ExtensionConfiguration != null) { this.ExtensionConfiguration = new PVM.ExtensionConfiguration(); if (deployment.ExtensionConfiguration.AllRoles != null) { this.ExtensionConfiguration.AllRoles = new PVM.AllRoles( from all in deployment.ExtensionConfiguration.AllRoles select new PVM.Extension(all.Id, 0, all.State)); } if (deployment.ExtensionConfiguration.NamedRoles != null) { this.ExtensionConfiguration.NamedRoles = new PVM.NamedRoles(); foreach (var role in deployment.ExtensionConfiguration.NamedRoles) { var extList = new PVM.ExtensionList( from ext in role.Extensions select new PVM.Extension(ext.Id, 0, ext.State)); this.ExtensionConfiguration.NamedRoles.Add(new PVM.RoleExtensions { RoleName = role.RoleName, Extensions = extList }); } } } }
public async Task <IHttpActionResult> Get() { // Will throw if more than one record exists with 'Selected = 1' (reason: by design) var mancert = await _sql.QueryAsync <ManagementCertificate>("SELECT * FROM ManagementCertificates WHERE Selected = 1").ContinueWith(a => a.Result.SingleOrDefault()); if (mancert == null) { // TODO: Inform user no certs exist return(Ok(new { Nodes = new List <Node>(), NodeDeployments = new List <NodeDeployment>(), NodeInstances = new List <NodeInstance>() })); } var certbytes = Convert.FromBase64String(mancert.Certificate); var cert = new X509Certificate2(certbytes); var creds = new CertificateCloudCredentials(mancert.SubscriptionId, cert); var cmc = new ComputeManagementClient(creds); // ---- var nodes = new List <Node>(); var nodeDeployments = new List <NodeDeployment>(); var nodeInstances = new List <NodeInstance>(); var slots = Enum.GetValues(typeof(DeploymentSlot)).Cast <DeploymentSlot>().ToArray(); //.OrderByDescending(x => x).ToList(); var hostedServices = await cmc.HostedServices.ListAsync(); foreach (var hostedService in hostedServices.Where(a => a.ServiceName.ToLower().Contains("blazedsp-node"))) { nodes.Add(new Node { Id = hostedService.ServiceName, Label = hostedService.Properties.Label, Location = hostedService.Properties.Location, Status = hostedService.Properties.Status, NodeDeployments = new List <string>() }); DeploymentGetResponse deployment = null; foreach (var slot in slots) { try { deployment = await cmc.Deployments.GetBySlotAsync(hostedService.ServiceName, slot); } catch (CloudException ce) { if (!ce.Message.Contains("No deployments were found")) { throw new NotImplementedException(ce.Message, ce); } } catch (Exception ex) { throw new NotImplementedException(ex.Message, ex); } if (deployment == null) { var guid = Guid.NewGuid().ToString(); nodeDeployments.Add(new NodeDeployment { Id = guid, DeploymentSlot = slot }); nodes.Single(a => a.Id == hostedService.ServiceName).NodeDeployments.Add(guid); continue; } var guids = new List <string>(); foreach (var instance in deployment.RoleInstances) { var guid = Guid.NewGuid().ToString(); guids.Add(guid); nodeInstances.Add(new NodeInstance { Id = guid, Name = instance.InstanceName, Size = instance.InstanceSize, StateDetails = instance.InstanceStateDetails, Status = instance.InstanceStatus, PowerState = instance.PowerState, RoleName = instance.RoleName }); } nodeDeployments.Add(new NodeDeployment { Id = deployment.PrivateId, Name = deployment.Name, Label = deployment.Label, DeploymentSlot = deployment.DeploymentSlot, SdkVersion = deployment.SdkVersion, Status = deployment.Status, CreatedTime = deployment.CreatedTime, LastModifiedTime = deployment.LastModifiedTime, NodeInstances = guids }); nodes.Single(a => a.Id == hostedService.ServiceName).NodeDeployments.Add(deployment.PrivateId); } } return(Ok(new { nodes, nodeDeployments, nodeInstances })); }
private T CreateVMContext <T>(string serviceName, Role vmRole, RoleInstance roleInstance, DeploymentGetResponse deployment) where T : PersistentVMRoleContext, new() { var vmContext = new T { ServiceName = serviceName, DeploymentName = deployment.Name, DNSName = deployment.Uri.AbsoluteUri, Name = vmRole.RoleName, AvailabilitySetName = vmRole.AvailabilitySetName, Label = vmRole.Label, InstanceSize = vmRole.RoleSize, InstanceStatus = roleInstance == null ? string.Empty : roleInstance.InstanceStatus, IpAddress = roleInstance == null ? string.Empty : roleInstance.IPAddress, PublicIPAddress = roleInstance == null ? null : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? null : roleInstance.PublicIPs.First().Address, PublicIPName = roleInstance == null ? null : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? null : !string.IsNullOrEmpty(roleInstance.PublicIPs.First().Name) ? roleInstance.PublicIPs.First().Name : PersistentVMHelper.GetPublicIPName(vmRole), InstanceStateDetails = roleInstance == null ? string.Empty : roleInstance.InstanceStateDetails, PowerState = roleInstance == null ? string.Empty : roleInstance.PowerState.ToString(), InstanceErrorCode = roleInstance == null ? string.Empty : roleInstance.InstanceErrorCode, InstanceName = roleInstance == null ? string.Empty : roleInstance.InstanceName, InstanceFaultDomain = roleInstance == null ? string.Empty : roleInstance.InstanceFaultDomain.HasValue ? roleInstance.InstanceFaultDomain.Value.ToString(CultureInfo.InvariantCulture) : null, InstanceUpgradeDomain = roleInstance == null ? string.Empty : roleInstance.InstanceUpgradeDomain.HasValue ? roleInstance.InstanceUpgradeDomain.Value.ToString(CultureInfo.InvariantCulture) : null, Status = roleInstance == null ? string.Empty : roleInstance.InstanceStatus, GuestAgentStatus = roleInstance == null ? null : Mapper.Map <PVM.GuestAgentStatus>(roleInstance.GuestAgentStatus), ResourceExtensionStatusList = roleInstance == null ? null : Mapper.Map <List <PVM.ResourceExtensionStatus> >(roleInstance.ResourceExtensionStatusList), OperationId = deployment.RequestId, OperationStatus = deployment.StatusCode.ToString(), OperationDescription = CommandRuntime.ToString(), VM = new PersistentVM { AvailabilitySetName = vmRole.AvailabilitySetName, Label = vmRole.Label, RoleName = vmRole.RoleName, RoleSize = vmRole.RoleSize, RoleType = vmRole.RoleType, DefaultWinRmCertificateThumbprint = vmRole.DefaultWinRmCertificateThumbprint, ProvisionGuestAgent = vmRole.ProvisionGuestAgent, ResourceExtensionReferences = Mapper.Map <PVM.ResourceExtensionReferenceList>(vmRole.ResourceExtensionReferences), DataVirtualHardDisks = Mapper.Map <Collection <PVM.DataVirtualHardDisk> >(vmRole.DataVirtualHardDisks), OSVirtualHardDisk = Mapper.Map <PVM.OSVirtualHardDisk>(vmRole.OSVirtualHardDisk), ConfigurationSets = PersistentVMHelper.MapConfigurationSets(vmRole.ConfigurationSets) } }; return(vmContext); }
private Task<DeploymentGetResponse> CreateDeploymentGetResponse(string serviceName, DeploymentSlot slot) { var service = Services.FirstOrDefault(s => s.Name == serviceName); var failedResponse = Tasks.FromException<DeploymentGetResponse>(ClientMocks.Make404Exception()); if (service == null) { return failedResponse; } if (slot == DeploymentSlot.Production && service.ProductionDeployment == null || slot == DeploymentSlot.Staging && service.StagingDeployment == null) { return failedResponse; } var response = new DeploymentGetResponse { Name = serviceName, Configuration = "config", DeploymentSlot = slot, Status = DeploymentStatus.Starting, PersistentVMDowntime = new PersistentVMDowntime { EndTime = DateTime.Now, StartTime = DateTime.Now, Status = "", }, LastModifiedTime = DateTime.Now }; return Tasks.FromResult(response); }
public DeploymentGetResponse CreateMultivipDeploymentAndAssertSuccess(NetworkManagementClient networkClient, ComputeManagementClient computeClient, List <string> vipNames, string serviceName, string deploymentName, string storageAccountName, string location) { Utilities.CreateAzureVirtualMachine(computeClient, serviceName, deploymentName, storageAccountName, "blob.core.windows.net"); DeploymentGetResponse depRetrieved = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); List <ConfigurationSet> endpointCfgSets = new List <ConfigurationSet> { new ConfigurationSet { ConfigurationSetType = "NetworkConfiguration", InputEndpoints = new List <InputEndpoint> { new InputEndpoint() { LocalPort = 3387, Name = "RDP2", Port = 52777, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false }, } } }; // Update with single endpoint var updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(), storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false); computeClient.VirtualMachines.Update( serviceName, deploymentName, depRetrieved.Roles.First().RoleName, updateParams); int i = 1; foreach (var vip in vipNames) { i++; OperationStatusResponse virtualIPCreate = networkClient.VirtualIPs.Add(serviceName: serviceName, deploymentName: deploymentName, virtualIPName: vip); Assert.True(virtualIPCreate.StatusCode == HttpStatusCode.OK); depRetrieved = Utilities.AssertLogicalVipWithoutIPPresentOrAbsent(computeClient, serviceName: serviceName, deploymentName: deploymentName, virtualIPName: vip, expectedVipCount: i, present: true); endpointCfgSets.First().InputEndpoints.Add( new InputEndpoint() { LocalPort = 3387 + i, Name = "RDPS" + i, Port = 52777 + i, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false, VirtualIPName = vip }); } updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(), storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false); computeClient.VirtualMachines.Update( serviceName, deploymentName, depRetrieved.Roles.First().RoleName, updateParams); depRetrieved = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); Assert.NotNull(depRetrieved); Assert.NotNull(depRetrieved.VirtualIPAddresses); Assert.True(depRetrieved.VirtualIPAddresses.Count == vipNames.Count + 1); foreach (var virtualIpAddress in depRetrieved.VirtualIPAddresses) { Assert.NotNull(virtualIpAddress.Address); } return(depRetrieved); }
public void TestAdditionalVipLifeCycle() { using (var undoContext = AZT.UndoContext.Current) { undoContext.Start(); using (NetworkTestBase _testFixture = new NetworkTestBase()) { bool hostedServiceCreated = false; bool storageAccountCreated = false; string storageAccountName = HttpMockServer.GetAssetName("tststr1234", "tststr").ToLower(); string serviceName = AZT.TestUtilities.GenerateName("testser"); string virtualIPName1 = AZT.TestUtilities.GenerateName("vip1"); string deploymentName = AZT.TestUtilities.GenerateName("dep"); ComputeManagementClient computeClient = _testFixture.GetComputeManagementClient(); ManagementClient managementClient = _testFixture.ManagementClient; StorageManagementClient storageClient = _testFixture.GetStorageManagementClient(); try { string location = Utilities.GetTestLocation(managementClient); Assert.True(!string.IsNullOrEmpty(location)); // Create hosted service Utilities.CreateHostedService(location, computeClient, serviceName, out hostedServiceCreated); Assert.True(hostedServiceCreated); // Create storage account storageAccountName = HttpMockServer.GetAssetName("tststr1234", "tststr").ToLower(); Utilities.CreateStorageAccount(location, storageClient, storageAccountName, out storageAccountCreated); Assert.True(storageAccountCreated); // Create a new VM Utilities.CreateAzureVirtualMachine(computeClient, serviceName, deploymentName, storageAccountName, "blob.core.windows.net"); DeploymentGetResponse depRetrieved = computeClient.Deployments.GetByName(serviceName: serviceName, deploymentName: deploymentName); IEnumerable <ConfigurationSet> endpointCfgSets = new List <ConfigurationSet> { new ConfigurationSet { ConfigurationSetType = "NetworkConfiguration", InputEndpoints = new List <InputEndpoint> { new InputEndpoint() { LocalPort = 3387, Name = "RDP2", Port = 52777, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false }, } } }; // Update with single endpoint var updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(), storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false); computeClient.VirtualMachines.Update( serviceName, deploymentName, depRetrieved.Roles.First().RoleName, updateParams); // Add and assert vip status OperationStatusResponse virtualIPCreate1 = _testFixture.NetworkClient.VirtualIPs.Add(serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1); Assert.True(virtualIPCreate1.StatusCode == HttpStatusCode.OK); depRetrieved = Utilities.AssertLogicalVipWithoutIPPresentOrAbsent(computeClient, serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1, expectedVipCount: 2, present: true); endpointCfgSets = new List <ConfigurationSet> { new ConfigurationSet { ConfigurationSetType = "NetworkConfiguration", InputEndpoints = new List <InputEndpoint> { new InputEndpoint() { LocalPort = 3387, Name = "RDP2", Port = 52777, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false, }, new InputEndpoint() { LocalPort = 3379, Name = "RDP", Port = 52728, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false, VirtualIPName = virtualIPName1, } } } }; updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(), storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false); computeClient.VirtualMachines.Update( serviceName, deploymentName, depRetrieved.Roles.First().RoleName, updateParams); var depRetrievedAfterUpdate = Utilities.AssertLogicalVipWithIPPresent(computeClient, serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1, expectedVipCount: 2); endpointCfgSets = new List <ConfigurationSet> { new ConfigurationSet { ConfigurationSetType = "NetworkConfiguration", InputEndpoints = new List <InputEndpoint> { new InputEndpoint() { LocalPort = 3387, Name = "RDP2", Port = 52777, Protocol = InputEndpointTransportProtocol.Tcp, EnableDirectServerReturn = false, }, } } }; updateParams = Utilities.GetVMUpdateParameters(depRetrieved.Roles.First(), storageAccountName, endpointCfgSets, preserveOriginalConfigSets: false); computeClient.VirtualMachines.Update( serviceName, deploymentName, depRetrieved.Roles.First().RoleName, updateParams); depRetrieved = Utilities.AssertLogicalVipWithoutIPPresentOrAbsent(computeClient, serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1, expectedVipCount: 2, present: true); // Remove and assert vip status OperationStatusResponse virtualIPRemove1 = _testFixture.NetworkClient.VirtualIPs.Remove(serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1); Assert.True(virtualIPRemove1.StatusCode == HttpStatusCode.OK); Utilities.AssertLogicalVipWithoutIPPresentOrAbsent(computeClient, serviceName: serviceName, deploymentName: deploymentName, virtualIPName: virtualIPName1, expectedVipCount: 3, present: false); } finally { if (hostedServiceCreated) { computeClient.HostedServices.DeleteAll(serviceName); } } } } }
public DeploymentInfoContext(DeploymentGetResponse deployment) { this.Slot = deployment.DeploymentSlot.ToString(); this.Name = deployment.Name; this.DeploymentName = deployment.Name; this.Url = deployment.Uri; this.Status = deployment.Status.ToString(); this.DeploymentId = deployment.PrivateId; this.VNetName = deployment.VirtualNetworkName; this.SdkVersion = deployment.SdkVersion; this.CreatedTime = deployment.CreatedTime; this.LastModifiedTime = deployment.LastModifiedTime; this.Locked = deployment.Locked; // IP Related this.ReservedIPName = deployment.ReservedIPName; this.VirtualIPs = deployment.VirtualIPAddresses == null ? null : new PVM.VirtualIPList( deployment.VirtualIPAddresses.Select(a => new PVM.VirtualIP { Address = a.Address, IsDnsProgrammed = a.IsDnsProgrammed, Name = a.Name })); // DNS if (deployment.DnsSettings != null) { this.DnsSettings = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsSettings { DnsServers = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServerList() }; foreach (var dns in deployment.DnsSettings.DnsServers) { var newDns = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServer { Name = dns.Name, Address = dns.Address.ToString() }; this.DnsSettings.DnsServers.Add(newDns); } } this.RollbackAllowed = deployment.RollbackAllowed; if (deployment.UpgradeStatus != null) { this.CurrentUpgradeDomain = deployment.UpgradeStatus.CurrentUpgradeDomain; this.CurrentUpgradeDomainState = deployment.UpgradeStatus.CurrentUpgradeDomainState.ToString(); this.UpgradeType = deployment.UpgradeStatus.UpgradeType.ToString(); } this.Configuration = string.IsNullOrEmpty(deployment.Configuration) ? string.Empty : deployment.Configuration; this.Label = string.IsNullOrEmpty(deployment.Label) ? string.Empty : deployment.Label; this.RoleInstanceList = deployment.RoleInstances; if (!string.IsNullOrEmpty(deployment.Configuration)) { string xmlString = this.Configuration; XDocument doc; using (var stringReader = new StringReader(xmlString)) { XmlReader reader = XmlReader.Create(stringReader); doc = XDocument.Load(reader); } this.OSVersion = doc.Root.Attribute("osVersion") != null ? doc.Root.Attribute("osVersion").Value : string.Empty; this.RolesConfiguration = new Dictionary<string, RoleConfiguration>(); var roles = doc.Root.Descendants(this.ns + "Role"); foreach (var role in roles) { this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role)); } } // ILB if (deployment.LoadBalancers != null) { this.LoadBalancers = new PVM.LoadBalancerList( from b in deployment.LoadBalancers select new PVM.LoadBalancer { Name = b.Name, FrontEndIpConfiguration = b.FrontendIPConfiguration == null ? null : new PVM.IpConfiguration { StaticVirtualNetworkIPAddress = b.FrontendIPConfiguration.StaticVirtualNetworkIPAddress, SubnetName = b.FrontendIPConfiguration.SubnetName, Type = string.Equals( b.FrontendIPConfiguration.Type, PVM.LoadBalancerType.Private.ToString(), StringComparison.OrdinalIgnoreCase) ? PVM.LoadBalancerType.Private : PVM.LoadBalancerType.Unknown } }); this.InternalLoadBalancerName = this.LoadBalancers == null || !this.LoadBalancers.Any() ? null : this.LoadBalancers.First().Name; } }
public ExtensionConfiguration InstallExtension(ExtensionConfigurationInput context, string slot, DeploymentGetResponse deployment, DeploymentGetResponse peerDeployment) { Func <DeploymentGetResponse, ExtensionConfiguration> func = (d) => d == null ? null : d.ExtensionConfiguration; ExtensionConfiguration extConfig = func(deployment); ExtensionConfiguration secondSlotExtConfig = func(peerDeployment); ExtensionConfigurationBuilder builder = GetBuilder(extConfig); ExtensionConfigurationBuilder secondSlotConfigBuilder = null; if (secondSlotExtConfig != null) { secondSlotConfigBuilder = GetBuilder(secondSlotExtConfig); } foreach (ExtensionRole r in context.Roles) { var extensionIds = (from index in Enumerable.Range(0, ExtensionIdLiveCycleCount) select r.GetExtensionId(context.Type, slot, index)).ToList(); string availableId = context.Id ?? (from extensionId in extensionIds where !builder.ExistAny(extensionId) && (secondSlotConfigBuilder == null || !secondSlotConfigBuilder.ExistAny(extensionId)) select extensionId).FirstOrDefault(); var extensionList = (from id in extensionIds let e = GetExtension(id) where e != null select e).ToList(); string thumbprint = context.CertificateThumbprint; string thumbprintAlgorithm = context.ThumbprintAlgorithm; if (context.X509Certificate != null) { thumbprint = context.X509Certificate.Thumbprint; } else { GetThumbprintAndAlgorithm(extensionList, availableId, ref thumbprint, ref thumbprintAlgorithm); } context.CertificateThumbprint = string.IsNullOrWhiteSpace(context.CertificateThumbprint) ? thumbprint : context.CertificateThumbprint; context.ThumbprintAlgorithm = string.IsNullOrWhiteSpace(context.ThumbprintAlgorithm) ? thumbprintAlgorithm : context.ThumbprintAlgorithm; if (!string.IsNullOrWhiteSpace(context.CertificateThumbprint) && string.IsNullOrWhiteSpace(context.ThumbprintAlgorithm)) { context.ThumbprintAlgorithm = ThumbprintAlgorithmStr; } else if (string.IsNullOrWhiteSpace(context.CertificateThumbprint) && !string.IsNullOrWhiteSpace(context.ThumbprintAlgorithm)) { context.ThumbprintAlgorithm = string.Empty; } var existingExtension = extensionList.Find(e => e.Id == availableId); if (existingExtension != null) { DeleteExtension(availableId); } if (r.Default) { Cmdlet.WriteVerbose(string.Format(Resources.ServiceExtensionSettingForDefaultRole, context.Type)); } else { Cmdlet.WriteVerbose(string.Format(Resources.ServiceExtensionSettingForSpecificRole, context.Type, r.RoleName)); } AddExtension(new HostedServiceAddExtensionParameters { Id = availableId, Thumbprint = context.CertificateThumbprint, ThumbprintAlgorithm = context.ThumbprintAlgorithm, ProviderNamespace = context.ProviderNameSpace, Type = context.Type, PublicConfiguration = context.PublicConfiguration, PrivateConfiguration = context.PrivateConfiguration, Version = string.IsNullOrEmpty(context.Version) ? ExtensionDefaultVersion : context.Version }); if (r.Default) { builder.RemoveDefault(context.ProviderNameSpace, context.Type); builder.AddDefault(availableId); } else { builder.Remove(r.RoleName, context.ProviderNameSpace, context.Type); builder.Add(r.RoleName, availableId); } } return(builder.ToConfiguration()); }
public DeploymentInfoContext(DeploymentGetResponse deployment) { this.Slot = deployment.DeploymentSlot.ToString(); this.Name = deployment.Name; this.DeploymentName = deployment.Name; this.Url = deployment.Uri; this.Status = deployment.Status.ToString(); this.DeploymentId = deployment.PrivateId; this.VNetName = deployment.VirtualNetworkName; this.SdkVersion = deployment.SdkVersion; // IP Related this.ReservedIPName = deployment.ReservedIPName; this.VirtualIPs = deployment.VirtualIPAddresses == null ? null : new VirtualIPList( deployment.VirtualIPAddresses.Select(a => new VirtualIP { Address = a.Address, IsDnsProgrammed = a.IsDnsProgrammed, Name = a.Name })); if (deployment.DnsSettings != null) { this.DnsSettings = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsSettings { DnsServers = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServerList() }; foreach (var dns in deployment.DnsSettings.DnsServers) { var newDns = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServer { Name = dns.Name, Address = dns.Address.ToString() }; this.DnsSettings.DnsServers.Add(newDns); } } this.RollbackAllowed = deployment.RollbackAllowed; if (deployment.UpgradeStatus != null) { this.CurrentUpgradeDomain = deployment.UpgradeStatus.CurrentUpgradeDomain; this.CurrentUpgradeDomainState = deployment.UpgradeStatus.CurrentUpgradeDomainState.ToString(); this.UpgradeType = deployment.UpgradeStatus.UpgradeType.ToString(); } this.Configuration = string.IsNullOrEmpty(deployment.Configuration) ? string.Empty : deployment.Configuration; this.Label = string.IsNullOrEmpty(deployment.Label) ? string.Empty : deployment.Label; this.RoleInstanceList = deployment.RoleInstances; if (!string.IsNullOrEmpty(deployment.Configuration)) { string xmlString = this.Configuration; XDocument doc; using (var stringReader = new StringReader(xmlString)) { XmlReader reader = XmlReader.Create(stringReader); doc = XDocument.Load(reader); } this.OSVersion = doc.Root.Attribute("osVersion") != null? doc.Root.Attribute("osVersion").Value: string.Empty; this.RolesConfiguration = new Dictionary <string, RoleConfiguration>(); var roles = doc.Root.Descendants(this.ns + "Role"); foreach (var role in roles) { this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role)); } } }
public DeploymentInfoContext(DeploymentGetResponse deployment) : base(deployment) { }
public virtual void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Staging); var storageName = CurrentSubscription.CurrentStorageAccountName; Uri packageUrl; if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(this.Package); } else { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage); WriteProgress(progress); removePackage = true; packageUrl = this.RetryCall(s => AzureBlob.UploadPackageToBlob( this.StorageClient, storageName, this.Package, null)); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { string errorConfigInput = null; if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null && context.X509Certificate != null) { ExecuteClientActionNewSM( null, string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint), () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate))); } } var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); DeploymentGetResponse d = null; InvokeInOperationContext(() => { try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteExceptionDetails(ex); } } }); ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName); extConfig = extensionMgr.Set(d, ExtensionConfiguration, this.Slot); } var deploymentInput = new DeploymentCreateParameters { PackageUri = packageUrl, Configuration = GeneralUtilities.GetConfiguration(this.Configuration), ExtensionConfiguration = extConfig, Label = this.Label, Name = this.Name, StartDeployment = !this.DoNotStart.IsPresent, TreatWarningsAsError = this.TreatWarningsAsError.IsPresent, }; InvokeInOperationContext(() => { try { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.CreatingNewDeployment); WriteProgress(progress); ExecuteClientActionNewSM( deploymentInput, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.Create( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), deploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.StorageClient, storageName, packageUrl)); } } catch (CloudException ex) { this.WriteExceptionDetails(ex); } }); }
public Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration Set(DeploymentGetResponse currentDeployment, ExtensionConfigurationInput[] inputs, string slot) { string errorConfigInput = null; if (!Validate(inputs, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } var oldExtConfig = currentDeployment != null ? currentDeployment.ExtensionConfiguration : new ExtensionConfiguration(); ExtensionConfigurationBuilder configBuilder = this.GetBuilder(); foreach (ExtensionConfigurationInput context in inputs) { if (context != null) { Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration currentConfig = this.InstallExtension(context, slot, oldExtConfig); foreach (var r in currentConfig.AllRoles) { if (currentDeployment == null || !this.GetBuilder(currentDeployment.ExtensionConfiguration).ExistAny(r.Id)) { configBuilder.AddDefault(r.Id); } } foreach (var r in currentConfig.NamedRoles) { foreach (var e in r.Extensions) { if (currentDeployment == null || !this.GetBuilder(currentDeployment.ExtensionConfiguration).ExistAny(e.Id)) { configBuilder.Add(r.RoleName, e.Id); } } } } } var extConfig = configBuilder.ToConfiguration(); return(extConfig); }
public void ExecuteCommand() { string configString = string.Empty; if (!string.IsNullOrEmpty(Configuration)) { configString = GeneralUtilities.GetConfiguration(Configuration); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { string errorConfigInput = null; if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null && context.X509Certificate != null) { ExecuteClientActionNewSM( null, string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint), () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate))); } } var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); DeploymentGetResponse d = null; InvokeInOperationContext(() => { try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteExceptionDetails(ex); } } }); ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName); extConfig = extensionMgr.Add(d, ExtensionConfiguration, this.Slot); } // Upgrade Parameter Set if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0) { bool removePackage = false; var storageName = Profile.Context.Subscription.GetProperty(AzureSubscription.Property.StorageAccount); Uri packageUrl = null; if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(Package); } else { if (string.IsNullOrEmpty(storageName)) { throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet); } var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage); WriteProgress(progress); removePackage = true; InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null))); } DeploymentUpgradeMode upgradeMode; if (!Enum.TryParse <DeploymentUpgradeMode>(Mode, out upgradeMode)) { upgradeMode = DeploymentUpgradeMode.Auto; } var upgradeDeploymentInput = new DeploymentUpgradeParameters { Mode = upgradeMode, Configuration = configString, ExtensionConfiguration = extConfig, PackageUri = packageUrl, Label = Label ?? ServiceName, Force = Force.IsPresent }; if (!string.IsNullOrEmpty(RoleName)) { upgradeDeploymentInput.RoleToUpgrade = RoleName; } InvokeInOperationContext(() => { try { ExecuteClientActionNewSM( upgradeDeploymentInput, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.UpgradeBySlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), upgradeDeploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.StorageClient, storageName, packageUrl)); } } catch (CloudException ex) { this.WriteExceptionDetails(ex); } }); } else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0) { // Config parameter set var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters { Configuration = configString, ExtensionConfiguration = extConfig }; ExecuteClientActionNewSM( changeDeploymentStatusParams, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.ChangeConfigurationBySlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), changeDeploymentStatusParams)); } else { // Status parameter set var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters { Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true) }; ExecuteClientActionNewSM( null, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), updateDeploymentStatusParams)); } }
public DeploymentInfoContext(DeploymentGetResponse deployment) { this.Slot = deployment.DeploymentSlot.ToString(); this.Name = deployment.Name; this.DeploymentName = deployment.Name; this.Url = deployment.Uri; this.Status = deployment.Status.ToString(); this.DeploymentId = deployment.PrivateId; this.VNetName = deployment.VirtualNetworkName; this.SdkVersion = deployment.SdkVersion; // IP Related this.ReservedIPName = deployment.ReservedIPName; this.VirtualIPs = deployment.VirtualIPAddresses == null ? null : new VirtualIPList( deployment.VirtualIPAddresses.Select(a => new VirtualIP { Address = a.Address, IsDnsProgrammed = a.IsDnsProgrammed, Name = a.Name })); if (deployment.DnsSettings != null) { this.DnsSettings = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsSettings { DnsServers = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServerList() }; foreach (var dns in deployment.DnsSettings.DnsServers) { var newDns = new Microsoft.WindowsAzure.Commands.ServiceManagement.Model.PersistentVMModel.DnsServer { Name = dns.Name, Address = dns.Address.ToString() }; this.DnsSettings.DnsServers.Add(newDns); } } this.RollbackAllowed = deployment.RollbackAllowed; if (deployment.UpgradeStatus != null) { this.CurrentUpgradeDomain = deployment.UpgradeStatus.CurrentUpgradeDomain; this.CurrentUpgradeDomainState = deployment.UpgradeStatus.CurrentUpgradeDomainState.ToString(); this.UpgradeType = deployment.UpgradeStatus.UpgradeType.ToString(); } this.Configuration = string.IsNullOrEmpty(deployment.Configuration) ? string.Empty : deployment.Configuration; this.Label = string.IsNullOrEmpty(deployment.Label) ? string.Empty : deployment.Label; this.RoleInstanceList = deployment.RoleInstances; if (!string.IsNullOrEmpty(deployment.Configuration)) { string xmlString = this.Configuration; XDocument doc; using (var stringReader = new StringReader(xmlString)) { XmlReader reader = XmlReader.Create(stringReader); doc = XDocument.Load(reader); } this.OSVersion = doc.Root.Attribute("osVersion") != null ? doc.Root.Attribute("osVersion").Value : string.Empty; this.RolesConfiguration = new Dictionary<string, RoleConfiguration>(); var roles = doc.Root.Descendants(this.ns + "Role"); foreach (var role in roles) { this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role)); } } }