public override void ExecuteCmdlet() { WriteVerboseWithTimestamp(string.Format(Resources.UpdateAzureApplicationGatewayBeginOperation, CommandRuntime.ToString())); if (String.IsNullOrEmpty(VnetName) && (Subnets == null || Subnets.Count == 0) && InstanceCount == 0 && String.IsNullOrEmpty(GatewaySize) && String.IsNullOrEmpty(Description)) { WriteObject("Invalid Arguments: Pass at least one argument other than gateway name."); WriteVerboseWithTimestamp(string.Format(Resources.UpdateAzureApplicationGatewayCompletedOperation, CommandRuntime.ToString())); return; } var responseObject = Client.UpdateApplicationGateway(Name, VnetName, Subnets, Description, InstanceCount, GatewaySize); WriteVerboseWithTimestamp(string.Format(Resources.UpdateAzureApplicationGatewayCompletedOperation, CommandRuntime.ToString())); WriteObject(responseObject); }
public virtual void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Staging); var storageName = CurrentContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount); 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); } }); }
protected override void ExecuteCommand() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); if (CurrentDeploymentNewSM == null) { return; } var role = CurrentDeploymentNewSM.Roles.FirstOrDefault(r => r.RoleName.Equals(Name, StringComparison.InvariantCultureIgnoreCase)); if (role == null) { throw new ApplicationException(string.Format(Resources.NoCorrespondingRoleCanBeFoundInDeployment, Name)); } try { var vm = role; var roleInstance = CurrentDeploymentNewSM.RoleInstances.First(r => r.RoleName == vm.RoleName); var vmContext = new PersistentVMRoleContext { ServiceName = ServiceName, Name = vm.RoleName, DeploymentName = CurrentDeploymentNewSM.Name, AvailabilitySetName = vm.AvailabilitySetName, Label = vm.Label, InstanceSize = vm.RoleSize.ToString(), InstanceStatus = roleInstance.InstanceStatus, IpAddress = roleInstance.IPAddress, InstanceStateDetails = roleInstance.InstanceStateDetails, PowerState = roleInstance.PowerState.ToString(), InstanceErrorCode = roleInstance.InstanceErrorCode, InstanceName = roleInstance.InstanceName, InstanceFaultDomain = roleInstance.InstanceFaultDomain.HasValue ? roleInstance.InstanceFaultDomain.Value.ToString(CultureInfo.InvariantCulture) : null, InstanceUpgradeDomain = roleInstance.InstanceUpgradeDomain.HasValue ? roleInstance.InstanceUpgradeDomain.Value.ToString(CultureInfo.InvariantCulture) : null, OperationDescription = CommandRuntime.ToString(), OperationId = GetDeploymentOperationNewSM.Id, OperationStatus = GetDeploymentOperationNewSM.Status.ToString(), VM = new PersistentVM { AvailabilitySetName = vm.AvailabilitySetName, ConfigurationSets = PersistentVMHelper.MapConfigurationSets(vm.ConfigurationSets), DataVirtualHardDisks = new Collection <DataVirtualHardDisk>(), Label = vm.Label, OSVirtualHardDisk = Mapper.Map(vm.OSVirtualHardDisk, new OSVirtualHardDisk()), RoleName = vm.RoleName, RoleSize = vm.RoleSize.ToString(), RoleType = vm.RoleType, DefaultWinRmCertificateThumbprint = vm.DefaultWinRmCertificateThumbprint, ProvisionGuestAgent = vm.ProvisionGuestAgent, ResourceExtensionReferences = Mapper.Map <PVM.ResourceExtensionReferenceList>(vm.ResourceExtensionReferences) } }; if (vm.DataVirtualHardDisks != null) { vm.DataVirtualHardDisks.ForEach( d => vmContext.VM.DataVirtualHardDisks.Add(Mapper.Map <DataVirtualHardDisk>(d))); } else { vmContext.VM.DataVirtualHardDisks = null; } PersistentVMHelper.SaveStateToFile(vmContext.VM, Path); WriteObject(vmContext, true); } catch (Exception e) { throw new ApplicationException(string.Format(Resources.VMPropertiesCanNotBeRead, role.RoleName), e); } }
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 = CurrentContext.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 override void ExecuteCmdlet() { WriteVerboseWithTimestamp(string.Format(Resources.RemoveAzureApplicationGatewayBeginOperation, CommandRuntime.ToString())); var responseObject = Client.RemoveApplicationGateway(Name); WriteVerboseWithTimestamp(string.Format(Resources.RemoveAzureApplicationGatewayCompletedOperation, CommandRuntime.ToString())); WriteObject(responseObject); }
internal void ExecuteCommandNewSM() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); AzureSubscription currentSubscription = CurrentContext.Subscription; if (CurrentDeploymentNewSM == null) { throw new ApplicationException(String.Format(Resources.CouldNotFindDeployment, ServiceName, Model.DeploymentSlotType.Production)); } // Auto generate disk names based off of default storage account foreach (var datadisk in this.VM.DataVirtualHardDisks) { if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName)) { CloudStorageAccount currentStorage = currentSubscription.GetCloudStorageAccount(); if (currentStorage == null) { throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible); } DateTime dateTimeCreated = DateTime.Now; string diskPartName = VM.RoleName; if (datadisk.DiskLabel != null) { diskPartName += "-" + datadisk.DiskLabel; } string vhdname = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", ServiceName, diskPartName, dateTimeCreated.Year, dateTimeCreated.Month, dateTimeCreated.Day, dateTimeCreated.Millisecond); string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri; if (blobEndpoint.EndsWith("/") == false) { blobEndpoint += "/"; } datadisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname); } if (VM.DataVirtualHardDisks.Count > 1) { // To avoid duplicate disk names System.Threading.Thread.Sleep(1); } } var parameters = new VirtualMachineUpdateParameters { AvailabilitySetName = VM.AvailabilitySetName, Label = VM.Label, OSVirtualHardDisk = Mapper.Map <OSVirtualHardDisk>(VM.OSVirtualHardDisk), RoleName = VM.RoleName, RoleSize = VM.RoleSize, ProvisionGuestAgent = VM.ProvisionGuestAgent, ResourceExtensionReferences = VM.ProvisionGuestAgent != null && VM.ProvisionGuestAgent.Value ? Mapper.Map <List <ResourceExtensionReference> >(VM.ResourceExtensionReferences) : null }; if (VM.DataVirtualHardDisks != null) { VM.DataVirtualHardDisks.ForEach(c => { var dataDisk = Mapper.Map <DataVirtualHardDisk>(c); dataDisk.LogicalUnitNumber = dataDisk.LogicalUnitNumber; parameters.DataVirtualHardDisks.Add(dataDisk); }); } if (VM.ConfigurationSets != null) { PersistentVMHelper.MapConfigurationSets(VM.ConfigurationSets).ForEach(c => parameters.ConfigurationSets.Add(c)); } if (VM.DataVirtualHardDisksToBeDeleted != null && VM.DataVirtualHardDisksToBeDeleted.Any()) { var vmRole = CurrentDeploymentNewSM.Roles.First(r => r.RoleName == this.Name); if (vmRole != null) { foreach (var dataDiskToBeDeleted in VM.DataVirtualHardDisksToBeDeleted) { int lun = dataDiskToBeDeleted.Lun; try { this.ComputeClient.VirtualMachineDisks.DeleteDataDisk( this.ServiceName, CurrentDeploymentNewSM.Name, vmRole.RoleName, lun, true); } catch (CloudException ex) { WriteWarning(string.Format(Resources.CannotDeleteVirtualMachineDataDiskForLUN, lun)); if (ex.Response.StatusCode != System.Net.HttpStatusCode.NotFound) { throw; } } } } } ExecuteClientActionNewSM( parameters, CommandRuntime.ToString(), () => this.ComputeClient.VirtualMachines.Update(this.ServiceName, CurrentDeploymentNewSM.Name, this.Name, parameters)); }
private void WriteExtendedSubscription(SubscriptionData subscriptionData, string subscriptionsDataFile) { SubscriptionData currentSubscription = this.GetCurrentSubscription(); this.SetCurrentSubscription(subscriptionData.SubscriptionName, subscriptionsDataFile); InitChannelCurrentSubscription(); using (new OperationContextScope(Channel.ToContextChannel())) { try { var subprops = RetryCall(s => Channel.GetSubscription(subscriptionData.SubscriptionId)); Operation operation = GetOperation(); var subscriptionDataExtended = new SubscriptionDataExtended(subprops, subscriptionData, CommandRuntime.ToString(), operation); WriteSubscription(subscriptionDataExtended); } catch (CommunicationException ex) { WriteErrorDetails(ex); } finally { if (currentSubscription != null && currentSubscription.Certificate != null && currentSubscription.SubscriptionId != null) { this.SetCurrentSubscription(currentSubscription.SubscriptionName, subscriptionsDataFile); } } } }
internal override void ExecuteCommand() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); if (!string.IsNullOrEmpty(ServiceName) && CurrentDeploymentNewSM == null) { return; } var roles = new List <PersistentVMRoleContext>(); IList <Management.Compute.Models.Role> vmRoles; if (string.IsNullOrEmpty(ServiceName)) { ListAllVMs(); return; } if (string.IsNullOrEmpty(Name)) { vmRoles = CurrentDeploymentNewSM.Roles; } else { vmRoles = new List <Management.Compute.Models.Role>(CurrentDeploymentNewSM.Roles.Where(r => r.RoleName.Equals(Name, StringComparison.InvariantCultureIgnoreCase))); } foreach (var role in vmRoles) { string lastVM = string.Empty; try { lastVM = role.RoleName; var vm = role; var roleInstance = CurrentDeploymentNewSM.RoleInstances.First(r => r.RoleName == vm.RoleName); var vmContext = new PersistentVMRoleContext { ServiceName = ServiceName, Name = vm.RoleName, DeploymentName = CurrentDeploymentNewSM.Name, AvailabilitySetName = vm.AvailabilitySetName, Label = vm.Label, InstanceSize = vm.RoleSize.ToString(), InstanceStatus = roleInstance.InstanceStatus, IpAddress = roleInstance.IPAddress, InstanceStateDetails = roleInstance.InstanceStateDetails, PowerState = roleInstance.PowerState.ToString(), InstanceErrorCode = roleInstance.InstanceErrorCode, InstanceName = roleInstance.InstanceName, InstanceFaultDomain = roleInstance.InstanceFaultDomain.HasValue ? roleInstance.InstanceFaultDomain.Value.ToString(CultureInfo.InvariantCulture) : null, InstanceUpgradeDomain = roleInstance.InstanceUpgradeDomain.HasValue ? roleInstance.InstanceUpgradeDomain.Value.ToString(CultureInfo.InvariantCulture) : null, OperationDescription = CommandRuntime.ToString(), OperationId = GetDeploymentOperationNewSM.Id, OperationStatus = GetDeploymentOperationNewSM.Status.ToString(), VM = new PersistentVM { AvailabilitySetName = vm.AvailabilitySetName, ConfigurationSets = PersistentVMHelper.MapConfigurationSets(vm.ConfigurationSets), DataVirtualHardDisks = Mapper.Map(vm.DataVirtualHardDisks, new Collection <DataVirtualHardDisk>()), Label = vm.Label, OSVirtualHardDisk = Mapper.Map(vm.OSVirtualHardDisk, new OSVirtualHardDisk()), RoleName = vm.RoleName, RoleSize = vm.RoleSize.ToString(), RoleType = vm.RoleType, DefaultWinRmCertificateThumbprint = vm.DefaultWinRmCertificateThumbprint } }; if (CurrentDeploymentNewSM != null) { vmContext.DNSName = CurrentDeploymentNewSM.Uri.AbsoluteUri; } roles.Add(vmContext); } catch (Exception e) { throw new ApplicationException(string.Format(Resources.VMPropertiesCanNotBeRead, lastVM), e); } } WriteObject(roles, true); }
public void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Staging); var storageName = CurrentSubscription.CurrentStorageAccount; 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, "Please wait...", "Uploading package to blob storage"); WriteProgress(progress); removePackage = true; packageUrl = this.RetryCall(s => AzureBlob.UploadPackageToBlob( this.Channel, storageName, s, this.Package, null)); } var config = string.Empty; if (this.Configuration.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || this.Configuration.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { config = this.RetryCall(s => AzureBlob.ReadConfigurationFromBlob( this.Channel, storageName, s, new Uri(this.Configuration))); } else { config = General.GetConfiguration(this.Configuration); } var deploymentInput = new CreateDeploymentInput { PackageUrl = packageUrl, Configuration = config, Label = this.Label, Name = this.Name, StartDeployment = !this.DoNotStart.IsPresent, TreatWarningsAsError = this.TreatWarningsAsError.IsPresent }; using (new OperationContextScope(Channel.ToContextChannel())) { try { var progress = new ProgressRecord(0, "Please wait...", "Creating the new deployment"); WriteProgress(progress); ExecuteClientAction(deploymentInput, CommandRuntime.ToString(), s => this.Channel.CreateOrUpdateDeployment(s, this.ServiceName, this.Slot, deploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.Channel, storageName, s, packageUrl)); } } catch (ServiceManagementClientException ex) { this.WriteErrorDetails(ex); } } }
protected override void ExecuteCommand() { base.ExecuteCommand(); if (CurrentDeploymentNewSM == null) { throw new ArgumentException(Resources.NoCloudServicePresent); } ManagementOperationContext context; string rdpFilePath = LocalPath ?? Path.GetTempFileName(); WriteVerboseWithTimestamp(string.Format(Resources.AzureRemoteDesktopBeginOperation, CommandRuntime)); var desktopFileResponse = this.ComputeClient.VirtualMachines.GetRemoteDesktopFile(this.ServiceName, CurrentDeploymentNewSM.Name, Name + "_IN_0"); using (var stream = new MemoryStream(desktopFileResponse.RemoteDesktopFile)) { using (var file = File.Create(rdpFilePath)) { int count; byte[] buffer = new byte[1000]; while ((count = stream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, count); } } var operation = GetOperationNewSM(desktopFileResponse.RequestId); WriteVerboseWithTimestamp(string.Format(Resources.AzureRemoteDesktopCompletedOperation, CommandRuntime)); context = new ManagementOperationContext { OperationDescription = CommandRuntime.ToString(), OperationStatus = operation.Status.ToString(), OperationId = operation.Id }; } if (Launch.IsPresent) { var startInfo = new ProcessStartInfo { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; if (LocalPath == null) { string scriptGuid = Guid.NewGuid().ToString(); string launchRDPScript = Path.GetTempPath() + scriptGuid + ".bat"; using (var scriptStream = File.OpenWrite(launchRDPScript)) { var writer = new StreamWriter(scriptStream); writer.WriteLine("start /wait mstsc.exe " + rdpFilePath); writer.WriteLine("del " + rdpFilePath); writer.WriteLine("del " + launchRDPScript); writer.Flush(); } startInfo.FileName = launchRDPScript; } else { startInfo.FileName = "mstsc.exe"; startInfo.Arguments = rdpFilePath; } Process.Start(startInfo); } WriteObject(context, true); }
internal override void ExecuteCommand() { base.ExecuteCommand(); if (!string.IsNullOrEmpty(ServiceName) && CurrentDeployment == null) { return; } List <PersistentVMRoleContext> roles = new List <PersistentVMRoleContext>(); RoleList vmRoles = null; if (string.IsNullOrEmpty(ServiceName)) { ListAllVMs(); return; } if (string.IsNullOrEmpty(Name)) { vmRoles = CurrentDeployment.RoleList; } else { vmRoles = new RoleList(CurrentDeployment.RoleList.Where(r => r.RoleName.Equals(Name, StringComparison.InvariantCultureIgnoreCase))); } foreach (Role role in vmRoles) { string lastVM = string.Empty; try { lastVM = role.RoleName; var vm = (PersistentVMRole)role; var roleInstance = CurrentDeployment.RoleInstanceList.First(r => r.RoleName == vm.RoleName); var vmContext = new PersistentVMRoleContext { ServiceName = ServiceName, Name = vm.RoleName, DeploymentName = CurrentDeployment.Name, AvailabilitySetName = vm.AvailabilitySetName, Label = vm.Label, InstanceSize = vm.RoleSize, InstanceStatus = roleInstance.InstanceStatus, IpAddress = roleInstance.IpAddress, InstanceStateDetails = roleInstance.InstanceStateDetails, PowerState = roleInstance.PowerState, InstanceErrorCode = roleInstance.InstanceErrorCode, InstanceName = roleInstance.InstanceName, InstanceFaultDomain = roleInstance.InstanceFaultDomain.Value.ToString(CultureInfo.InvariantCulture), InstanceUpgradeDomain = roleInstance.InstanceUpgradeDomain.Value.ToString(CultureInfo.InvariantCulture), OperationDescription = CommandRuntime.ToString(), OperationId = GetDeploymentOperation.OperationTrackingId, OperationStatus = GetDeploymentOperation.Status, VM = new PersistentVM { AvailabilitySetName = vm.AvailabilitySetName, ConfigurationSets = vm.ConfigurationSets, DataVirtualHardDisks = vm.DataVirtualHardDisks, Label = vm.Label, OSVirtualHardDisk = vm.OSVirtualHardDisk, RoleName = vm.RoleName, RoleSize = vm.RoleSize, RoleType = vm.RoleType, DefaultWinRmCertificateThumbprint = vm.DefaultWinRmCertificateThumbprint }, }; if (CurrentDeployment != null) { vmContext.DNSName = CurrentDeployment.Url.AbsoluteUri; } roles.Add(vmContext); } catch (Exception) { WriteObject(string.Format("Could not read properties for virtual machine: {0}. It may still be provisioning.", lastVM)); } } if (!string.IsNullOrEmpty(Name) && roles != null && roles.Count > 0) { SaveRoleState(roles[0].VM); } WriteObject(roles, true); }
public void RemoveDeploymentProcess() { ExecuteClientActionInOCS(null, CommandRuntime.ToString(), s => this.Channel.DeleteDeploymentBySlot(s, this.ServiceName, this.Slot)); }
public VirtualNetworkConfigContext GetVirtualNetworkConfigProcess() { this.ValidateParameters(); using (new OperationContextScope(Channel.ToContextChannel())) { try { WriteVerboseWithTimestamp(string.Format(Resources.AzureVNetConfigBeginOperation, CommandRuntime.ToString())); var netConfigStream = this.RetryCall(s => this.Channel.GetNetworkConfiguration(s)) as Stream; Operation operation = GetOperation(); WriteVerboseWithTimestamp(string.Format(Resources.AzureVNetConfigCompletedOperation, CommandRuntime.ToString())); if (netConfigStream != null) { // TODO: might want to change this to an XML object of some kind... var configReader = new StreamReader(netConfigStream); var xml = configReader.ReadToEnd(); var networkConfig = new VirtualNetworkConfigContext { XMLConfiguration = xml, OperationId = operation.OperationTrackingId, OperationDescription = CommandRuntime.ToString(), OperationStatus = operation.Status }; if (!string.IsNullOrEmpty(this.ExportToFile)) { networkConfig.ExportToFile(this.ExportToFile); } return(networkConfig); } } catch (ServiceManagementClientException ex) { if (ex.HttpStatus == HttpStatusCode.NotFound && !IsVerbose()) { return(null); } else { this.WriteErrorDetails(ex); } } return(null); } }
private void GetNoGatewayName() { WriteVerboseWithTimestamp(string.Format(Resources.GetAzureApplicationGatewayBeginOperation, CommandRuntime.ToString())); var gateways = Client.ListApplicationGateway(); WriteVerboseWithTimestamp(string.Format(Resources.GetAzureApplicationGatewayCompletedOperation, CommandRuntime.ToString())); WriteObject(gateways, true); }
private void ProcessShareImageParameterSet() { this.Channel.GetOSImage(CurrentSubscription.SubscriptionId, this.ImageName); ExecuteClientActionInOCS(null, CommandRuntime.ToString(), s => this.Channel.ShareOSImage(s, this.ImageName, this.Permission)); }
protected override void OnProcessRecord() { this.Channel.GetOSImage(CurrentSubscription.SubscriptionId, this.ImageName); ExecuteClientActionInOCS(null, CommandRuntime.ToString(), s => this.Channel.UnReplicateOSImage(s, this.ImageName)); }
private void ProcessReplicateImageParameterSet() { this.Channel.GetOSImage(CurrentSubscription.SubscriptionId, this.ImageName); ValidateTargetLocations(); ExecuteClientActionInOCS(null, CommandRuntime.ToString(), s => this.Channel.ReplicateOSImage(s, this.ImageName, CreateReplicationInput())); }
public override void ExecuteCmdlet() { if (CurrentSubscription == null) { throw new Exception(Resources.NoDefaultSubscriptionMessage); } if (!string.IsNullOrEmpty(Name)) { // Show website Site websiteObject = RetryCall(s => Channel.GetSite(s, Name, "repositoryuri,publishingpassword,publishingusername")); if (websiteObject == null) { throw new Exception(string.Format(Resources.InvalidWebsite, Name)); } SiteConfig websiteConfiguration = null; InvokeInOperationContext(() => { websiteConfiguration = RetryCall(s => Channel.GetSiteConfig(s, websiteObject.WebSpace, websiteObject.Name)); WaitForOperation(CommandRuntime.ToString()); }); // Add to cache Cache.AddSite(CurrentSubscription.SubscriptionId, websiteObject); DiagnosticsSettings diagnosticsSettings = null; if (websiteObject.State == "Running") { WebsitesClient = WebsitesClient ?? new WebsitesClient(CurrentSubscription, WriteDebug); diagnosticsSettings = WebsitesClient.GetApplicationDiagnosticsSettings(Name); } // Output results WriteObject(new SiteWithConfig(websiteObject, websiteConfiguration, diagnosticsSettings), false); } else { // Show websites WebSpaces webspaces = null; InvokeInOperationContext(() => { webspaces = RetryCall(s => Channel.GetWebSpaces(s)); WaitForOperation(CommandRuntime.ToString()); }); List <Site> websites = new List <Site>(); foreach (var webspace in webspaces) { InvokeInOperationContext(() => { websites.AddRange(RetryCall(s => Channel.GetSites(s, webspace.Name, "repositoryuri,publishingpassword,publishingusername"))); WaitForOperation(CommandRuntime.ToString()); }); } // Add to cache Cache.SaveSites(CurrentSubscription.SubscriptionId, new Sites(websites)); // Output results WriteWebsites(websites); } }
private T CreateVMContext <T>(string serviceName, NSM.Role vmRole, NSM.RoleInstance roleInstance, NSM.DeploymentGetResponse deployment) where T : PVM.PersistentVMRoleContext, new() { var vmContext = new T { ServiceName = serviceName, DeploymentName = deployment == null ? string.Empty : deployment.Name, DNSName = deployment == null || deployment.Uri == null ? string.Empty : deployment.Uri.AbsoluteUri, Name = vmRole == null ? string.Empty : vmRole.RoleName, AvailabilitySetName = vmRole == null ? string.Empty : vmRole.AvailabilitySetName, Label = vmRole == null ? string.Empty : vmRole.Label, InstanceSize = vmRole == null ? string.Empty : vmRole.RoleSize, InstanceStatus = roleInstance == null ? string.Empty : roleInstance.InstanceStatus, IpAddress = roleInstance == null ? string.Empty : roleInstance.IPAddress, PublicIPAddress = roleInstance == null ? string.Empty : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? string.Empty : roleInstance.PublicIPs.First().Address, PublicIPName = roleInstance == null ? string.Empty : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? string.Empty : !string.IsNullOrEmpty(roleInstance.PublicIPs.First().Name) ? roleInstance.PublicIPs.First().Name : PersistentVMHelper.GetPublicIPName(vmRole), PublicIPDomainNameLabel = roleInstance == null ? string.Empty : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? string.Empty : roleInstance.PublicIPs.First().DomainNameLabel, PublicIPFqdns = roleInstance == null ? new List <string>() : roleInstance.PublicIPs == null || !roleInstance.PublicIPs.Any() ? new List <string>() : roleInstance.PublicIPs.First().Fqdns.ToList(), InstanceStateDetails = roleInstance == null ? string.Empty : roleInstance.InstanceStateDetails, PowerState = roleInstance == null ? string.Empty : roleInstance.PowerState.ToString(), HostName = roleInstance == null ? string.Empty : roleInstance.HostName, 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), MaintenanceStatus = roleInstance == null ? null : Mapper.Map <PVM.MaintenanceStatus>(roleInstance.MaintenanceStatus), ResourceExtensionStatusList = roleInstance == null ? null : Mapper.Map <List <PVM.ResourceExtensionStatus> >(roleInstance.ResourceExtensionStatusList), OperationId = deployment == null ? string.Empty : deployment.RequestId, OperationStatus = deployment == null ? string.Empty : deployment.StatusCode.ToString(), OperationDescription = CommandRuntime.ToString(), NetworkInterfaces = roleInstance == null ? null : Mapper.Map <PVM.NetworkInterfaceList>(roleInstance.NetworkInterfaces), VirtualNetworkName = deployment == null ? null : deployment.VirtualNetworkName, RemoteAccessCertificateThumbprint = roleInstance == null ? string.Empty : roleInstance.RemoteAccessCertificateThumbprint, VM = new PVM.PersistentVM { AvailabilitySetName = vmRole == null ? string.Empty : vmRole.AvailabilitySetName, Label = vmRole == null ? string.Empty : vmRole.Label, RoleName = vmRole == null ? string.Empty : vmRole.RoleName, RoleSize = vmRole == null ? string.Empty : vmRole.RoleSize, RoleType = vmRole == null ? string.Empty : vmRole.RoleType, DefaultWinRmCertificateThumbprint = vmRole == null ? string.Empty : vmRole.DefaultWinRmCertificateThumbprint, ProvisionGuestAgent = vmRole == null ? null : vmRole.ProvisionGuestAgent, ResourceExtensionReferences = vmRole == null ? null : Mapper.Map <PVM.ResourceExtensionReferenceList>(vmRole.ResourceExtensionReferences), DataVirtualHardDisks = vmRole == null ? null : Mapper.Map <Collection <PVM.DataVirtualHardDisk> >(vmRole.DataVirtualHardDisks), OSVirtualHardDisk = vmRole == null ? null : Mapper.Map <PVM.OSVirtualHardDisk>(vmRole.OSVirtualHardDisk), ConfigurationSets = vmRole == null ? null : PersistentVMHelper.MapConfigurationSets(vmRole.ConfigurationSets), DebugSettings = (vmRole == null || vmRole.DebugSettings == null) ? null : Mapper.Map <PVM.DebugSettings>(vmRole.DebugSettings), MigrationState = vmRole == null ? string.Empty : vmRole.MigrationState, LicenseType = vmRole == null ? string.Empty : vmRole.LicenseType } }; return(vmContext); }
internal void ExecuteCommand() { ExecuteClientActionNewSM(null, CommandRuntime.ToString(), () => NetworkClient.ReservedIPs.Delete(ReservedIPName)); }
internal override void ExecuteCommand() { base.ExecuteCommand(); if (CurrentDeployment == null) { throw new ArgumentException(Resources.NoCloudServicePresent); } ManagementOperationContext context = null; string rdpFilePath = LocalPath ?? Path.GetTempFileName(); using (new OperationContextScope(Channel.ToContextChannel())) { WriteVerboseWithTimestamp(string.Format(Resources.AzureRemoteDesktopBeginOperation, CommandRuntime.ToString())); using (var stream = RetryCall(s => Channel.DownloadRDPFile(s, ServiceName, CurrentDeployment.Name, Name + "_IN_0"))) { using (var file = File.Create(rdpFilePath)) { int count; byte[] buffer = new byte[1000]; while ((count = stream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, count); } } Operation operation = GetOperation(); WriteVerboseWithTimestamp(string.Format(Resources.AzureRemoteDesktopCompletedOperation, CommandRuntime.ToString())); context = new ManagementOperationContext { OperationDescription = CommandRuntime.ToString(), OperationStatus = operation.Status, OperationId = operation.OperationTrackingId }; } } if (Launch.IsPresent) { var startInfo = new ProcessStartInfo() { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; if (LocalPath == null) { string scriptGuid = Guid.NewGuid().ToString(); string launchRDPScript = Path.GetTempPath() + scriptGuid + ".bat"; using (var scriptStream = File.OpenWrite(launchRDPScript)) { var writer = new StreamWriter(scriptStream); writer.WriteLine("start /wait mstsc.exe " + rdpFilePath); writer.WriteLine("del " + rdpFilePath); writer.WriteLine("del " + launchRDPScript); writer.Flush(); } startInfo.FileName = launchRDPScript; } else { startInfo.FileName = "mstsc.exe"; startInfo.Arguments = rdpFilePath; } Process.Start(startInfo); } WriteObject(context, true); }
public IEnumerable <VirtualNetworkSiteContext> GetVirtualNetworkSiteProcess() { IEnumerable <VirtualNetworkSiteContext> result = null; InvokeInOperationContext(() => { try { WriteVerboseWithTimestamp(string.Format(Resources.AzureVNetSiteBeginOperation, CommandRuntime.ToString())); var response = this.NetworkClient.Networks.List(); var sites = response.VirtualNetworkSites; if (!string.IsNullOrEmpty(this.VNetName)) { sites = sites.Where(s => string.Equals(s.Name, this.VNetName, StringComparison.InvariantCultureIgnoreCase)).ToList(); if (sites.Count() == 0) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.VirtualNetworkNameNotFound, this.VNetName), "VNetName"); } } var operation = GetOperation(response.RequestId); WriteVerboseWithTimestamp(string.Format(Resources.AzureVNetSiteCompletedOperation, CommandRuntime.ToString())); result = sites.Select(site => ContextFactory <NetworkListResponse.VirtualNetworkSite, VirtualNetworkSiteContext>(site, operation)); } catch (CloudException ex) { if (ex.Response.StatusCode == HttpStatusCode.NotFound && !IsVerbose()) { result = null; } else { WriteExceptionError(ex); } } }); return(result); }
public void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Staging); var storageName = CurrentSubscription.CurrentStorageAccount; 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.Channel, storageName, s, this.Package, null)); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { var roleList = (from c in ExtensionConfiguration where c != null from r in c.Roles select r).GroupBy(r => r.ToString()).Select(g => g.First()); foreach (var role in roleList) { var result = from c in ExtensionConfiguration where c != null && c.Roles.Any(r => r.ToString() == role.ToString()) select string.Format("{0}.{1}", c.ProviderNameSpace, c.Type); foreach (var s in result) { if (result.Count(t => t == s) > 1) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, s)); } } } ExtensionManager extensionMgr = new ExtensionManager(Channel, CurrentSubscription.SubscriptionId, ServiceName); Deployment currentDeployment = null; ExtensionConfiguration deploymentExtensionConfig = null; using (new OperationContextScope(Channel.ToContextChannel())) { try { currentDeployment = this.RetryCall(s => this.Channel.GetDeploymentBySlot(s, this.ServiceName, Slot)); deploymentExtensionConfig = currentDeployment == null ? null : extensionMgr.GetBuilder(currentDeployment.ExtensionConfiguration).ToConfiguration(); } catch (ServiceManagementClientException ex) { if (ex.HttpStatus != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteErrorDetails(ex); } } } ExtensionConfigurationBuilder configBuilder = extensionMgr.GetBuilder(); foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null) { if (context.X509Certificate != null) { var operationDescription = string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint); ExecuteClientActionInOCS(null, operationDescription, s => this.Channel.AddCertificates(s, this.ServiceName, CertUtils.Create(context.X509Certificate))); } ExtensionConfiguration currentConfig = extensionMgr.InstallExtension(context, Slot, deploymentExtensionConfig); foreach (var r in currentConfig.AllRoles) { if (currentDeployment == null || !extensionMgr.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 || !extensionMgr.GetBuilder(currentDeployment.ExtensionConfiguration).ExistAny(e.Id)) { configBuilder.Add(r.RoleName, e.Id); } } } } } extConfig = configBuilder.ToConfiguration(); } var deploymentInput = new CreateDeploymentInput { PackageUrl = packageUrl, Configuration = General.GetConfiguration(this.Configuration), ExtensionConfiguration = extConfig, Label = this.Label, Name = this.Name, StartDeployment = !this.DoNotStart.IsPresent, TreatWarningsAsError = this.TreatWarningsAsError.IsPresent }; using (new OperationContextScope(Channel.ToContextChannel())) { try { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.CreatingNewDeployment); WriteProgress(progress); ExecuteClientAction(deploymentInput, CommandRuntime.ToString(), s => this.Channel.CreateOrUpdateDeployment(s, this.ServiceName, this.Slot, deploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.Channel, storageName, s, packageUrl)); } } catch (ServiceManagementClientException ex) { this.WriteErrorDetails(ex); } } }
protected override void ExecuteCommand() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); if (CurrentDeploymentNewSM == null) { WriteWarning(string.Format(Resources.NoDeploymentFoundByServiceAndVMName, this.ServiceName, this.Name)); return; } Model.VirtualMachineImageType otherImagetype = Model.VirtualMachineImageType.None; if (!ValidateNoImageInOtherType(out otherImagetype)) { // If there is another type of image with the same name, // WAPS will stop here to avoid duplicates and potential conflicts WriteErrorWithTimestamp( string.Format( Resources.ErrorAnotherImageTypeFoundWithTheSameName, otherImagetype, this.ImageName)); return; } Func <OperationStatusResponse> action = null; if (string.IsNullOrEmpty(this.OSState)) { action = () => this.ComputeClient.VirtualMachines.CaptureOSImage( this.ServiceName, CurrentDeploymentNewSM.Name, this.Name, new VirtualMachineCaptureOSImageParameters { PostCaptureAction = PostCaptureAction.Delete, TargetImageLabel = string.IsNullOrEmpty(this.ImageLabel) ? this.ImageName : this.ImageLabel, TargetImageName = this.ImageName }); } else { if (string.Equals(GetRoleInstanceStatus(), RoleInstanceStatus.ReadyRole)) { WriteWarning(Resources.CaptureVMImageOperationWhileVMIsStillRunning); } action = () => this.ComputeClient.VirtualMachines.CaptureVMImage( this.ServiceName, CurrentDeploymentNewSM.Name, this.Name, new VirtualMachineCaptureVMImageParameters { VMImageName = this.ImageName, VMImageLabel = string.IsNullOrEmpty(this.ImageLabel) ? this.ImageName : this.ImageLabel, OSState = this.OSState }); } if (action != null) { ExecuteClientActionNewSM(null, CommandRuntime.ToString(), action); } }
protected override void OnProcessRecord() { ServiceManagementProfile.Initialize(); var imageType = new VirtualMachineImageHelper(this.ComputeClient).GetImageType(this.ImageName); bool isOSImage = imageType.HasFlag(VirtualMachineImageType.OSImage); bool isVMImage = imageType.HasFlag(VirtualMachineImageType.VMImage); if (isOSImage || !isVMImage) { ExecuteClientActionNewSM( null, CommandRuntime.ToString(), () => this.ComputeClient.VirtualMachineOSImages.GetDetails(this.ImageName), (operation, imageDetails) => imageDetails == null ? null : new OSImageDetailsContext { AffinityGroup = imageDetails.AffinityGroup, Category = imageDetails.Category, Label = imageDetails.Label, Location = imageDetails.Location, MediaLink = imageDetails.MediaLinkUri, ImageName = imageDetails.Name, OS = imageDetails.OperatingSystemType, LogicalSizeInGB = (int)imageDetails.LogicalSizeInGB, Eula = imageDetails.Eula, Description = imageDetails.Description, IconUri = imageDetails.IconUri, ImageFamily = imageDetails.ImageFamily, IsPremium = imageDetails.IsPremium, PrivacyUri = imageDetails.PrivacyUri, PublishedDate = imageDetails.PublishedDate, RecommendedVMSize = imageDetails.RecommendedVMSize, IsCorrupted = imageDetails.IsCorrupted, SmallIconUri = imageDetails.SmallIconUri, PublisherName = imageDetails.PublisherName, ReplicationProgress = imageDetails.ReplicationProgress.Select( detail => new ReplicationProgressContext { Location = detail.Location, Progress = detail.Progress }).ToList(), OperationId = operation.RequestId, OperationDescription = CommandRuntime.ToString(), OperationStatus = operation.Status.ToString() }); } if (isVMImage) { ExecuteClientActionNewSM( null, CommandRuntime.ToString(), () => this.ComputeClient.VirtualMachineVMImages.GetDetails(this.ImageName), (operation, imageDetails) => imageDetails == null ? null : new VMImageDetailsContext { AffinityGroup = imageDetails.AffinityGroup, Location = imageDetails.Location, Category = imageDetails.Category, Label = imageDetails.Label, ImageName = imageDetails.Name, Eula = imageDetails.Eula, Description = imageDetails.Description, IconUri = imageDetails.IconUri, ImageFamily = imageDetails.ImageFamily, IsPremium = imageDetails.IsPremium, PrivacyUri = imageDetails.PrivacyUri, PublishedDate = imageDetails.PublishedDate, RecommendedVMSize = imageDetails.RecommendedVMSize, IsCorrupted = imageDetails.IsCorrupted, SmallIconUri = imageDetails.SmallIconUri, SharingStatus = imageDetails.SharingStatus, PublisherName = imageDetails.PublisherName, ReplicationProgress = imageDetails.ReplicationProgress.Select( detail => new ReplicationProgressContext { Location = detail.Location, Progress = detail.Progress }).ToList(), OperationId = operation.RequestId, OperationDescription = CommandRuntime.ToString(), OperationStatus = operation.Status.ToString() }); } }
public void ExecuteCommand() { string configString = string.Empty; if (!string.IsNullOrEmpty(Configuration)) { configString = General.GetConfiguration(Configuration); } // Upgrade Parameter Set if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0) { bool removePackage = false; CurrentSubscription = this.GetCurrentSubscription(); var storageName = CurrentSubscription.CurrentStorageAccount; 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("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it."); } var progress = new ProgressRecord(0, "Please wait...", "Uploading package to blob storage"); WriteProgress(progress); removePackage = true; InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.Channel, storageName, s, Package, null))); } var upgradeDeploymentInput = new UpgradeDeploymentInput { Mode = Mode ?? UpgradeType.Auto, Configuration = configString, PackageUrl = packageUrl, Label = Label != null ? Label : ServiceName, Force = Force.IsPresent }; if (!string.IsNullOrEmpty(RoleName)) { upgradeDeploymentInput.RoleToUpgrade = RoleName; } using (new OperationContextScope(Channel.ToContextChannel())) { try { ExecuteClientAction(upgradeDeploymentInput, CommandRuntime.ToString(), s => this.Channel.UpgradeDeploymentBySlot(s, this.ServiceName, this.Slot, upgradeDeploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.Channel, storageName, s, packageUrl)); } } catch (ServiceManagementClientException ex) { this.WriteErrorDetails(ex); } } } else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0) { // Config parameter set var changeConfiguration = new ChangeConfigurationInput { Configuration = configString }; ExecuteClientActionInOCS(changeConfiguration, CommandRuntime.ToString(), s => this.Channel.ChangeConfigurationBySlot(s, this.ServiceName, this.Slot, changeConfiguration)); } else { // Status parameter set var updateDeploymentStatus = new UpdateDeploymentStatusInput() { Status = this.NewStatus }; ExecuteClientActionInOCS(null, CommandRuntime.ToString(), s => this.Channel.UpdateDeploymentStatusBySlot(s, this.ServiceName, this.Slot, updateDeploymentStatus)); } }
internal void ExecuteCommandNewSM() { ServiceManagementProfile.Initialize(); base.ExecuteCommand(); IAzureSubscription currentSubscription = Profile.Context.Subscription; if (CurrentDeploymentNewSM == null) { throw new ApplicationException(String.Format(Resources.CouldNotFindDeployment, ServiceName, Model.DeploymentSlotType.Production)); } // Auto generate disk names based off of default storage account foreach (var datadisk in this.VM.DataVirtualHardDisks) { if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName)) { CloudStorageAccount currentStorage = Profile.Context.GetCurrentStorageAccount( new RDFEStorageProvider(AzureSession.Instance.ClientFactory.CreateClient <StorageManagementClient>( Profile.Context, AzureEnvironment.Endpoint.ServiceManagement), Profile.Context.Environment)); if (currentStorage == null) { throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible); } string diskPartName = VM.RoleName; if (datadisk.DiskLabel != null) { diskPartName += "-" + datadisk.DiskLabel; } var mediaLinkFactory = new MediaLinkFactory(currentStorage, this.ServiceName, diskPartName); datadisk.MediaLink = mediaLinkFactory.Create(); } if (VM.DataVirtualHardDisks.Count > 1) { // To avoid duplicate disk names System.Threading.Thread.Sleep(1); } } var parameters = new VirtualMachineUpdateParameters { AvailabilitySetName = VM.AvailabilitySetName, Label = VM.Label, OSVirtualHardDisk = Mapper.Map <OSVirtualHardDisk>(VM.OSVirtualHardDisk), RoleName = VM.RoleName, RoleSize = VM.RoleSize, ProvisionGuestAgent = VM.ProvisionGuestAgent, ResourceExtensionReferences = VM.ProvisionGuestAgent != null && VM.ProvisionGuestAgent.Value ? Mapper.Map <List <ResourceExtensionReference> >(VM.ResourceExtensionReferences) : null }; if (parameters.OSVirtualHardDisk != null) { parameters.OSVirtualHardDisk.IOType = null; } if (VM.DataVirtualHardDisks != null) { parameters.DataVirtualHardDisks = new List <DataVirtualHardDisk>(); VM.DataVirtualHardDisks.ForEach(c => { var dataDisk = Mapper.Map <DataVirtualHardDisk>(c); dataDisk.LogicalUnitNumber = dataDisk.LogicalUnitNumber; parameters.DataVirtualHardDisks.Add(dataDisk); }); parameters.DataVirtualHardDisks.ForEach(d => d.IOType = null); } if (VM.ConfigurationSets != null) { PersistentVMHelper.MapConfigurationSets(VM.ConfigurationSets).ForEach(c => parameters.ConfigurationSets.Add(c)); } if (VM.DataVirtualHardDisksToBeDeleted != null && VM.DataVirtualHardDisksToBeDeleted.Any()) { var vmRole = CurrentDeploymentNewSM.Roles.First(r => r.RoleName == this.Name); if (vmRole != null) { foreach (var dataDiskToBeDeleted in VM.DataVirtualHardDisksToBeDeleted) { int lun = dataDiskToBeDeleted.Lun; try { this.ComputeClient.VirtualMachineDisks.DeleteDataDisk( this.ServiceName, CurrentDeploymentNewSM.Name, vmRole.RoleName, lun, true); } catch (CloudException ex) { WriteWarning(string.Format(Resources.CannotDeleteVirtualMachineDataDiskForLUN, lun)); if (ex.Response.StatusCode != System.Net.HttpStatusCode.NotFound) { throw; } } } } } if (VM.DebugSettings != null) { parameters.DebugSettings = new DebugSettings { BootDiagnosticsEnabled = VM.DebugSettings.BootDiagnosticsEnabled }; } ExecuteClientActionNewSM( parameters, CommandRuntime.ToString(), () => this.ComputeClient.VirtualMachines.Update(this.ServiceName, CurrentDeploymentNewSM.Name, this.Name, parameters)); }
protected bool DoesCloudServiceExist(string serviceName) { bool isPresent = false; using (new OperationContextScope(Channel.ToContextChannel())) { try { WriteVerboseWithTimestamp(string.Format("Begin Operation: {0}", CommandRuntime.ToString())); AvailabilityResponse response = this.RetryCall(s => this.Channel.IsDNSAvailable(s, serviceName)); WriteVerboseWithTimestamp(string.Format("Completed Operation: {0}", CommandRuntime.ToString())); isPresent = !response.Result; } catch (ServiceManagementClientException ex) { if (ex.HttpStatus == HttpStatusCode.NotFound) { isPresent = false; } else { this.WriteErrorDetails(ex); } } } return(isPresent); }
/// <summary> /// This calls the command. It assumes that Prepare() has already been called. /// JonN 2003-04-02 Split from Execute() /// </summary> /// <exception cref="PipelineStoppedException"> /// a terminating error occurred, or the pipeline was otherwise stopped /// </exception> internal override void ProcessRecord() { // Invoke the Command method with the request object if (!this.RanBeginAlready) { RanBeginAlready = true; try { // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { if (Context._debuggingMode > 0 && !(Command is PSScriptCmdlet)) { Context.Debugger.CheckCommand(this.Command.MyInvocation); } Command.DoBeginProcessing(); } } // 2004/03/18-JonN This is understood to be // an FXCOP violation, cleared by KCwalina. catch (Exception e) // Catch-all OK, 3rd party callout. { // This cmdlet threw an exception, so // wrap it and bubble it up. throw ManageInvocationException(e); } } Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipeline was started while (Read()) { Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe; Exception exceptionToThrow = null; try { // // On V1 the output pipe was redirected to the command's output pipe only when it // was already redirected. This is the original comment explaining this behaviour: // // NTRAID#Windows Out of Band Releases-926183-2005-12-15 // MonadTestHarness has a bad dependency on an artifact of the current implementation // The following code only redirects the output pipe if it's already redirected // to preserve the artifact. The test suites need to be fixed and then this // the check can be removed and the assignment always done. // // However, this makes the hosting APIs behave differently than commands executed // from the command-line host (for example, see bugs Win7:415915 and Win7:108670). // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { if (CmdletParameterBinderController.ObsoleteParameterWarningList != null && CmdletParameterBinderController.ObsoleteParameterWarningList.Count > 0) { // Write out warning messages for the pipeline-value-bound obsolete parameters. // The warning message are generated during parameter binding, but we delay writing // them out until now so that the -WarningAction will be respected as expected. foreach (WarningRecord warningRecord in CmdletParameterBinderController.ObsoleteParameterWarningList) { CommandRuntime.WriteWarning(warningRecord); } // Clear up the warning message list CmdletParameterBinderController.ObsoleteParameterWarningList.Clear(); } this.Command.MyInvocation.PipelineIterationInfo[this.Command.MyInvocation.PipelinePosition]++; Command.DoProcessRecord(); } } catch (RuntimeException rte) { // Most exceptions get wrapped here, but an exception that originated from // a throw statement should not get wrapped, so it is just rethrown. if (rte.WasThrownFromThrowStatement) { throw; } exceptionToThrow = rte; } catch (LoopFlowException) { // Win8:84066 - Don't wrap LoopFlowException, we incorrectly raise a PipelineStoppedException // which gets caught by a script try/catch if we wrap here. throw; } // 2004/03/18-JonN This is understood to be // an FXCOP violation, cleared by KCwalina. catch (Exception e) // Catch-all OK, 3rd party callout. { exceptionToThrow = e; } finally { _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; } if (exceptionToThrow != null) { // This cmdlet threw an exception, so // wrap it and bubble it up. throw ManageInvocationException(exceptionToThrow); } } }
private void GetNoCertificateName() { WriteVerboseWithTimestamp(string.Format(Resources.GetAzureApplicationGatewaySslCertificateBeginOperation, CommandRuntime.ToString())); var certificates = Client.ListApplicationGatewayCertificate(Name); WriteVerboseWithTimestamp(string.Format(Resources.GetAzureApplicationGatewaySslCertificateCompletedOperation, CommandRuntime.ToString())); WriteObject(certificates, true); }