private async void DeallocateVM(IVirtualMachine virtualMachine) { string vmName = virtualMachine.ComputerName; Task task = virtualMachine.DeallocateAsync(); await task; lstBoxLog.Items.Add(vmName + " deallocated at " + DateTime.Now); UpdateVMData(null, null); }
public Status SetPowerState() { Status status = Status.NoChange; bool isRunning = false; string powerState = virtualMachine.PowerState.ToString(); // Determine if VMs are being managed bool manage_vm = Convert.ToBoolean(settings.First(s => s.name == "manage_vms").value); // Only operate on the machine if it is running or deallocated // There are many states that the vm could be in so this needs to be guarded logger.Debug("{0} - {1}: Power state - {2}", resourceGroup.GetName(), GetName(), powerState); if (powerState.ToLower() == "powerstate/running" || powerState.ToLower() == "powerstate/deallocated") { // Set the isRunning flag if (powerState.ToLower() == "powerstate/running") { isRunning = true; } // Perform checks to see if this machine should be running bool permitted = ShouldBeRunning(); if (isRunning && !permitted && manage_vm) { logger.Information("{0} - {1}: Stopping virtual machine", resourceGroup.GetName(), GetName()); virtualMachine.DeallocateAsync(); // Deallocate(); status = Status.Stopped; } if (!isRunning && permitted && manage_vm) { logger.Information("{0} - {1}: Starting virtual machine", resourceGroup.GetName(), GetName()); virtualMachine.StartAsync(); // Start(); status = Status.Started; } } return(status); }
public static async Task <JObject> StartAndStopVMsCore(HttpRequest req, Logging logging) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); JObject data = JsonConvert.DeserializeObject <JObject>(requestBody); string _TaskInstanceId = data["TaskInstanceId"].ToString(); string _ExecutionUid = data["ExecutionUid"].ToString(); try { logging.LogInformation("StartAndStopVMs function processed a request."); string Subscription = data["Target"]["SubscriptionUid"].ToString(); string VmName = data["Target"]["VMname"].ToString(); string VmResourceGroup = data["Target"]["ResourceGroup"].ToString(); string VmAction = data["Target"]["Action"].ToString(); Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureAuth = Microsoft.Azure.Management.Fluent.Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders).Authenticate(Shared.Azure.AzureSDK.GetAzureCreds(Shared._ApplicationOptions.UseMSI)); IAzure azure = azureAuth.WithSubscription(Subscription); logging.LogInformation("Selected subscription: " + azure.SubscriptionId); IVirtualMachine vm = azure.VirtualMachines.GetByResourceGroup(VmResourceGroup, VmName); if (vm.PowerState == Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "start") { logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString()); vm.StartAsync().Wait(5000); logging.LogInformation("VM Start Initiated: " + vm.Name); } if (vm.PowerState != Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "stop") { logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString()); vm.DeallocateAsync().Wait(5000); logging.LogInformation("VM Stop Initiated: " + vm.Name); } JObject Root = new JObject { ["Result"] = "Complete" }; TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); if (VmName != null) { Root["Result"] = "Complete"; } else { Root["Result"] = "Please pass a name, resourcegroup and action to request body"; TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Task missing VMname, ResourceGroup or SubscriptionUid in Target element."); return(Root); } //Update Task Instance TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, System.Guid.Empty, ""); return(Root); } catch (System.Exception TaskException) { logging.LogErrors(TaskException); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Failed when trying to start or stop VM"); JObject Root = new JObject { ["Result"] = "Failed" }; return(Root); } }
public static Task Stop(IVirtualMachine vm, ILogger log) { log.LogInformation("Stopping {name} (current state: {state})", vm.Name, vm.PowerState.ToString()); return(vm.DeallocateAsync()); }
public Task StopVirtualMachineAsync(IVirtualMachine vm) { return(vm.DeallocateAsync()); }