Exemple #1
0
        /// <summary>
        /// After configuring the .cscfg file, this function publishes the package to Azure
        /// </summary>
        public bool PublishServiceToAzure(ReportProgress reportDelegate, ReDoInitializeDB reDoInitializeDB)
        {
            this.reportDelegate = reportDelegate;

            report(10, "Creating a broker object ...");

            AzureManagementBroker broker;

            try
            {
                // Create hostedservice if it does not exist in Azure
                broker = new AzureManagementBroker(_settings.DeploymentName,
                                                   _settings.ManagementCert.Thumbprint,
                                                   new Guid(_settings.SubscriptionId),
                                                   _settings.ServiceName,
                                                   _settings.StorageName,
                                                   _settings.StorageKey,
                                                   null,
                                                   null);

                try
                {
                    broker.CreateHostedServiceIfNotExist(_settings.ServiceName, _settings.Location);
                }
                catch (Exception ex)
                {
                    report(10, "Error: " + ex.Message + ". Please check and try later.");
                    return false;
                }

                report(20, "Adding the certificate to service ...");

                IAsyncAzureOperation opServiceCert = broker.AddCertificateToService(_settings.ServiceCert, Password, CertificateLocation.AzureManagement);
                opServiceCert.WaitForCompletion(TimeSpan.MaxValue);
                if (opServiceCert.GetOperationStatus() == AzureOperationStatus.Failed)
                {
                    report(20, "Error: " + opServiceCert.ErrorMessage());
                    return false;
                }

                /***************************************************************************************
                //**** Create two default firewall filters for the newly-created SQL server
                //1:   0.0.0.0  to 0.0.0.0
                //2.   IP address to IP address
                ***************************************************************************************/
                report(30, "Creating firewall rules ...");

                broker.CreateFirewallRule(_settings.SqlServerName);
                string localIP = broker.CreateFirewallRuleWithIPDetect(_settings.SqlServerName, "FirewallWithIP");
                string[] IPRange = GenerateIPRange(localIP);
                broker.CreateFirewallRule(_settings.SqlServerName, "RangeFireWall", IPRange[0], IPRange[1]);

                // If a user sets InitializeDBOnline = false, then do the initializeDB from local machine
                // or else, create database and InitializeDB at Azure
                if (!_settings.InitializeDBOnline)
                {
                    report(40, "Creating database ...");

                    // Create a new database under the newly-created SQL Server
                    try
                    {
                        List<string> listOfDB = GetExistingDatabases(_settings.SqlServerName, _settings.SqlServerUser, _settings.SqlServerPassword);

                        // If no database named as settings.DBName is found, create one
                        if (listOfDB.IndexOf(_settings.DBName) == -1)
                        {
                            CreateDatabase(_settings.SqlServerName, _settings.DBName, _settings.SqlServerUser, _settings.SqlServerPassword, Maxsize);
                        }
                    }
                    catch (SqlException e)
                    {
                        report(40, "Error from SQL server " + e.Server + ": " + e.Message);
                        return false;
                    }
                    catch (Exception e)
                    {
                        report(40, "Error: " + e.Message);
                        return false;
                    }

                    report(50, "Initializing database ...");

                    if (DoInitializeDB(report, reDoInitializeDB, true) == false)
                    {
                        report(50, "Error: Initializing database failed. Please check AzureSampleService.log for details.");
                        return false;
                    }
                }

                // Start to deploy the service
                AzureDeployment deployment = new AzureDeployment();

                FileInfo localFile;

                // Verify whether CspkgFile exists
                if (File.Exists(CspkgFile))
                {
                    // Upload package file to Azure first
                    localFile = new FileInfo(CspkgFile);
                }
                else
                {
                    report(50, "Error: Please copy the .cspkg file to the current working folder.");
                    return false;
                }

                try
                {
                    report(70, "Copying HPC package to blob storage ...");

                    broker.CopyHpcPackageToBlobStorage(localFile, DestinationName);

                    report(90, "Creating Azure deployment ...");

                    // Start to deploy the service now.
                    IAsyncAzureOperation op = broker.CreateAzureDeployment(File.ReadAllText(_settings.ServiceCscfg), DestinationName, out deployment);
                    op.WaitForCompletion(TimeSpan.MaxValue);
                    if (op.GetOperationStatus() != AzureOperationStatus.Succeeded)
                    {
                        report(90, "Error: " + op.ErrorMessage());
                        return false;
                    }

                    // Delete the service cscfg file
                    File.Delete((_settings.ServiceCscfg));
                }
                catch (Exception ex)
                {
                    report(90, "Error: " + ex.Message);
                    return false;
                }
            }
            catch (Exception exception)
            {
                report(90, "Error: " + exception.Message);
                return false;
            }

            report(100, "Client Portion Complete (Azure deploying now).");
            return true;
        }
        /// <summary>
        /// Starts an azure deployment immediately after it is created
        /// </summary>
        public IAsyncAzureOperation CreateAzureDeployment(string configXml, string packageFileName, out AzureDeployment deployment)
        {
            // Initialize the return deployment struct
            deployment = new AzureDeployment();

            // Start generating an Azure deployment request from this template
            string azureRequest =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
                "<CreateDeployment xmlns=\"http://schemas.microsoft.com/windowsazure\">\r\n" +
                "<Name>{0}</Name>\r\n" +
                "<PackageUrl>{1}</PackageUrl>\r\n" +
                "<Label>{2}</Label>\r\n" +
                "<Configuration>{3}</Configuration>\r\n" +
                "<StartDeployment>true</StartDeployment>\r\n" +
                "</CreateDeployment>";

            // Generate the URL of the HPC runtime package
            string blobUrl = string.Format(
                "https://{0}.{1}/{2}/{3}",
                this.storageServiceName,
                AzureNaming.AzureBlobStorageDomain,
                AzureNaming.GenerateAzureEntityName("HpcRuntime", this.clusterName, this.subscriptionId, this.serviceName),
                packageFileName
            );

            // Generate a name for the deployment
            string deploymentName = AzureNaming.GenerateAzureEntityName("HpcDeployment", this.clusterName, this.subscriptionId, this.serviceName);

            // Generate a label
            string label = string.Format(
                "Deployment for Windows Azure HPC Scheduler: {0}",
                this.clusterName);
            label = Utility.Base64EncodeString(label);
            if (label.Length > 100)
            {
                label = label.Substring(0, 100);
            }

            // Fill in the request template
            azureRequest = string.Format(
                azureRequest,
                deploymentName,
                blobUrl,
                label,
                Utility.Base64EncodeString(configXml)
                );

            // Submit the request
            AzureManagementClient client = new AzureManagementClient(this.certificate, this.subscriptionId);
            AzureManagementResponse response = client.SubmitRequestWithBody(
                RequestType.POST,
                azureRequest,
                "2010-04-01",
                "services/hostedservices/{0}/deploymentslots/production",
                this.serviceName
                );

            // Generate an Async operation to track the deployment
            AsyncAzureOperation op = new AsyncAzureOperation(this, response.OperationId, false);

            // Need to poll Azure to find detailed information about the deployment
            for (; ; )
            {
                // Loop through all deployments looking for the one we created
                foreach (AzureDeployment deploy in this.EnumerateAzureDeployments())
                {
                    // If we find it, return it
                    if (string.Equals(deploy.Name, deploymentName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        deployment = deploy;
                        return op;
                    }
                }

                // Abort polling if the operation has failed
                if (op.GetOperationStatus() == AzureOperationStatus.Failed)
                {
                    break;
                }

                // Wait 2 seconds before polling next
                System.Threading.Thread.Sleep(2 * 1000);
            }

            return op;
        }
        /// <summary>
        /// Enumerates all Azure Deployments for the subscription/service
        /// </summary>
        public IEnumerable<AzureDeployment> EnumerateAzureDeployments()
        {
            // Query Azure for deployments
            AzureManagementClient client = new AzureManagementClient(this.certificate, this.subscriptionId);
            AzureManagementResponse response = client.SubmitRequest(
                RequestType.GET,
                "2010-04-01",
                "services/hostedservices/{0}?embed-detail=true",
                this.serviceName);

            // Create collection to return
            List<AzureDeployment> deployments = new List<AzureDeployment>();

            // If there is no deployment node in the result, return an empty collection
            XmlNode xmlDeployments = response.GetXmlNode("Deployments");
            if (xmlDeployments == null)
            {
                return deployments;
            }

            // Populate our collection of deployments
            foreach (XmlNode xmlDeployment in xmlDeployments.ChildNodes)
            {
                AzureDeployment dep = new AzureDeployment();

                // Get the deployment ID;
                string guidStr = response.GetXmlValue(xmlDeployment, "PrivateID");
                dep.Id = new Guid(guidStr);

                // Get all the other deployment properties
                dep.Name = response.GetXmlValue(xmlDeployment, "Name");
                string status = response.GetXmlValue(xmlDeployment, "Status");
                dep.Status = AzureDeploymentState.Unknown;
                try
                {
                    dep.Status = (AzureDeploymentState)Enum.Parse(typeof(AzureDeploymentState), status, true);
                }
                catch (Exception)
                { }
                dep.Label = response.GetXmlValue(xmlDeployment, "Label");
                dep.Url = response.GetXmlValue(xmlDeployment, "Url");
                dep.Configuration = response.GetXmlValue(xmlDeployment, "Configuration");

                List<string> roles = new List<string>();
                XmlNode roleList = response.GetXmlNode(xmlDeployment, "RoleList");
                if (roleList != null)
                    foreach (XmlNode role in roleList.ChildNodes)
                    {
                        roles.Add(response.GetXmlValue(role, "RoleName"));
                    }

                dep.roles = roles;

                // Add to the collection
                deployments.Add(dep);

            }

            return deployments;
        }
        /// <summary>
        /// Change Azure deployment state between the suspended and running states
        /// </summary>
        public IAsyncAzureOperation ChangeAzureDeploymentState(string deploymentName, out AzureDeployment deployment, AzureDeploymentState state)
        {
            string request =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<UpdateDeploymentStatus xmlns=\"http://schemas.microsoft.com/windowsazure\">" +
                "<Status>{0}</Status>" +
                "</UpdateDeploymentStatus>";

            request = string.Format(request, state.ToString());

            AzureManagementClient client = new AzureManagementClient(this.certificate, this.subscriptionId);
            AzureManagementResponse response = client.SubmitRequestWithBody(
                RequestType.POST,
                request,
                "2009-10-01",
                "services/hostedservices/{0}/deployments/{1}/?comp=status",
                this.serviceName,
                deploymentName
                );

            string operationId = response.OperationId;
            AsyncAzureOperation op = new AsyncAzureOperation(this, operationId, false);
            deployment = this.QueryAzureDeployment(deploymentName);

            return op;
        }