Beispiel #1
0
        /// <summary>
        /// Checks for the existence of a specific Cloud Service, if it doesn't exist it will create it.
        /// </summary>
        /// <param name="client">The <see cref="ComputeManagementClient"/> that is performing the operation.</param>
        /// <param name="parameters">The <see cref="HostedServiceCreateParameters"/> that define the service we want to create.</param>
        /// <returns>The async <see cref="Task"/> wrapper.</returns>
        public static async Task CreateServiceIfNotExistsAsync(this ComputeManagementClient client, HostedServiceCreateParameters parameters)
        {
            Contract.Requires(client != null);
            Contract.Requires(parameters != null);

            HostedServiceGetResponse service = null;

            FlexStreams.BuildEventsObserver.OnNext(new CheckIfExistsEvent(AzureResource.CloudService, parameters.ServiceName));

            try
            {
                service = await client.HostedServices.GetAsync(parameters.ServiceName);
            }
            catch (CloudException cex)
            {
                if (cex.Error.Code != "ResourceNotFound")
                {
                    throw;
                }
            }

            if (service != null)
            {
                FlexStreams.BuildEventsObserver.OnNext(new FoundExistingEvent(AzureResource.CloudService, parameters.ServiceName));
                return;
            }

            await client.HostedServices.CreateAsync(parameters);

            FlexStreams.BuildEventsObserver.OnNext(new ProvisionEvent(AzureResource.CloudService, parameters.ServiceName));
        }
Beispiel #2
0
        public void NewAzureVMProcess()
        {
            AzureSubscription   currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount(Profile);
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }

            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
            {
                var parameter = new HostedServiceCreateParameters
                {
                    AffinityGroup = this.AffinityGroup,
                    Location      = this.Location,
                    ServiceName   = this.ServiceName,
                    Description   = this.ServiceDescription ?? String.Format(
                        "Implicitly created hosted service{0}",
                        DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                    Label          = this.ServiceLabel ?? this.ServiceName,
                    ReverseDnsFqdn = this.ReverseDnsFqdn
                };

                try
                {
                    this.ComputeClient.HostedServices.Create(parameter);
                }
                catch (CloudException ex)
                {
                    if (string.Equals(ex.Error.Code, "ConflictError"))
                    {
                        HostedServiceGetResponse existingService = this.ComputeClient.HostedServices.Get(this.ServiceName);

                        if (existingService == null || existingService.Properties == null)
                        {
                            // The same service name is already used by another subscription.
                            WriteExceptionError(ex);
                            return;
                        }
                        else if ((string.IsNullOrEmpty(existingService.Properties.Location) &&
                                  string.Compare(existingService.Properties.AffinityGroup, this.AffinityGroup, StringComparison.InvariantCultureIgnoreCase) == 0) ||
                                 (string.IsNullOrEmpty(existingService.Properties.AffinityGroup) &&
                                  string.Compare(existingService.Properties.Location, this.Location, StringComparison.InvariantCultureIgnoreCase) == 0))
                        {
                            // The same service name is already created under the same subscription,
                            // and its affinity group or location is matched with the given parameter.
                            this.WriteWarning(ex.Error.Message);
                        }
                        else
                        {
                            // The same service name is already created under the same subscription,
                            // but its affinity group or location is not matched with the given parameter.
                            this.WriteWarning("Location or AffinityGroup name is not matched with the existing service");
                            WriteExceptionError(ex);
                            return;
                        }
                    }
                    else
                    {
                        WriteExceptionError(ex);
                        return;
                    }
                }
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType <Model.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(vm.WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                     select new
                {
                    c.Thumbprint,
                    CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                };

                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select((vm, index) => CreatePersistentVMRole(VMTuples[index], currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.DeploymentName ?? this.ServiceName,
                        Label              = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { persistentVMs[0] },
                        ReservedIPName     = ReservedIPName
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(
                                new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer
                            {
                                Name    = dns.Name,
                                Address = dns.Address
                            });
                        }
                    }

                    if (this.InternalLoadBalancerConfig != null)
                    {
                        parameters.LoadBalancers = new LoadBalancer[1]
                        {
                            new LoadBalancer
                            {
                                Name = this.InternalLoadBalancerConfig.InternalLoadBalancerName,
                                FrontendIPConfiguration = new FrontendIPConfiguration
                                {
                                    Type       = FrontendIPConfigurationType.Private,
                                    SubnetName = this.InternalLoadBalancerConfig.SubnetName,
                                    StaticVirtualNetworkIPAddress = this.InternalLoadBalancerConfig.IPAddress
                                }
                            }
                        };
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if (this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        WriteExceptionError(ex);
                    }

                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

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

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);

                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName         = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk           = VMTuples[i].Item3 ? null : persistentVMs[i].OSVirtualHardDisk,
                    RoleName                    = persistentVMs[i].RoleName,
                    RoleSize                    = persistentVMs[i].RoleSize,
                    ProvisionGuestAgent         = persistentVMs[i].ProvisionGuestAgent,
                    ResourceExtensionReferences = persistentVMs[i].ProvisionGuestAgent != null && persistentVMs[i].ProvisionGuestAgent.Value ? persistentVMs[i].ResourceExtensionReferences : null,
                    VMImageName                 = VMTuples[i].Item3 ? persistentVMs[i].VMImageName : null,
                    MediaLocation               = VMTuples[i].Item3 ? persistentVMs[i].MediaLocation : null
                };

                if (parameter.OSVirtualHardDisk != null)
                {
                    parameter.OSVirtualHardDisk.IOType = null;
                }

                if (persistentVMs[i].DataVirtualHardDisks != null && persistentVMs[i].DataVirtualHardDisks.Any())
                {
                    persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                    parameter.DataVirtualHardDisks.ForEach(d => d.IOType = null);
                }

                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if (this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
        public void NewAzureVMProcess()
        {
            AzureSubscription   currentSubscription = Profile.Context.Subscription;
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount(Profile);
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if (!string.IsNullOrEmpty(this.Location))
            {
                if (serviceExists)
                {
                    HostedServiceGetResponse existingSvc = null;
                    try
                    {
                        existingSvc = ComputeClient.HostedServices.Get(this.ServiceName);
                    }
                    catch
                    {
                        throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                    }

                    if (existingSvc == null ||
                        existingSvc.Properties == null ||
                        !this.Location.Equals(existingSvc.Properties.Location))
                    {
                        throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    HostedServiceGetResponse existingSvc = null;
                    try
                    {
                        existingSvc = ComputeClient.HostedServices.Get(this.ServiceName);
                    }
                    catch
                    {
                        throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                    }

                    if (existingSvc == null ||
                        existingSvc.Properties == null ||
                        !this.AffinityGroup.Equals(existingSvc.Properties.AffinityGroup))
                    {
                        throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.ReverseDnsFqdn))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsReverseDnsFqdnCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                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 parameter = new HostedServiceCreateParameters
                    {
                        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          = this.ServiceName,
                        ReverseDnsFqdn = this.ReverseDnsFqdn
                    };

                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + Resources.QuickVMCreateCloudService,
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
                catch (CloudException ex)
                {
                    WriteExceptionError(ex);
                    return;
                }
            }

            if (ParameterSetName.Equals(WindowsParamSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }

                    var operationDescription = string.Format(Resources.QuickVMUploadingWinRMCertificate, CommandRuntime, WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(WinRMCertificate);

                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                }

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                    {
                        c.Thumbprint,
                        CertificateFile = CertUtilsNewSM.Create(c, this.NoExportPrivateKey.IsPresent)
                    };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionNewSM(
                            null,
                            operationDescription,
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                            (s, r) => ContextFactory <OperationStatusResponse, ManagementOperationContext>(r, s));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            try
            {
                if (CurrentDeploymentNewSM == null)
                {
                    // If the current deployment doesn't exist set it create it
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.ServiceName,
                        Label              = this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { vm },
                        ReservedIPName     = this.ReservedIPName,
                        DnsSettings        = this.DnsSettings == null ? null : new Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings
                        {
                            DnsServers = (from dns in this.DnsSettings
                                          select new Management.Compute.Models.DnsServer
                            {
                                Name = dns.Name,
                                Address = dns.Address
                            }).ToList()
                        }
                    };

                    ExecuteClientActionNewSM(
                        parameters,
                        string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));
                }
                else
                {
                    if (!string.IsNullOrEmpty(VNetName) || DnsSettings != null)
                    {
                        WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                    }

                    // Only create the VM when a new VM was added and it was not created during the deployment phase.
                    ExecuteClientActionNewSM(
                        vm,
                        string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName),
                        () => this.ComputeClient.VirtualMachines.Create(
                            this.ServiceName,
                            this.ServiceName,
                            new VirtualMachineCreateParameters
                    {
                        AvailabilitySetName         = vm.AvailabilitySetName,
                        OSVirtualHardDisk           = vm.OSVirtualHardDisk,
                        DataVirtualHardDisks        = vm.DataVirtualHardDisks,
                        RoleName                    = vm.RoleName,
                        RoleSize                    = vm.RoleSize,
                        VMImageName                 = vm.VMImageName,
                        MediaLocation               = vm.MediaLocation,
                        ProvisionGuestAgent         = vm.ProvisionGuestAgent,
                        ResourceExtensionReferences = vm.ResourceExtensionReferences,
                        ConfigurationSets           = vm.ConfigurationSets
                    }));
                }

                if (WaitForBoot.IsPresent)
                {
                    WaitForRoleToBoot(vm.RoleName);
                }
            }
            catch (CloudException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                }

                WriteExceptionError(ex);
            }
        }