private void validate_button_Click(object sender, EventArgs e) { var validateExecutable = new ObservableCollection <Executables> { new Executables { Argument = "/c timeout 3", ExecutableFileName = "cmd.exe" } }; operations_groupBox.Enabled = false; foreach (DataGridViewRow row in machines_DataGridView.Rows) { var selected = Convert.ToBoolean(row.Cells[0].Value); if (!selected) { continue; } VirtualMachine vm = row.DataBoundItem as VirtualMachine; UpdateRowIndex(row.Index, ExecuteOnVirtualMachine(vm, validateExecutable)); } operations_groupBox.Enabled = true; }
/// <summary> /// Handles the Click event of the ok_Button control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void remove_Button_Click(object sender, EventArgs e) { operations_groupBox.Enabled = false; foreach (DataGridViewRow row in machines_DataGridView.Rows) { var selected = Convert.ToBoolean(row.Cells[0].Value); if (!selected) { continue; } VirtualMachine vm = row.DataBoundItem as VirtualMachine; using (var virtualCenter = GetVSphereController()) { var machine = virtualCenter.GetVirtualMachines().First(x => x.HostName == vm.Name); if (machine.PowerState == VirtualMachinePowerState.PoweredOn) { continue; } // The VM is not powered on, so go ahead and power it on. //if (!machine.RevertToSnapshot(true)) continue; virtualCenter.RevertToSnapshot(machine); //if (!machine.DeleteAllSnapshot(true)) continue; virtualCenter.DeleteAllVirtualMachineSnapshot(machine); TraceFactory.Logger.Info("Machine {0}: Snapshot deleted".FormatWith(vm.Name)); virtualCenter.PowerOn(machine); } } operations_groupBox.Enabled = true; }
private void PopulateMachinesGrid(string platformName) { VirtualMachinePlatform platform = _entities.VirtualMachinePlatforms.FirstOrDefault(x => x.PlatformId.Equals(platformName)); if (platform != null) { IEnumerable <VirtualMachine> machines = VirtualMachine.Select(platform: platformName, includePlatforms: true); var query = ( from m in machines from p in m.VirtualMachinePlatforms where platform.PlatformId.Equals(p.PlatformId) select m ).Distinct(); _machines.Clear(); foreach (var item in query) { _machines.Add(item); } machines_DataGridView.DataSource = null; machines_DataGridView.DataSource = _machines; } }
private bool ExecuteOnVirtualMachine(VirtualMachine vm, ObservableCollection <Executables> executables) { using (var virtualCenter = GetVSphereController()) { var machine = virtualCenter.GetVirtualMachines().First(x => x.HostName == vm.Name); if (machine.PowerState != VirtualMachinePowerState.PoweredOn) { // The VM is not powered on, so go ahead and power it on. //if (machine.PowerOn(true)) virtualCenter.PowerOn(machine); { Thread.Sleep(TimeSpan.FromSeconds(90)); } } try { for (int i = 0; i < executables.Count; i++) { string executable = executables.ElementAt(i).ExecutableFileName; string argument = executables.ElementAt(i).Argument.Replace("{MachineName}", vm.Name); // string decryptedPassword = BasicEncryption.Decrypt(UserManager.CurrentUserCredential.Password, UserManager.EncryptionKey); var pid = virtualCenter.RunGuestProcess(machine, executable, argument, UserManager.CurrentUser.ToNetworkCredential(), true); if (pid <= 0) { UpdateStatus("{0} failed to execute on {1}".FormatWith(executable, vm.Name)); return(false); } UpdateStatus("Executed: {0} on {1}".FormatWith(executable, vm.Name)); } } catch (Exception exception) { TraceFactory.Logger.Error("{0}:{1} with {2}".FormatWith(machine.HostName, "Failed", exception.Message)); vm.PowerState = "Powered Off"; if ( exception.Message == "The guest authentication being used does not have sufficient permissions to perform the operation.") { vm.UsageState = VMError.GuestPrivilege.ToString(); } else if (exception.Message == "The guest operations agent could not be contacted") { vm.UsageState = VMError.ServiceConnection.ToString(); } else if (exception.Message.Contains("The specified guest user does not match the user currently logged in interactively")) { vm.UsageState = VMError.GuestLogin.ToString(); } UpdateStatus("{0} failed with exception: {1}".FormatWith(vm.Name, exception.Message)); virtualCenter.Shutdown(machine); } } return(true); }
/// <summary> /// Gets the VM list. /// </summary> /// <param name="sessionId">The session id.</param> /// <param name="usageState">State of the usage.</param> /// <returns></returns> private static Collection <VirtualMachine> GetMachineList(string sessionId, VMUsageState usageState) { var reservedVMList = new Collection <VirtualMachine>(); foreach (var machine in VirtualMachine.Select(sessionId: sessionId, usageState: usageState)) { reservedVMList.Add(machine); } return(reservedVMList); }
private static List <VirtualMachine> GetMasterList(UserCredential credential, RequestedVMDictionary requestedVMs) { List <VirtualMachine> masterMachineList = null; if (requestedVMs.Count == 0) { TraceFactory.Logger.Debug("No specific machines requested."); // Add all available VMs with no hold ID to the master list masterMachineList = VirtualMachine.Select(VMPowerState.PoweredOff, VMUsageState.Available, holdId: null).ToList(); } else { TraceFactory.Logger.Debug("Specific machines requested."); // Add all available VMs with no hold ID to the master list masterMachineList = VirtualMachine.Select(VMPowerState.PoweredOff, VMUsageState.Available).ToList(); // The user requested specific machines, so throw out any machines that are not on that list IEnumerable <string> requestedVMNames = requestedVMs.SelectMany(n => n.Value); masterMachineList.RemoveAll(n => !requestedVMNames.Contains(n.Name, StringComparer.OrdinalIgnoreCase)); } // If user is not an admin, check for user group rights to the VMs if (!credential.HasPrivilege(UserRole.Administrator)) { TraceFactory.Logger.Debug("{0} total machines BEFORE quota".FormatWith(masterMachineList.Count)); using (var enterpriseTestContext = DbConnect.EnterpriseTestContext()) { var allowedVMs = enterpriseTestContext.UserGroups .Where(n => n.Users.Any(m => m.UserName == credential.UserName)) .SelectMany(n => n.FrameworkClients) .Select(n => n.FrameworkClientHostName).ToList(); masterMachineList.RemoveAll(n => !allowedVMs.Contains(n.Name, StringComparer.OrdinalIgnoreCase)); } TraceFactory.Logger.Debug("{0} total machines AFTER quota".FormatWith(masterMachineList.Count)); } return(masterMachineList); }
private void shutdown_button_Click(object sender, EventArgs e) { operations_groupBox.Enabled = false; foreach (DataGridViewRow row in machines_DataGridView.Rows) { var selected = Convert.ToBoolean(row.Cells[0].Value); if (!selected) { continue; } VirtualMachine vm = row.DataBoundItem as VirtualMachine; using (var virtualCenter = GetVSphereController()) { var machine = virtualCenter.GetVirtualMachines().First(x => x.HostName == vm.Name); if (machine.PowerState == VirtualMachinePowerState.PoweredOn) { virtualCenter.Shutdown(machine); } } } operations_groupBox.Enabled = true; }
/// <summary> /// Gets a replacement VM if one is not responding. /// </summary> /// <param name="replacedVMName">The name of the replaced VM.</param> /// <returns></returns> public static VirtualMachine GetReplacement(string replacedVMName) { VirtualMachine replacement = null; using (AssetInventoryContext context = DbConnect.AssetInventoryContext()) { //Get the SessionId that tried to power-on the failed machine FrameworkClient replacedVirtualMachine = Select(context, replacedVMName); LockToken lockToken = new GlobalLockToken("VirtualMachineReservation", new TimeSpan(0, 1, 0), new TimeSpan(0, 2, 0)); ExecutionServices.CriticalSection.Run(lockToken, () => { //Get the next available machine replacement = VirtualMachine.SelectReplacement(replacedVirtualMachine.PlatformUsage, replacedVirtualMachine.HoldId); if (replacement != null) { Reserve ( context, replacement.Name, replacedVirtualMachine.PlatformUsage, DateTime.Now, replacedVirtualMachine.SessionId, GlobalSettings.Environment ); context.SaveChanges(); } else { throw new VMInventoryException("Insufficient VMs available."); } }); } return(replacement); }
private void execute_button_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in machines_DataGridView.Rows) { var selected = Convert.ToBoolean(row.Cells[0].Value); if (!selected) { continue; } VirtualMachine vm = row.DataBoundItem as VirtualMachine; UpdateRowIndex(row.Index, ExecuteOnVirtualMachine(vm, executableListCollection)); } //int parallelOperationCount = (int)(batchsize_numericUpDown.Value / machines_DataGridView.SelectedRows.Count); //Parallel.ForEach(Partitioner.Create(0, machines_DataGridView.SelectedRows.Count, parallelOperationCount), range => // { // for (int i = range.Item1; i < range.Item2; i++) // { // VirtualMachine vm = machines_DataGridView.SelectedRows[i].DataBoundItem as VirtualMachine; // UpdateRowIndex(i, ExecuteOnVirtualMachine(vm, executableListCollection)); // } // }); }
/// <summary> /// Initializes a new instance of the <see cref="VirtualMachineSelection"/> class. /// </summary> /// <param name="machine">The machine.</param> /// <param name="remainingCount">The remaining count.</param> /// <param name="totalCount">The total count.</param> public VirtualMachineSelection(VirtualMachine machine, int remainingCount, int totalCount) { _data = new Tuple <VirtualMachine, int, int>(machine, remainingCount, totalCount); }