internal async Task <string> StartVirtualMachineAsync(string name)
        {
            string          returnMessage;
            IVirtualMachine machine = await GetVmByNameAsync(name);

            if (machine == null)
            {
                returnMessage = $"No machine named {name} was found";
            }
            else if (machine.PowerState == PowerState.Deallocated || machine.PowerState == PowerState.Stopped)
            {
#pragma warning disable CS4014 //This will take a while, let it run async and continue no need to await it
                machine.StartAsync();
#pragma warning restore CS4014
                returnMessage = $"{name} is starting, original state was {VmHtmlMaker.FormatPowerState(machine.PowerState)}";
            }
            else if (machine.PowerState == PowerState.Running)
            {
                IPublicIPAddress ipAddress = machine.GetPrimaryPublicIPAddress();
                returnMessage = $"Machine is already running, IP address is {ipAddress.IPAddress}";
            }
            else
            {
                returnMessage = $"No action taken, machine state is: {VmHtmlMaker.FormatPowerState(machine.PowerState)}";
            }

            //_helper.LogMessage("Finished");

            return(returnMessage);
        }
Example #2
0
        private async void PowerOnVM(IVirtualMachine virtualMachine)
        {
            string vmName = virtualMachine.ComputerName;
            Task   task   = virtualMachine.StartAsync();
            await  task;

            lstBoxLog.Items.Add(vmName + " Started at " + DateTime.Now);
            lstBoxLog.Items.Add(vmName + " IPAddress : " + virtualMachine.GetPrimaryPublicIPAddress().IPAddress);
            UpdateVMData(null, null);
        }
        string GetVmControlContent(IVirtualMachine machine)
        {
            string           contents   = GetWebContentFile(ChangeStateFormFile);
            string           powerState = FormatPowerState(machine.PowerState);
            IPublicIPAddress ipAddress  = machine.GetPrimaryPublicIPAddress();
            string           action;
            string           buttonText;
            string           formVisibility      = "visible";
            string           qualifiedDnsName    = string.Empty;
            string           displayIp           = string.Empty;
            string           dnsCopyDisplayClass = "hidden";
            string           ipCopyDisplayClass  = "hidden";

            if (machine.PowerState == PowerState.Running)
            {
                action              = nameof(StopVm);
                buttonText          = "Deallocate";
                qualifiedDnsName    = ipAddress.Inner.DnsSettings != null ? ipAddress.Inner.DnsSettings.Fqdn : string.Empty;
                dnsCopyDisplayClass = !string.IsNullOrEmpty(qualifiedDnsName) ? "visible" : dnsCopyDisplayClass;
                displayIp           = ipAddress.IPAddress;
                ipCopyDisplayClass  = !string.IsNullOrEmpty(displayIp) ? "visible" : ipCopyDisplayClass;
            }
            else if (machine.PowerState == PowerState.Stopped || machine.PowerState == PowerState.Deallocated)
            {
                action     = nameof(StartVm);
                buttonText = "Start";
            }
            else
            {
                action         = string.Empty;
                buttonText     = string.Empty;
                formVisibility = "collapse";
            }
            if (!string.IsNullOrEmpty(_functionAccessCode))
            {
                action = $"{action}?code={_functionAccessCode}";
            }
            string finalForm = string.Format(contents, machine.Name, powerState, qualifiedDnsName, displayIp, action, formVisibility, buttonText, dnsCopyDisplayClass, ipCopyDisplayClass);

            return(finalForm);
        }
        internal async Task <string> GetVmStatusAsync(string name)
        {
            _helper.LogMessage($"Starting");

            string          returnMessage;
            IVirtualMachine machine = await GetVmByNameAsync(name);

            PowerState powerState = machine.PowerState;

            if (powerState == PowerState.Running)
            {
                IPublicIPAddress ipAddress = machine.GetPrimaryPublicIPAddress();
                returnMessage = $"{powerState}, IP Address: {ipAddress.IPAddress}";
            }
            else
            {
                returnMessage = $"Machine status: {powerState}";
            }

            _helper.LogMessage($"Finished");

            return(returnMessage);
        }
        private IVirtualMachineCustomImage PrepareCustomImage(string rgName, Region region, IAzure azure)
        {
            string vmName   = TestUtilities.GenerateName("muldvm");
            string uname    = "javauser";
            string password = "******";
            KnownLinuxVirtualMachineImage linuxImage = KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts;
            string          publicIpDnsLabel         = TestUtilities.GenerateName("pip");
            string          storageName = TestUtilities.GenerateName("stg");
            IVirtualMachine linuxVM     = azure.VirtualMachines
                                          .Define(vmName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithNewPrimaryNetwork("10.0.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
                                          .WithPopularLinuxImage(linuxImage)
                                          .WithRootUsername(uname)
                                          .WithRootPassword(password)
                                          .WithUnmanagedDisks()
                                          .DefineUnmanagedDataDisk("disk-1")
                                          .WithNewVhd(30)
                                          .WithCaching(CachingTypes.ReadWrite)
                                          .Attach()
                                          .DefineUnmanagedDataDisk("disk-2")
                                          .WithNewVhd(60)
                                          .WithCaching(CachingTypes.ReadOnly)
                                          .Attach()
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .WithNewStorageAccount(storageName)
                                          .WithOSDiskCaching(CachingTypes.ReadWrite)
                                          .Create();

            //
            TestHelper.DeprovisionAgentInLinuxVM(linuxVM.GetPrimaryPublicIPAddress().Fqdn, 22, uname, password);
            //
            linuxVM.Deallocate();
            linuxVM.Generalize();
            //
            string vhdBasedImageName = TestUtilities.GenerateName("img");
            //
            var creatableDisk = azure
                                .VirtualMachineCustomImages
                                .Define(vhdBasedImageName)
                                .WithRegion(region)
                                .WithExistingResourceGroup(rgName)
                                .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                .WithOSDiskCaching(linuxVM.OSDiskCachingType);

            foreach (IVirtualMachineUnmanagedDataDisk disk in linuxVM.UnmanagedDataDisks.Values)
            {
                creatableDisk.DefineDataDiskImage()
                .WithLun(disk.Lun)
                .FromVhd(disk.VhdUri)
                .WithDiskCaching(disk.CachingType)
                .WithDiskSizeInGB(disk.Size + 10)         // Resize each data disk image by +10GB
                .Attach();
            }
            //
            IVirtualMachineCustomImage customImage = creatableDisk.Create();

            return(customImage);
        }
Example #6
0
        public async Task <bool> DeployAsync()
        {
            var isDeploymentSuccessful = false;
            var mainTimer = Stopwatch.StartNew();

            RefreshableConsole.WriteLine("Running...");

            await ValidateTokenProviderAsync();

            tokenCredentials = new TokenCredentials(new RefreshableAzureServiceTokenProvider("https://management.azure.com/"));
            azureCredentials = new AzureCredentials(tokenCredentials, null, null, AzureEnvironment.AzureGlobalCloud);
            azureClient      = GetAzureClient(azureCredentials);

            await ValidateConfigurationAsync();

            try
            {
                RefreshableConsole.WriteLine();
                RefreshableConsole.WriteLine($"VM host: {configuration.VmName}.{configuration.RegionName}.cloudapp.azure.com");
                RefreshableConsole.WriteLine($"VM username: {configuration.VmUsername}");
                RefreshableConsole.WriteLine($"VM password: {configuration.VmPassword}");
                RefreshableConsole.WriteLine();

                await CreateResourceGroupAsync();

                BatchAccount     batchAccount      = null;
                IGenericResource appInsights       = null;
                ICosmosDBAccount cosmosDb          = null;
                IStorageAccount  storageAccount    = null;
                IVirtualMachine  linuxVm           = null;
                ConnectionInfo   sshConnectionInfo = null;

                await Task.WhenAll(new Task[]
                {
                    Task.Run(async() => batchAccount   = await CreateBatchAccountAsync(), cts.Token),
                    Task.Run(async() => appInsights    = await CreateAppInsightsResourceAsync(), cts.Token),
                    Task.Run(async() => cosmosDb       = await CreateCosmosDbAsync(), cts.Token),
                    Task.Run(async() => storageAccount = await CreateStorageAccountAsync(), cts.Token),

                    Task.Run(async() =>
                    {
                        linuxVm           = await CreateVirtualMachineAsync();
                        sshConnectionInfo = new ConnectionInfo(linuxVm.GetPrimaryPublicIPAddress().Fqdn, configuration.VmUsername, new PasswordAuthenticationMethod(configuration.VmUsername, configuration.VmPassword));
                        await WaitForSshConnectivityAsync(sshConnectionInfo);
                        await ConfigureVmAsync(sshConnectionInfo);
                    }, cts.Token)
                });

                var vmManagedIdentity = linuxVm.SystemAssignedManagedServiceIdentityPrincipalId;

                await AssignVmAsBillingReaderToSubscriptionAsync(vmManagedIdentity);
                await AssignVmAsContributorToAppInsightsAsync(vmManagedIdentity, appInsights);
                await AssignVmAsContributorToCosmosDb(vmManagedIdentity, cosmosDb);
                await AssignVmAsContributorToBatchAccountAsync(vmManagedIdentity, batchAccount);
                await AssignVmAsContributorToStorageAccountAsync(vmManagedIdentity, storageAccount);
                await AssignVmAsDataReaderToStorageAccountAsync(vmManagedIdentity, storageAccount);

                await RestartVmAsync(linuxVm);
                await WaitForSshConnectivityAsync(sshConnectionInfo);
                await WaitForDockerComposeAsync(sshConnectionInfo);
                await WaitForCromwellAsync(sshConnectionInfo);

                isDeploymentSuccessful = await VerifyInstallationAsync(storageAccount);

                if (!isDeploymentSuccessful)
                {
                    await DeleteResourceGroupIfUserConsentsAsync();
                }
            }
            catch (Microsoft.Rest.Azure.CloudException cloudException)
            {
                var json = cloudException.Response.Content;
                RefreshableConsole.WriteLine(json);
                Debugger.Break();
                WriteGeneralRetryMessageToConsole();
                await DeleteResourceGroupIfUserConsentsAsync();
            }
            catch (Exception exc)
            {
                RefreshableConsole.WriteLine(exc.ToString());
                Debugger.Break();
                WriteGeneralRetryMessageToConsole();
                await DeleteResourceGroupIfUserConsentsAsync();
            }

            RefreshableConsole.WriteLine($"Completed in {mainTimer.Elapsed.TotalMinutes:n1} minutes.");

            return(isDeploymentSuccessful);
        }