Example #1
0
        /// <summary>
        /// Creates a deployment payload for a predefined template
        /// </summary>
        /// <returns>A string xml representation</returns>
        protected override string CreatePayload()
        {
            var deployment = PersistentVMRole.AddAdhocLinuxRoleTemplates(new List <LinuxVirtualMachineProperties>(new[] { Properties }));
            var document   = new XDocument(deployment[0].GetXmlTree());

            return(document.ToStringFullXmlDeclarationWithReplace());
        }
Example #2
0
        /// <summary>
        /// Creates a deployment payload for a predefined template
        /// </summary>
        /// <returns>A string xml representation</returns>
        protected override string CreatePayload()
        {
            var deployment = new NetworkConfigurationSet {
                InputEndpoints = AllEndpoints
            };
            var template = new PersistentVMRole {
                NetworkConfigurationSet = deployment, RoleName = RoleName
            };
            var document = new XDocument(template.GetXmlTree());

            return(document.ToStringFullXmlDeclarationWithReplace());
        }
 public static void AddRole(this IServiceManagement proxy,
                            string subscriptionId,
                            string serviceName,
                            string deploymentName,
                            PersistentVMRole role)
 {
     proxy.EndAddRole(
         proxy.BeginAddRole(subscriptionId,
                            serviceName,
                            deploymentName,
                            role,
                            null,
                            null));
 }
 public static void AddRole(this IServiceManagement proxy,
     string subscriptionId,
     string serviceName,
     string deploymentName,
     PersistentVMRole role)
 {
     proxy.EndAddRole(
         proxy.BeginAddRole(subscriptionId,
         serviceName,
         deploymentName,
         role,
         null,
         null));
 }
Example #5
0
        private void DeleteDataDisks(PersistentVMRole vm, IBlobClient client)
        {
            // delete the data disks in the reverse order
            if (vm.HardDisks.HardDiskCollection == null)
            {
                return;
            }
            for (int i = vm.HardDisks.HardDiskCollection.Count - 1; i >= 0; i--)
            {
                var dataDiskCommand = new DeleteVirtualMachineDiskCommand(vm.HardDisks.HardDiskCollection[i].DiskName)
                {
                    SubscriptionId = SubscriptionId,
                    Certificate    = ManagementCertificate
                };
                dataDiskCommand.Execute();

                int    pos      = vm.HardDisks.HardDiskCollection[i].MediaLink.LastIndexOf('/');
                string diskFile = vm.HardDisks.HardDiskCollection[i].MediaLink.Substring(pos + 1);
                if (client != null)
                {
                    client.DeleteBlob(diskFile);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Deletes the virtual machine that has context with the client
        /// </summary>
        /// <param name="removeDisks">True if the underlying disks in blob storage should be removed</param>
        /// <param name="removeUnderlyingBlobs">Whether or not remove the blob as well as the OS disk</param>
        /// <param name="removeCloudService">Removes the cloud service container</param>
        /// <param name="removeStorageAccount">The storage account that the vhd is in</param>
        public void DeleteVirtualMachine(bool removeDisks = true, bool removeUnderlyingBlobs = true, bool removeCloudService = true, bool removeStorageAccount = true)
        {
            // set this if it hasn't been set yet
            PersistentVMRole vm = null;

            if (_vmRole == null)
            {
                vm = VirtualMachine;
            }

            // create the blob client
            string diskName       = _vmRole.OSHardDisk.DiskName;
            string storageAccount = ParseBlobDetails(_vmRole.OSHardDisk.MediaLink);
            // create the blob client
            IBlobClient blobClient = new BlobClient(Properties.SubscriptionId, StorageContainerName, storageAccount, Properties.Certificate);

            // first delete the virtual machine command
            var deleteVirtualMachine = new DeleteVirtualMachineCommand(Properties)
            {
                SubscriptionId = Properties.SubscriptionId,
                Certificate    = Properties.Certificate
            };

            try
            {
                deleteVirtualMachine.Execute();
            }
            catch (Exception)
            {
                // should be a 400 here if this is the case then there is only a single role in the deployment - quicker to do it this way!
                var deleteVirtualMachineDeployment = new DeleteVirtualMachineDeploymentCommand(Properties)
                {
                    SubscriptionId = Properties.SubscriptionId,
                    Certificate    = Properties.Certificate
                };
                deleteVirtualMachineDeployment.Execute();
            }

            // when this is finished we'll delete the operating system disk - check this as we may need to putin a pause
            // remove the disk association
            DeleteNamedVirtualMachineDisk(diskName);
            // remove the data disks
            DeleteDataDisks(removeDisks ? blobClient : null);
            if (removeDisks)
            {
                // remove the physical disk
                blobClient.DeleteBlob(StorageFileName);
            }
            // remove the cloud services
            if (removeCloudService)
            {
                // delete the cloud service here
                var deleteCloudService = new DeleteHostedServiceCommand(Properties.CloudServiceName)
                {
                    SubscriptionId = Properties.SubscriptionId,
                    Certificate    = Properties.Certificate
                };
                deleteCloudService.Execute();
            }
            // remove the storage account
            if (removeStorageAccount)
            {
                blobClient.DeleteStorageAccount();
            }
        }
Example #7
0
        private PersistentVMRole CreatePersistenVMRole(CloudStorageAccount currentStorage)
        {
            var vm = new PersistentVMRole
            {
                AvailabilitySetName  = AvailabilitySetName,
                ConfigurationSets    = new Collection <ConfigurationSet>(),
                DataVirtualHardDisks = new Collection <DataVirtualHardDisk>(),
                RoleName             = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize             = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType             = "PersistentVMRole",
                Label             = ServiceName,
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    DiskName        = null,
                    SourceImageName = ImageName,
                    MediaLink       = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                    HostCaching     = HostCaching
                }
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated    = DateTime.Now;
                string   vhdname      = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string   blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                {
                    blobEndpoint += "/";
                }
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }


            var netConfig = CreateNetworkConfigurationSet();

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                var windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminUsername = this.AdminUsername,
                    AdminPassword = Password,
                    ComputerName  =
                        string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates    = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = CertUtils.GetCertificateSettings(this.Certificates, this.X509Certificates),
                    WinRM = GetWinRmConfiguration()
                };

                netConfig.InputEndpoints.Add(new InputEndpoint {
                    LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop"
                });
                if (!this.DisableWinRMHttps.IsPresent)
                {
                    netConfig.InputEndpoints.Add(new InputEndpoint {
                        LocalPort = WinRMConstants.HttpsListenerPort, Protocol = "tcp", Name = WinRMConstants.EndpointName
                    });
                }
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                var linuxConfig = new LinuxProvisioningConfigurationSet
                {
                    HostName     = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name,
                    UserName     = this.LinuxUser,
                    UserPassword = this.Password,
                    DisableSshPasswordAuthentication = false
                };

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 ||
                    this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings
                    {
                        PublicKeys = this.SSHPublicKeys,
                        KeyPairs   = this.SSHKeyPairs
                    };
                }

                var rdpEndpoint = new InputEndpoint {
                    LocalPort = 22, Protocol = "tcp", Name = "SSH"
                };
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            return(vm);
        }
Example #8
0
        internal override void ExecuteCommand()
        {
            base.ExecuteCommand();

            SubscriptionData currentSubscription = this.GetCurrentSubscription();

            if (CurrentDeployment == null)
            {
                return;
            }

            // Auto generate disk names based off of default storage account
            foreach (DataVirtualHardDisk datadisk in this.VM.DataVirtualHardDisks)
            {
                if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName))
                {
                    CloudStorageAccount currentStorage = currentSubscription.GetCurrentStorageAccount();
                    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 role = new PersistentVMRole
            {
                AvailabilitySetName  = VM.AvailabilitySetName,
                ConfigurationSets    = VM.ConfigurationSets,
                DataVirtualHardDisks = VM.DataVirtualHardDisks,
                Label             = VM.Label,
                OSVirtualHardDisk = VM.OSVirtualHardDisk,
                RoleName          = VM.RoleName,
                RoleSize          = VM.RoleSize,
                RoleType          = VM.RoleType
            };

            ExecuteClientActionInOCS(role, CommandRuntime.ToString(), s => this.Channel.UpdateRole(s, this.ServiceName, CurrentDeployment.Name, this.Name, role));
        }
        public void NewAzureVMProcess()
        {
            SubscriptionData currentSubscription = this.GetCurrentSubscription();
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCurrentStorageAccount(Channel);
            }
            catch (EndpointNotFoundException) // couldn't access
            {
                throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }

            var vm = new PersistentVMRole
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType = "PersistentVMRole",
                Label = ServiceManagementHelper.EncodeToBase64String(ServiceName)
            };

            vm.OSVirtualHardDisk = new OSVirtualHardDisk()
            {
                DiskName = null,
                SourceImageName = ImageName,
                MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                HostCaching = HostCaching
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated = DateTime.Now;
                string vhdname = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                    blobEndpoint += "/";
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }

            NetworkConfigurationSet netConfig = new NetworkConfigurationSet();
            netConfig.InputEndpoints = new Collection<InputEndpoint>();
            if (SubnetNames != null)
            {
                netConfig.SubnetNames = new SubnetNamesCollection();
                foreach (string subnet in SubnetNames)
                {
                    netConfig.SubnetNames.Add(subnet);
                }
            }

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                WindowsProvisioningConfigurationSet windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminPassword = Password,
                    ComputerName = string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = Certificates
                };

                InputEndpoint rdpEndpoint = new InputEndpoint { LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop" };

                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                LinuxProvisioningConfigurationSet linuxConfig = new LinuxProvisioningConfigurationSet();
                linuxConfig.HostName = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name;
                linuxConfig.UserName = this.LinuxUser;
                linuxConfig.UserPassword = this.Password;
                linuxConfig.DisableSshPasswordAuthentication = false;

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings();
                    linuxConfig.SSH.PublicKeys = this.SSHPublicKeys;
                    linuxConfig.SSH.KeyPairs = this.SSHKeyPairs;
                }

                InputEndpoint rdpEndpoint = new InputEndpoint();
                rdpEndpoint.LocalPort = 22;
                rdpEndpoint.Protocol = "tcp";
                rdpEndpoint.Name = "SSH";
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            string CreateCloudServiceOperationID = String.Empty;
            string CreateDeploymentOperationID = String.Empty;
            List<String> CreateVMOperationIDs = new List<String>();
            Operation lastOperation = null;

            bool ServiceExists = DoesCloudServiceExist(this.ServiceName);

            if (string.IsNullOrEmpty(this.Location) == false || string.IsNullOrEmpty(AffinityGroup) == false || (!String.IsNullOrEmpty(VNetName) && ServiceExists == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        //Implicitly created hosted service2012-05-07 23:12

                        // Create the Cloud Service when
                        // Location or Affinity Group is Specified
                        // or VNET is specified and the service doesn't exist
                        var chsi = new CreateHostedServiceInput
                        {
                            AffinityGroup = this.AffinityGroup,
                            Location = this.Location,
                            ServiceName = this.ServiceName,
                            Description = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                            Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName)
                        };

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.ServiceName,
                            Label = this.ServiceName,
                            RoleList = new RoleList(new List<Role> { vm }),
                            VirtualNetworkName = this.VNetName

                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings();
                            deployment.Dns.DnsServers = new DnsServerList();
                            foreach (DnsServer dns in this.DnsSettings)
                                deployment.Dns.DnsServers.Add(dns);
                        }

                        ExecuteClientAction(deployment, CommandRuntime + " - Create Deployment with VM " + vm.RoleName, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        if (ex is EndpointNotFoundException)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    _createdDeployment = true;
                }
            }
            else
            {
                if (VNetName != null || DnsSettings != null)
                {
                    WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // Only create the VM when a new VM was added and it was not created during the deployment phase.
            if ((_createdDeployment == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        ExecuteClientAction(vm, CommandRuntime + " - Create VM " + vm.RoleName, s => this.Channel.AddRole(s, this.ServiceName, this.ServiceName, vm), WaitForOperation);
                    }
                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
        }
Example #10
0
        internal override void ExecuteCommand()
        {
            base.ExecuteCommand();

            SubscriptionData currentSubscription = this.GetCurrentSubscription();
            if (CurrentDeployment == null)
            {
                return;
            }

            // Auto generate disk names based off of default storage account
            foreach (DataVirtualHardDisk datadisk in this.VM.DataVirtualHardDisks)
            {
                if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName))
                {
                    CloudStorageAccount currentStorage = currentSubscription.GetCurrentStorageAccount();
                    if (currentStorage == null)
                    {
                        throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
                    }

                    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 role = new PersistentVMRole
            {
                AvailabilitySetName = VM.AvailabilitySetName,
                ConfigurationSets = VM.ConfigurationSets,
                DataVirtualHardDisks = VM.DataVirtualHardDisks,
                Label = VM.Label,
                OSVirtualHardDisk = VM.OSVirtualHardDisk,
                RoleName = VM.RoleName,
                RoleSize = VM.RoleSize,
                RoleType = VM.RoleType
            };

            ExecuteClientActionInOCS(role, CommandRuntime.ToString(), s => this.Channel.UpdateRole(s, this.ServiceName, CurrentDeployment.Name, this.Name, role));
        }
        private PersistentVMRole CreatePersistenVMRole(CloudStorageAccount currentStorage)
        {
            var vm = new PersistentVMRole
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType = "PersistentVMRole",
                Label = ServiceName,
                OSVirtualHardDisk = new OSVirtualHardDisk
                {
                    DiskName = null,
                    SourceImageName = ImageName,
                    MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                    HostCaching = HostCaching
                }
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated = DateTime.Now;
                string vhdname = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                    blobEndpoint += "/";
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }

            var netConfig = CreateNetworkConfigurationSet();

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                var windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminUsername = this.AdminUsername,
                    AdminPassword = Password,
                    ComputerName =
                        string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = CertUtils.GetCertificateSettings(this.Certificates, this.X509Certificates),
                    WinRM = GetWinRmConfiguration()
                };

                netConfig.InputEndpoints.Add(new InputEndpoint {LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop"});
                if(!this.DisableWinRMHttps.IsPresent)
                {
                    netConfig.InputEndpoints.Add(new InputEndpoint { LocalPort = WinRMConstants.HttpsListenerPort, Protocol = "tcp", Name = WinRMConstants.EndpointName });
                }
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                var linuxConfig = new LinuxProvisioningConfigurationSet
                {
                    HostName = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name,
                    UserName = this.LinuxUser,
                    UserPassword = this.Password,
                    DisableSshPasswordAuthentication = false
                };

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 ||
                    this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings
                    {
                        PublicKeys = this.SSHPublicKeys,
                        KeyPairs = this.SSHKeyPairs
                    };
                }

                var rdpEndpoint = new InputEndpoint {LocalPort = 22, Protocol = "tcp", Name = "SSH"};
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            return vm;
        }
Example #12
0
        public IEnumerable <PersistentVMRoleContext> GetVirtualMachineProcess()
        {
            RoleList roleList;

            GetAzureVMCommand.GetAzureVMCommand   variable = null;
            IEnumerable <PersistentVMRoleContext> persistentVMRoleContexts;
            Func <Role, bool> func = null;

            if (string.IsNullOrEmpty(this.ServiceName) || base.CurrentDeployment != null)
            {
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        List <PersistentVMRoleContext> persistentVMRoleContexts1 = new List <PersistentVMRoleContext>();
                        if (!string.IsNullOrEmpty(this.ServiceName))
                        {
                            if (!string.IsNullOrEmpty(this.Name))
                            {
                                RoleList roleList1 = base.CurrentDeployment.RoleList;
                                if (func == null)
                                {
                                    func = (Role r) => r.RoleName.Equals(this.Name, StringComparison.InvariantCultureIgnoreCase);
                                }
                                roleList = new RoleList(roleList1.Where <Role>(func));
                            }
                            else
                            {
                                roleList = base.CurrentDeployment.RoleList;
                            }
                            for (int i = 0; i < roleList.Count; i++)
                            {
                                string empty = string.Empty;
                                try
                                {
                                    empty = roleList[i].RoleName;
                                    PersistentVMRole        item = (PersistentVMRole)roleList[i];
                                    PersistentVMRoleContext persistentVMRoleContext = new PersistentVMRoleContext();
                                    if (base.CurrentDeployment != null)
                                    {
                                        persistentVMRoleContext.DNSName = base.CurrentDeployment.Url.AbsoluteUri;
                                    }
                                    persistentVMRoleContext.ServiceName            = this.ServiceName;
                                    persistentVMRoleContext.Name                   = item.RoleName;
                                    persistentVMRoleContext.DeploymentName         = base.CurrentDeployment.Name;
                                    persistentVMRoleContext.VM                     = new PersistentVM();
                                    persistentVMRoleContext.VM.AvailabilitySetName = item.AvailabilitySetName;
                                    persistentVMRoleContext.AvailabilitySetName    = item.AvailabilitySetName;
                                    persistentVMRoleContext.Label                  = item.Label;
                                    persistentVMRoleContext.VM.ConfigurationSets   = item.ConfigurationSets;
                                    persistentVMRoleContext.VM.ConfigurationSets.OfType <NetworkConfigurationSet>().SingleOrDefault <NetworkConfigurationSet>();
                                    persistentVMRoleContext.VM.DataVirtualHardDisks = item.DataVirtualHardDisks;
                                    persistentVMRoleContext.VM.Label             = item.Label;
                                    persistentVMRoleContext.VM.OSVirtualHardDisk = item.OSVirtualHardDisk;
                                    persistentVMRoleContext.VM.RoleName          = item.RoleName;
                                    persistentVMRoleContext.Name                 = item.RoleName;
                                    persistentVMRoleContext.VM.RoleSize          = item.RoleSize;
                                    persistentVMRoleContext.InstanceSize         = item.RoleSize;
                                    persistentVMRoleContext.VM.RoleType          = item.RoleType;
                                    persistentVMRoleContext.InstanceStatus       = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceStatus;
                                    persistentVMRoleContext.IpAddress            = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == this.vm.RoleName).First <RoleInstance>().IpAddress;
                                    persistentVMRoleContext.InstanceStateDetails = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceStateDetails;
                                    persistentVMRoleContext.PowerState           = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().PowerState;
                                    persistentVMRoleContext.InstanceErrorCode    = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceErrorCode;
                                    persistentVMRoleContext.InstanceName         = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceName;
                                    int?instanceFaultDomain = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceFaultDomain;
                                    int value = instanceFaultDomain.Value;
                                    persistentVMRoleContext.InstanceFaultDomain = value.ToString();
                                    int?instanceUpgradeDomain = base.CurrentDeployment.RoleInstanceList.Where <RoleInstance>((RoleInstance r) => r.RoleName == item.RoleName).First <RoleInstance>().InstanceUpgradeDomain;
                                    int num = instanceUpgradeDomain.Value;
                                    persistentVMRoleContext.InstanceUpgradeDomain = num.ToString();
                                    persistentVMRoleContext.set_OperationDescription(base.CommandRuntime.ToString());
                                    persistentVMRoleContext.set_OperationId(base.GetDeploymentOperation.OperationTrackingId);
                                    persistentVMRoleContext.set_OperationStatus(base.GetDeploymentOperation.Status);
                                    persistentVMRoleContexts1.Add(persistentVMRoleContext);
                                }
                                catch (Exception exception)
                                {
                                    base.WriteObject(string.Format("Could not read properties for virtual machine: {0}. It may still be provisioning.", empty));
                                }
                            }
                            if (!string.IsNullOrEmpty(this.Name) && persistentVMRoleContexts1 != null && persistentVMRoleContexts1.Count > 0)
                            {
                                this.SaveRoleState(persistentVMRoleContexts1[0].VM);
                            }
                            persistentVMRoleContexts = persistentVMRoleContexts1;
                            return(persistentVMRoleContexts);
                        }
                        else
                        {
                            this.ListAllVMs();
                            persistentVMRoleContexts = null;
                            return(persistentVMRoleContexts);
                        }
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        if (communicationException as EndpointNotFoundException == null || base.IsVerbose())
                        {
                            this.WriteErrorDetails(communicationException);
                        }
                        else
                        {
                            persistentVMRoleContexts = null;
                            return(persistentVMRoleContexts);
                        }
                    }
                    persistentVMRoleContexts = null;
                }
                return(persistentVMRoleContexts);
            }
            else
            {
                return(null);
            }
        }
Example #13
0
        public void NewAzureVMProcess()
        {
            NewAzureVMCommand.NewAzureVMCommand variable = null;
            int num;
            List <PersistentVMRole> persistentVMRoles  = new List <PersistentVMRole>();
            NewAzureVMCommand       persistentVMRoles1 = this;
            var persistentVMs = new List <PersistentVMRole>();
            SubscriptionData currentSubscription = CmdletSubscriptionExtensions.GetCurrentSubscription(this);

            PersistentVM[] vMs = this.VMs;
            for (int i = 0; i < (int)vMs.Length; i++)
            {
                PersistentVM uri = vMs[i];
                if (uri.OSVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(uri.OSVirtualHardDisk.DiskName))
                {
                    CloudStorageAccount currentStorageAccount = null;
                    try
                    {
                        currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
                    }
                    catch (EndpointNotFoundException endpointNotFoundException)
                    {
                        throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
                    }
                    if (currentStorageAccount != null)
                    {
                        DateTime now      = DateTime.Now;
                        string   roleName = uri.RoleName;
                        if (uri.OSVirtualHardDisk.DiskLabel != null)
                        {
                            roleName = string.Concat(roleName, "-", uri.OSVirtualHardDisk.DiskLabel);
                        }
                        object[] serviceName = new object[6];
                        serviceName[0] = this.ServiceName;
                        serviceName[1] = roleName;
                        serviceName[2] = now.Year;
                        serviceName[3] = now.Month;
                        serviceName[4] = now.Day;
                        serviceName[5] = now.Millisecond;
                        string str         = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", serviceName);
                        string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri;
                        if (!absoluteUri.EndsWith("/"))
                        {
                            absoluteUri = string.Concat(absoluteUri, "/");
                        }
                        uri.OSVirtualHardDisk.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str));
                    }
                    else
                    {
                        throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storage account to set it.");
                    }
                }
                foreach (DataVirtualHardDisk dataVirtualHardDisk in uri.DataVirtualHardDisks)
                {
                    if (dataVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(dataVirtualHardDisk.DiskName))
                    {
                        CloudStorageAccount cloudStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
                        if (cloudStorageAccount != null)
                        {
                            DateTime dateTime  = DateTime.Now;
                            string   roleName1 = uri.RoleName;
                            if (dataVirtualHardDisk.DiskLabel != null)
                            {
                                roleName1 = string.Concat(roleName1, "-", dataVirtualHardDisk.DiskLabel);
                            }
                            object[] year = new object[6];
                            year[0] = this.ServiceName;
                            year[1] = roleName1;
                            year[2] = dateTime.Year;
                            year[3] = dateTime.Month;
                            year[4] = dateTime.Day;
                            year[5] = dateTime.Millisecond;
                            string str1         = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", year);
                            string absoluteUri1 = cloudStorageAccount.BlobEndpoint.AbsoluteUri;
                            if (!absoluteUri1.EndsWith("/"))
                            {
                                absoluteUri1 = string.Concat(absoluteUri1, "/");
                            }
                            dataVirtualHardDisk.MediaLink = new Uri(string.Concat(absoluteUri1, "vhds/", str1));
                        }
                        else
                        {
                            throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
                        }
                    }
                    if (uri.DataVirtualHardDisks.Count <DataVirtualHardDisk>() <= 1)
                    {
                        continue;
                    }
                    Thread.Sleep(1);
                }
                PersistentVMRole persistentVMRole = new PersistentVMRole();
                persistentVMRole.AvailabilitySetName  = uri.AvailabilitySetName;
                persistentVMRole.ConfigurationSets    = uri.ConfigurationSets;
                persistentVMRole.DataVirtualHardDisks = uri.DataVirtualHardDisks;
                persistentVMRole.OSVirtualHardDisk    = uri.OSVirtualHardDisk;
                persistentVMRole.RoleName             = uri.RoleName;
                persistentVMRole.RoleSize             = uri.RoleSize;
                persistentVMRole.RoleType             = uri.RoleType;
                persistentVMRole.Label = uri.Label;
                PersistentVMRole persistentVMRole1 = persistentVMRole;
                persistentVMRoles1.persistentVMs.Add(persistentVMRole1);
            }
            new List <string>();
            Operation operation = null;

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    if (base.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
                    {
                        CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput();
                        createHostedServiceInput.AffinityGroup = this.AffinityGroup;
                        createHostedServiceInput.Location      = this.Location;
                        createHostedServiceInput.ServiceName   = this.ServiceName;
                        if (this.ServiceDescription != null)
                        {
                            createHostedServiceInput.Description = this.ServiceDescription;
                        }
                        else
                        {
                            DateTime now1          = DateTime.Now;
                            DateTime universalTime = now1.ToUniversalTime();
                            string   str2          = string.Format("Implicitly created hosted service{0}", universalTime.ToString("yyyy-MM-dd HH:mm"));
                            createHostedServiceInput.Description = str2;
                        }
                        if (this.ServiceLabel != null)
                        {
                            createHostedServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceLabel);
                        }
                        else
                        {
                            createHostedServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                        }
                        CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput);
                        base.RetryCall((string s) => base.Channel.CreateHostedService(s, createHostedServiceInput));
                        Operation operation1 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                        ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                        managementOperationContext.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                        managementOperationContext.set_OperationId(operation1.OperationTrackingId);
                        managementOperationContext.set_OperationStatus(operation1.Status);
                        ManagementOperationContext managementOperationContext1 = managementOperationContext;
                        base.WriteObject(managementOperationContext1, true);
                    }
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    this.WriteErrorDetails(communicationException);
                    return;
                }
            }
            if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
            {
                if (base.CurrentDeployment != null)
                {
                    if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                    {
                        base.WriteWarning("VNetName, DnsSettings, DeploymentLabel or DeploymentName Name can only be specified on new deployments.");
                    }
                }
                else
                {
                    using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel))
                    {
                        try
                        {
                            if (string.IsNullOrEmpty(this.DeploymentName))
                            {
                                this.DeploymentName = this.ServiceName;
                            }
                            if (string.IsNullOrEmpty(this.DeploymentLabel))
                            {
                                this.DeploymentLabel = this.ServiceName;
                            }
                            Deployment deployment = new Deployment();
                            deployment.DeploymentSlot = "Production";
                            deployment.Name           = this.DeploymentName;
                            deployment.Label          = this.DeploymentLabel;
                            List <Role> roles = new List <Role>();
                            roles.Add(persistentVMRoles1.persistentVMs[0]);
                            deployment.RoleList           = new RoleList(roles);
                            deployment.VirtualNetworkName = this.VNetName;
                            Deployment dnsSetting = deployment;
                            if (this.DnsSettings != null)
                            {
                                dnsSetting.Dns            = new DnsSettings();
                                dnsSetting.Dns.DnsServers = new DnsServerList();
                                DnsServer[] dnsSettings = this.DnsSettings;
                                for (int j = 0; j < (int)dnsSettings.Length; j++)
                                {
                                    DnsServer dnsServer = dnsSettings[j];
                                    dnsSetting.Dns.DnsServers.Add(dnsServer);
                                }
                            }
                            CmdletExtensions.WriteVerboseOutputForObject(this, dnsSetting);
                            base.RetryCall((string s) => base.Channel.CreateDeployment(s, this.ServiceName, dnsSetting));
                            Operation operation2 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", persistentVMRoles1.persistentVMs[0].RoleName));
                            ManagementOperationContext managementOperationContext2 = new ManagementOperationContext();
                            managementOperationContext2.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", persistentVMRoles1.persistentVMs[0].RoleName));
                            managementOperationContext2.set_OperationId(operation2.OperationTrackingId);
                            managementOperationContext2.set_OperationStatus(operation2.Status);
                            ManagementOperationContext managementOperationContext3 = managementOperationContext2;
                            base.WriteObject(managementOperationContext3, true);
                        }
                        catch (CommunicationException communicationException3)
                        {
                            CommunicationException communicationException2 = communicationException3;
                            if (communicationException2 as EndpointNotFoundException == null)
                            {
                                this.WriteErrorDetails(communicationException2);
                                return;
                            }
                            else
                            {
                                throw new Exception("Cloud Service does not exist. Specify -Location or -AffinityGroup to create one.");
                            }
                        }
                        this.createdDeployment = true;
                    }
                }
                if (!this.createdDeployment && base.CurrentDeployment != null)
                {
                    this.DeploymentName = base.CurrentDeployment.Name;
                }
                if (this.createdDeployment)
                {
                    num = 1;
                }
                else
                {
                    num = 0;
                }
                int             num1   = num;
                Action <string> action = null;
                while (num1 < persistentVMRoles1.persistentVMs.Count)
                {
                    if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        using (OperationContextScope operationContextScope2 = new OperationContextScope((IContextChannel)base.Channel))
                        {
                            try
                            {
                                CmdletExtensions.WriteVerboseOutputForObject(this, persistentVMRoles1.persistentVMs[num1]);
                                NewAzureVMCommand newAzureVMCommand = this;
                                if (action == null)
                                {
                                    action = (string s) => base.Channel.AddRole(s, this.ServiceName, this.DeploymentName, persistentVMRoles[num1]);
                                }
                                ((CmdletBase <IServiceManagement>)newAzureVMCommand).RetryCall(action);
                                Operation operation3 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", persistentVMRoles1.persistentVMs[num1].RoleName));
                                ManagementOperationContext managementOperationContext4 = new ManagementOperationContext();
                                managementOperationContext4.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", persistentVMRoles1.persistentVMs[num1].RoleName));
                                managementOperationContext4.set_OperationId(operation3.OperationTrackingId);
                                managementOperationContext4.set_OperationStatus(operation3.Status);
                                ManagementOperationContext managementOperationContext5 = managementOperationContext4;
                                base.WriteObject(managementOperationContext5, true);
                            }
                            catch (CommunicationException communicationException5)
                            {
                                CommunicationException communicationException4 = communicationException5;
                                this.WriteErrorDetails(communicationException4);
                                return;
                            }
                        }
                        NewAzureVMCommand.NewAzureVMCommand variable1 = variable;
                        variable1.i = variable1.i + 1;
                    }
                    else
                    {
                        return;
                    }
                }
                return;
            }
        }
Example #14
0
        public void NewAzureVMProcess()
        {
            List<PersistentVMRole> persistentVMs = new List<PersistentVMRole>();
            SubscriptionData currentSubscription = this.GetCurrentSubscription();

            foreach (PersistentVM pVM in this.VMs)
            {
                if (pVM.OSVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(pVM.OSVirtualHardDisk.DiskName))
                {
                    CloudStorageAccount currentStorage = null;
                    try
                    {
                        currentStorage = CloudStorageAccountFactory.GetCurrentCloudStorageAccount(Channel, currentSubscription);
                    }
                    catch (ServiceManagementClientException) // couldn't access
                    {
                        throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
                    }
                    if (currentStorage == null) // not set
                    {
                        throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storage account to set it.");
                    }

                    DateTime dateTimeCreated = DateTime.Now;
                    string diskPartName = pVM.RoleName;

                    if (pVM.OSVirtualHardDisk.DiskLabel != null)
                    {
                        diskPartName += "-" + pVM.OSVirtualHardDisk.DiskLabel;
                    }

                    string vhdname = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, diskPartName, dateTimeCreated.Year, dateTimeCreated.Month, dateTimeCreated.Day, dateTimeCreated.Millisecond);
                    string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                    if (blobEndpoint.EndsWith("/") == false)
                    {
                        blobEndpoint += "/";
                    }

                    pVM.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
                }

                foreach (DataVirtualHardDisk datadisk in pVM.DataVirtualHardDisks)
                {
                    if (datadisk.MediaLink == null && string.IsNullOrEmpty(datadisk.DiskName))
                    {
                        CloudStorageAccount currentStorage = CloudStorageAccountFactory.GetCurrentCloudStorageAccount(Channel, currentSubscription);
                        if (currentStorage == null)
                        {
                            throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
                        }

                        DateTime dateTimeCreated = DateTime.Now;
                        string diskPartName = pVM.RoleName;

                        if (datadisk.DiskLabel != null)
                        {
                            diskPartName += "-" + datadisk.DiskLabel;
                        }

                        string vhdname = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.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 (pVM.DataVirtualHardDisks.Count() > 1)
                    {
                        // To avoid duplicate disk names
                        System.Threading.Thread.Sleep(1);
                    }
                }

                var vmRole = new PersistentVMRole
                {
                    AvailabilitySetName = pVM.AvailabilitySetName,
                    ConfigurationSets = pVM.ConfigurationSets,
                    DataVirtualHardDisks = pVM.DataVirtualHardDisks,
                    OSVirtualHardDisk = pVM.OSVirtualHardDisk,
                    RoleName = pVM.RoleName,
                    RoleSize = pVM.RoleSize,
                    RoleType = pVM.RoleType,
                    Label = pVM.Label
                };

                persistentVMs.Add(vmRole);
            }

            Operation lastOperation = null;

            using (new OperationContextScope(Channel.ToContextChannel()))
            {
                try
                {
                    if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase) == true)
                    {
                        CreateHostedServiceInput chsi = new CreateHostedServiceInput();
                        chsi.AffinityGroup = this.AffinityGroup;
                        chsi.Location = this.Location;
                        chsi.ServiceName = this.ServiceName;

                        if (this.ServiceDescription == null)
                        {
                            DateTime dtUTC = DateTime.Now.ToUniversalTime();
                            //Implicitly created hosted service2012-05-07 23:12
                            string serviceDesc = String.Format("Implicitly created hosted service{0}", dtUTC.ToString("yyyy-MM-dd HH:mm"));
                            chsi.Description = serviceDesc;
                        }
                        else
                        {
                            chsi.Description = this.ServiceDescription;
                        }

                        if (this.ServiceLabel == null)
                        {
                            chsi.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                        }
                        else
                        {
                            chsi.Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceLabel);
                        }

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi), WaitForOperation);
                    }
                }
                catch (ServiceManagementClientException ex)
                {
                    this.WriteErrorDetails(ex);
                    return;
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return;
            }

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        if (string.IsNullOrEmpty(this.DeploymentName))
                        {
                            this.DeploymentName = this.ServiceName;
                        }

                        if (string.IsNullOrEmpty(this.DeploymentLabel))
                        {
                            this.DeploymentLabel = this.ServiceName;
                        }

                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.DeploymentName,
                            Label = this.DeploymentLabel,
                            RoleList = new RoleList(new List<Role> { persistentVMs[0] }),
                            VirtualNetworkName = this.VNetName
                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings();
                            deployment.Dns.DnsServers = new DnsServerList();
                            foreach (DnsServer dns in this.DnsSettings)
                            {
                                deployment.Dns.DnsServers.Add(dns);
                            }
                        }

                        ExecuteClientAction(deployment, CommandRuntime.ToString() + " - Create Deployment with VM " + persistentVMs[0].RoleName, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment), WaitForOperation);
                    }
                    catch (ServiceManagementClientException ex)
                    {
                        if (ex.HttpStatus == HttpStatusCode.NotFound)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -AffinityGroup to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    this.createdDeployment = true;
                }
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning("VNetName, DnsSettings, DeploymentLabel or DeploymentName Name can only be specified on new deployments.");
                }
            }

            if (this.createdDeployment == false && CurrentDeployment != null)
            {
                this.DeploymentName = CurrentDeployment.Name;
            }

            int startingVM = (this.createdDeployment == true) ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return;
                }

                ExecuteClientActionInOCS(persistentVMs[i],
                    CommandRuntime.ToString() + " - Create VM " + persistentVMs[i].RoleName,
                    s => this.Channel.AddRole(s, this.ServiceName, this.DeploymentName, persistentVMs[i]),
                    WaitForOperation);
            }
        }
Example #15
0
        public void NewAzureVMProcess()
        {
            NewQuickVM.NewQuickVM variable = null;
            string              serviceName;
            string              instanceSize;
            Uri                 uri;
            string              name;
            string              str;
            Action <string>     action = null;
            SubscriptionData    currentSubscription   = CmdletSubscriptionExtensions.GetCurrentSubscription(this);
            CloudStorageAccount currentStorageAccount = null;

            try
            {
                currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
            }
            catch (EndpointNotFoundException endpointNotFoundException)
            {
                throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
            }
            if (currentStorageAccount != null)
            {
                NewQuickVM.NewQuickVM variable1        = variable;
                PersistentVMRole      persistentVMRole = new PersistentVMRole();
                persistentVMRole.AvailabilitySetName  = this.AvailabilitySetName;
                persistentVMRole.ConfigurationSets    = new Collection <ConfigurationSet>();
                persistentVMRole.DataVirtualHardDisks = new Collection <DataVirtualHardDisk>();
                PersistentVMRole persistentVMRole1 = persistentVMRole;
                if (string.IsNullOrEmpty(this.Name))
                {
                    serviceName = this.ServiceName;
                }
                else
                {
                    serviceName = this.Name;
                }
                persistentVMRole1.RoleName = serviceName;
                PersistentVMRole persistentVMRole2 = persistentVMRole;
                if (string.IsNullOrEmpty(this.InstanceSize))
                {
                    instanceSize = null;
                }
                else
                {
                    instanceSize = this.InstanceSize;
                }
                persistentVMRole2.RoleSize = instanceSize;
                persistentVMRole.RoleType  = "PersistentVMRole";
                persistentVMRole.Label     = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                variable1.vm = persistentVMRole;
                PersistentVMRole  persistentVMRole3 = uri1;
                OSVirtualHardDisk oSVirtualHardDisk = new OSVirtualHardDisk();
                oSVirtualHardDisk.DiskName        = null;
                oSVirtualHardDisk.SourceImageName = this.ImageName;
                OSVirtualHardDisk oSVirtualHardDisk1 = oSVirtualHardDisk;
                if (string.IsNullOrEmpty(this.MediaLocation))
                {
                    uri = null;
                }
                else
                {
                    uri = new Uri(this.MediaLocation);
                }
                oSVirtualHardDisk1.MediaLink        = uri;
                oSVirtualHardDisk.HostCaching       = this.HostCaching;
                persistentVMRole3.OSVirtualHardDisk = oSVirtualHardDisk;
                if (oSVirtualHardDisk1.MediaLink == null && string.IsNullOrEmpty(oSVirtualHardDisk1.DiskName))
                {
                    DateTime now      = DateTime.Now;
                    object[] roleName = new object[6];
                    roleName[0] = this.ServiceName;
                    roleName[1] = uri1.RoleName;
                    roleName[2] = now.Year;
                    roleName[3] = now.Month;
                    roleName[4] = now.Day;
                    roleName[5] = now.Millisecond;
                    string str1        = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", roleName);
                    string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri;
                    if (!absoluteUri.EndsWith("/"))
                    {
                        absoluteUri = string.Concat(absoluteUri, "/");
                    }
                    oSVirtualHardDisk1.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str1));
                }
                NetworkConfigurationSet networkConfigurationSet = new NetworkConfigurationSet();
                networkConfigurationSet.InputEndpoints = new Collection <InputEndpoint>();
                if (this.SubnetNames != null)
                {
                    networkConfigurationSet.SubnetNames = new SubnetNamesCollection();
                    string[] subnetNames = this.SubnetNames;
                    for (int i = 0; i < (int)subnetNames.Length; i++)
                    {
                        string str2 = subnetNames[i];
                        networkConfigurationSet.SubnetNames.Add(str2);
                    }
                }
                if (!base.ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
                {
                    LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet  = new LinuxProvisioningConfigurationSet();
                    LinuxProvisioningConfigurationSet linuxProvisioningConfigurationSet1 = linuxProvisioningConfigurationSet;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        name = this.ServiceName;
                    }
                    else
                    {
                        name = this.Name;
                    }
                    linuxProvisioningConfigurationSet1.HostName    = name;
                    linuxProvisioningConfigurationSet.UserName     = this.LinuxUser;
                    linuxProvisioningConfigurationSet.UserPassword = this.Password;
                    linuxProvisioningConfigurationSet.DisableSshPasswordAuthentication = new bool?(false);
                    if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                    {
                        linuxProvisioningConfigurationSet.SSH            = new LinuxProvisioningConfigurationSet.SSHSettings();
                        linuxProvisioningConfigurationSet.SSH.PublicKeys = this.SSHPublicKeys;
                        linuxProvisioningConfigurationSet.SSH.KeyPairs   = this.SSHKeyPairs;
                    }
                    InputEndpoint inputEndpoint = new InputEndpoint();
                    inputEndpoint.LocalPort = 22;
                    inputEndpoint.Protocol  = "tcp";
                    inputEndpoint.Name      = "SSH";
                    networkConfigurationSet.InputEndpoints.Add(inputEndpoint);
                    uri1.ConfigurationSets.Add(linuxProvisioningConfigurationSet);
                    uri1.ConfigurationSets.Add(networkConfigurationSet);
                }
                else
                {
                    WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet = new WindowsProvisioningConfigurationSet();
                    windowsProvisioningConfigurationSet.AdminPassword = this.Password;
                    WindowsProvisioningConfigurationSet windowsProvisioningConfigurationSet1 = windowsProvisioningConfigurationSet;
                    if (string.IsNullOrEmpty(this.Name))
                    {
                        str = this.ServiceName;
                    }
                    else
                    {
                        str = this.Name;
                    }
                    windowsProvisioningConfigurationSet1.ComputerName             = str;
                    windowsProvisioningConfigurationSet.EnableAutomaticUpdates    = new bool?(true);
                    windowsProvisioningConfigurationSet.ResetPasswordOnFirstLogon = false;
                    windowsProvisioningConfigurationSet.StoredCertificateSettings = this.Certificates;
                    InputEndpoint inputEndpoint1 = new InputEndpoint();
                    inputEndpoint1.LocalPort = 0xd3d;
                    inputEndpoint1.Protocol  = "tcp";
                    inputEndpoint1.Name      = "RemoteDesktop";
                    networkConfigurationSet.InputEndpoints.Add(inputEndpoint1);
                    uri1.ConfigurationSets.Add(windowsProvisioningConfigurationSet);
                    uri1.ConfigurationSets.Add(networkConfigurationSet);
                }
                new List <string>();
                Operation operation = null;
                bool      flag      = this.DoesCloudServiceExist(this.ServiceName);
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        DateTime dateTime      = DateTime.Now;
                        DateTime universalTime = dateTime.ToUniversalTime();
                        string   str3          = string.Format("Implicitly created hosted service{0}", universalTime.ToString("yyyy-MM-dd HH:mm"));
                        if (!string.IsNullOrEmpty(this.Location) || !string.IsNullOrEmpty(this.AffinityGroup) || !string.IsNullOrEmpty(this.VNetName) && !flag)
                        {
                            CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput();
                            createHostedServiceInput.AffinityGroup = this.AffinityGroup;
                            createHostedServiceInput.Location      = this.Location;
                            createHostedServiceInput.ServiceName   = this.ServiceName;
                            createHostedServiceInput.Description   = str3;
                            createHostedServiceInput.Label         = ServiceManagementHelper.EncodeToBase64String(this.ServiceName);
                            CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput);
                            base.RetryCall((string s) => base.Channel.CreateHostedService(s, createHostedServiceInput));
                            Operation operation1 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                            ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                            managementOperationContext.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Cloud Service"));
                            managementOperationContext.set_OperationId(operation1.OperationTrackingId);
                            managementOperationContext.set_OperationStatus(operation1.Status);
                            ManagementOperationContext managementOperationContext1 = managementOperationContext;
                            base.WriteObject(managementOperationContext1, true);
                        }
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        this.WriteErrorDetails(communicationException);
                        return;
                    }
                }
                if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (base.CurrentDeployment != null)
                    {
                        if (this.VNetName != null || this.DnsSettings != null)
                        {
                            base.WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
                        }
                    }
                    else
                    {
                        using (OperationContextScope operationContextScope1 = new OperationContextScope((IContextChannel)base.Channel))
                        {
                            try
                            {
                                Deployment deployment = new Deployment();
                                deployment.DeploymentSlot = "Production";
                                deployment.Name           = this.ServiceName;
                                deployment.Label          = this.ServiceName;
                                List <Role> roles = new List <Role>();
                                roles.Add(uri1);
                                deployment.RoleList           = new RoleList(roles);
                                deployment.VirtualNetworkName = this.VNetName;
                                Deployment dnsSetting = deployment;
                                if (this.DnsSettings != null)
                                {
                                    dnsSetting.Dns            = new DnsSettings();
                                    dnsSetting.Dns.DnsServers = new DnsServerList();
                                    DnsServer[] dnsSettings = this.DnsSettings;
                                    for (int j = 0; j < (int)dnsSettings.Length; j++)
                                    {
                                        DnsServer dnsServer = dnsSettings[j];
                                        dnsSetting.Dns.DnsServers.Add(dnsServer);
                                    }
                                }
                                CmdletExtensions.WriteVerboseOutputForObject(this, dnsSetting);
                                base.RetryCall((string s) => base.Channel.CreateDeployment(s, this.ServiceName, dnsSetting));
                                Operation operation2 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
                                ManagementOperationContext managementOperationContext2 = new ManagementOperationContext();
                                managementOperationContext2.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create Deployment with VM ", uri1.RoleName));
                                managementOperationContext2.set_OperationId(operation2.OperationTrackingId);
                                managementOperationContext2.set_OperationStatus(operation2.Status);
                                ManagementOperationContext managementOperationContext3 = managementOperationContext2;
                                base.WriteObject(managementOperationContext3, true);
                            }
                            catch (CommunicationException communicationException3)
                            {
                                CommunicationException communicationException2 = communicationException3;
                                if (communicationException2 as EndpointNotFoundException == null)
                                {
                                    this.WriteErrorDetails(communicationException2);
                                    return;
                                }
                                else
                                {
                                    throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
                                }
                            }
                            this.CreatedDeployment = true;
                        }
                    }
                    if (operation == null || string.Compare(operation.Status, "Failed", StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        if (!this.CreatedDeployment)
                        {
                            using (OperationContextScope operationContextScope2 = new OperationContextScope((IContextChannel)base.Channel))
                            {
                                try
                                {
                                    CmdletExtensions.WriteVerboseOutputForObject(this, uri1);
                                    NewQuickVM newQuickVM = this;
                                    if (action == null)
                                    {
                                        action = (string s) => base.Channel.AddRole(s, this.ServiceName, this.ServiceName, uri1);
                                    }
                                    ((CmdletBase <IServiceManagement>)newQuickVM).RetryCall(action);
                                    Operation operation3 = base.WaitForOperation(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
                                    ManagementOperationContext managementOperationContext4 = new ManagementOperationContext();
                                    managementOperationContext4.set_OperationDescription(string.Concat(base.CommandRuntime.ToString(), " - Create VM ", uri1.RoleName));
                                    managementOperationContext4.set_OperationId(operation3.OperationTrackingId);
                                    managementOperationContext4.set_OperationStatus(operation3.Status);
                                    ManagementOperationContext managementOperationContext5 = managementOperationContext4;
                                    base.WriteObject(managementOperationContext5, true);
                                }
                                catch (CommunicationException communicationException5)
                                {
                                    CommunicationException communicationException4 = communicationException5;
                                    this.WriteErrorDetails(communicationException4);
                                    return;
                                }
                            }
                        }
                        return;
                    }
                    else
                    {
                        return;
                    }
                }
                return;
            }
            else
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }
        }
Example #16
0
        public string UpdateVirtualMachineProcess()
        {
            Action <string>  action = null;
            SubscriptionData currentSubscription = CmdletSubscriptionExtensions.GetCurrentSubscription(this);

            if (base.CurrentDeployment != null)
            {
                foreach (DataVirtualHardDisk dataVirtualHardDisk in this.VM.DataVirtualHardDisks)
                {
                    if (dataVirtualHardDisk.MediaLink == null && string.IsNullOrEmpty(dataVirtualHardDisk.DiskName))
                    {
                        CloudStorageAccount currentStorageAccount = currentSubscription.GetCurrentStorageAccount(base.Channel);
                        if (currentStorageAccount != null)
                        {
                            DateTime now      = DateTime.Now;
                            string   roleName = this.VM.RoleName;
                            if (dataVirtualHardDisk.DiskLabel != null)
                            {
                                roleName = string.Concat(roleName, "-", dataVirtualHardDisk.DiskLabel);
                            }
                            object[] serviceName = new object[6];
                            serviceName[0] = this.ServiceName;
                            serviceName[1] = roleName;
                            serviceName[2] = now.Year;
                            serviceName[3] = now.Month;
                            serviceName[4] = now.Day;
                            serviceName[5] = now.Millisecond;
                            string str         = string.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", serviceName);
                            string absoluteUri = currentStorageAccount.BlobEndpoint.AbsoluteUri;
                            if (!absoluteUri.EndsWith("/"))
                            {
                                absoluteUri = string.Concat(absoluteUri, "/");
                            }
                            dataVirtualHardDisk.MediaLink = new Uri(string.Concat(absoluteUri, "vhds/", str));
                        }
                        else
                        {
                            throw new ArgumentException("CurrentStorageAccount is not set or not accessible. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
                        }
                    }
                    if (this.VM.DataVirtualHardDisks.Count <= 1)
                    {
                        continue;
                    }
                    Thread.Sleep(1);
                }
                PersistentVMRole persistentVMRole = new PersistentVMRole();
                persistentVMRole.AvailabilitySetName  = this.VM.AvailabilitySetName;
                persistentVMRole.ConfigurationSets    = this.VM.ConfigurationSets;
                persistentVMRole.DataVirtualHardDisks = this.VM.DataVirtualHardDisks;
                persistentVMRole.Label             = this.VM.Label;
                persistentVMRole.OSVirtualHardDisk = this.VM.OSVirtualHardDisk;
                persistentVMRole.RoleName          = this.VM.RoleName;
                persistentVMRole.RoleSize          = this.VM.RoleSize;
                persistentVMRole.RoleType          = this.VM.RoleType;
                PersistentVMRole persistentVMRole1 = persistentVMRole;
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        CmdletExtensions.WriteVerboseOutputForObject(this, persistentVMRole1);
                        UpdateAzureVMCommand updateAzureVMCommand = this;
                        if (action == null)
                        {
                            action = (string s) => base.Channel.UpdateRole(s, this.ServiceName, this.CurrentDeployment.Name, this.Name, persistentVMRole1);
                        }
                        ((CmdletBase <IServiceManagement>)updateAzureVMCommand).RetryCall(action);
                        Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                        ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                        managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                        managementOperationContext.set_OperationId(operation.OperationTrackingId);
                        managementOperationContext.set_OperationStatus(operation.Status);
                        ManagementOperationContext managementOperationContext1 = managementOperationContext;
                        base.WriteObject(managementOperationContext1, true);
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        this.WriteErrorDetails(communicationException);
                    }
                }
                return(null);
            }
            else
            {
                return(null);
            }
        }