private string EvaluateFileContents(string filename) { ConsoleOutput.WriteLine("Loading {0} ...", filename); using (StreamReader reader = new StreamReader(filename)) { return(Regex.Replace(reader.ReadToEnd(), VarRegex, new MatchEvaluator(Rewrite), RegexOptions.IgnoreCase)); } }
private void CopyFiles(string sourcePath, string destinationPath, string exclude) { if (!string.IsNullOrEmpty(exclude) && Regex.IsMatch(sourcePath, exclude)) { ConsoleOutput.WriteLine(" Skip '{0}'", sourcePath); return; } if (_simulationOnly) { return; } if (File.Exists(sourcePath)) { // this is a file, target is a directory or a file if (Directory.Exists(destinationPath)) { // target is a directory string resolvedDestinationPath = Path.Combine(destinationPath, Path.GetFileName(sourcePath)); ConsoleOutput.WriteLine(" Copy '{0}' => '{1}'", sourcePath, resolvedDestinationPath); File.Copy(sourcePath, resolvedDestinationPath, true); } else { // target is a file ConsoleOutput.WriteLine(" Copy '{0}' => '{1}'", sourcePath, destinationPath); File.Copy(sourcePath, destinationPath, true); } } else { // this is a directory if (!Directory.Exists(destinationPath)) { ConsoleOutput.WriteLine(" MkDir '{0}'", destinationPath); Directory.CreateDirectory(destinationPath); } string[] systementries = Directory.GetFileSystemEntries(sourcePath); foreach (string systementry in systementries) { if (Directory.Exists(systementry)) { CopyFiles(systementry, Path.Combine(destinationPath, Path.GetFileName(systementry)), exclude); } else { string resolvedDestinationPath = Path.Combine(destinationPath, Path.GetFileName(systementry)); ConsoleOutput.WriteLine(" Copy '{0}' => '{1}'", systementry, resolvedDestinationPath); File.Copy(systementry, resolvedDestinationPath, true); } } } }
public VirtualMachinePowerDriver( VirtualMachineConfig virtualMachineConfig, SnapshotConfig snapshotConfig, bool simulationOnly) { _vmConfig = virtualMachineConfig; _snapshotConfig = snapshotConfig; _simulationOnly = simulationOnly; ConsoleOutput.WriteLine("Loading '{0}'", _vmConfig.Name); }
public void DisconnectFromHost() { ConsoleOutput.WriteLine("Disconnecting from '{0}' ({1})", string.IsNullOrEmpty(_vmConfig.Host) ? "localhost" : _vmConfig.Host, _vmConfig.Type); if (!_simulationOnly && _host != null) { _host.Disconnect(); _host = null; } }
public void MapVirtualMachine(CopyMethod copyMethod) { ConsoleOutput.WriteLine("Opening '{0}' ({1})", _vmConfig.File, _vmConfig.Type); _vm = new VMWareMappedVirtualMachine( _vmConfig.Name, _simulationOnly ? null : _host.Open(_vmConfig.File), _snapshotConfig.Username, _snapshotConfig.Password, copyMethod, _simulationOnly); }
public void PowerOffDependencies() { if (_dependenciesPowerDriver == null) { return; } ConsoleOutput.WriteLine("Powering off {0} dependenc{1}", _snapshotConfig.VirtualMachines.Count, _snapshotConfig.VirtualMachines.Count == 1 ? "y" : "ies"); _dependenciesPowerDriver.PowerOff(); _dependenciesPowerDriver.Dispose(); _dependenciesPowerDriver = null; }
/// <summary> /// Execute a file from a remote vm. /// </summary> private TaskResult Execute(VirtualMachineTaskConfig vmConfig) { TaskResult vmResult = new TaskResult(); vmResult.CmdLine = string.Format("VirtualMachine: {0} '{1}'", vmConfig.Command, vmConfig.Name); vmResult.Name = vmConfig.Name; try { ConsoleOutput.WriteLine(vmResult.CmdLine); if (!_installInstance.SimulationOnly) { switch (vmConfig.Command) { case VirtualMachineCommand.poweroff: _installInstance.VirtualMachine.PowerOff(); break; case VirtualMachineCommand.poweron: _installInstance.VirtualMachine.PowerOn(); break; case VirtualMachineCommand.waitfortoolsinguest: _installInstance.VirtualMachine.WaitForToolsInGuest(); break; case VirtualMachineCommand.shutdownguest: _installInstance.VirtualMachine.ShutdownGuest(); break; default: throw new Exception(string.Format("Unsupported command '{0}'", vmConfig.Command)); } ConsoleOutput.WriteLine(string.Format("Finished {0}", vmResult.CmdLine)); } } catch (Exception ex) { vmResult.LastError = ex.Message; vmResult.Success = false; ConsoleOutput.WriteLine(ex); } return(vmResult); }
public void CloseVirtualMachine() { ConsoleOutput.WriteLine("Closing '{0}' ({1})", _vmConfig.File, _vmConfig.Type); if (!_simulationOnly) { if (_vm != null) { _vm.Dispose(); _vm = null; } // bug: http://communities.vmware.com/message/1144091 GC.Collect(); GC.WaitForPendingFinalizers(); } }
private void CopyToVirtualMachine(CopyFileConfig copyFileConfig) { string destinationPath = copyFileConfig.DestinationPath; string destinationFileName = Path.Combine(destinationPath, Path.GetFileName(copyFileConfig.Name)); string sourceFilePath = Path.Combine(Environment.CurrentDirectory, copyFileConfig.File); bool createDirectory = false; bool copyFile = false; if (!_installInstance.SimulationOnly) { if (!copyFileConfig.CheckIfExists || (File.Exists(sourceFilePath) || Directory.Exists(sourceFilePath))) { if (!_installInstance.VirtualMachine.DirectoryExistsInGuest(destinationPath)) { createDirectory = true; } copyFile = true; } } else { copyFile = true; createDirectory = true; } if (createDirectory) { _installInstance.VirtualMachine.CreateDirectoryInGuest(destinationPath); } if (copyFile) { ConsoleOutput.WriteLine("Copying 'Local:{0}' to 'Remote:{1}'", sourceFilePath, destinationFileName); _installInstance.VirtualMachine.CopyFileFromHostToGuest( sourceFilePath, destinationFileName, copyFileConfig.Exclude); } else { ConsoleOutput.WriteLine("Skipping 'Local:{0}'", sourceFilePath); } }
public void PowerOnDependencies() { if (_snapshotConfig.VirtualMachines.Count == 0) { _dependenciesPowerDriver = null; return; } ConsoleOutput.WriteLine("Powering on {0} dependenc{1}", _snapshotConfig.VirtualMachines.Count, _snapshotConfig.VirtualMachines.Count == 1 ? "y" : "ies"); _dependenciesPowerDriver = new VirtualMachinesPowerDriver( _snapshotConfig.VirtualMachines, _simulationOnly); _dependenciesPowerDriver.PowerOn(); }
public void PowerOn() { // power on the virtual machine if it's powered off _vm.PowerOn(); _vm.WaitForToolsInGuest(); int powerDelay = _vmConfig.PowerDelay; if (powerDelay > 0) { ConsoleOutput.WriteLine("Waiting for {0} seconds for '{1}:{2}'", powerDelay, _vmConfig.Name, _snapshotConfig.Name); if (!_simulationOnly) { Thread.Sleep(powerDelay * 1000); } } }
public void LoginInGuest(string username, string password, GuestLoginType logintype) { int loginOptions = 0; switch (logintype) { case GuestLoginType.interactive: ConsoleOutput.WriteLine(" Interactively logging on to 'Remote:{0}' as '{1}'", _name, username); loginOptions = Constants.VIX_LOGIN_IN_GUEST_REQUIRE_INTERACTIVE_ENVIRONMENT; break; default: ConsoleOutput.WriteLine(" Logging on to 'Remote:{0}' as '{1}'", _name, username); break; } if (!_simulationOnly) { _vm.LoginInGuest(username, password, loginOptions, VMWareInterop.Timeouts.LoginTimeout); } }
/// <summary> /// Is a reboot required? /// </summary> /// <returns>true if a reboot was required</returns> public bool IsRebootRequired() { if (_config.RebootRequired) { return(true); } if (_process == null) { return(false); } if (_config.ExitCodes.Contains(_process.ExitCode, ExitCodeResult.reboot)) { ConsoleOutput.WriteLine(string.Format("Execution requires reboot (defined in exitcodes), return code: {0}", _process.ExitCode)); return(true); } return(false); }
public void ConnectToHost() { ConsoleOutput.WriteLine("Connecting to '{0}' ({1})", string.IsNullOrEmpty(_vmConfig.Host) ? "localhost" : _vmConfig.Host, _vmConfig.Type); if (!_simulationOnly) { _host = new VMWareVirtualHost(); switch (_vmConfig.Type) { case VirtualMachineType.Workstation: _host.ConnectToVMWareWorkstation(); break; case VirtualMachineType.ESX: _host.ConnectToVMWareVIServer(_vmConfig.Host, _vmConfig.Username, _vmConfig.Password); break; } } }
public void PowerOff() { foreach (VirtualMachinePowerDriver virtualMachinePowerDriver in _virtualMachinePowerDrivers) { try { virtualMachinePowerDriver.PowerOff(); virtualMachinePowerDriver.CloseVirtualMachine(); virtualMachinePowerDriver.DisconnectFromHost(); } catch (Exception ex) { ConsoleOutput.WriteLine("ERROR: Failed to power off and close '{0}:{1}'", virtualMachinePowerDriver.VmConfig.Name, virtualMachinePowerDriver.SnapshotConfig.Name); ConsoleOutput.WriteLine(ex); } virtualMachinePowerDriver.Dispose(); } _virtualMachinePowerDrivers.Clear(); }
/// <summary> /// Runs each installer on every VM in specified by config file /// </summary> /// <returns>List of all the results from the RemoteInstalls</returns> public List <ResultsGroup> Run() { STPStartInfo poolStartInfo = new STPStartInfo(); List <IWorkItemResult <IList <IList <ResultsGroup> > > > poolResults = new List <IWorkItemResult <IList <IList <ResultsGroup> > > >(); // build parallelizable tasks ParallelizableRemoteInstallDriverTaskCollections ptasks = new ParallelizableRemoteInstallDriverTaskCollections(); if (_configuration.VirtualMachines.Count == 0) { throw new InvalidConfigurationException("Missing virtual machines in configuration."); } // build the sequence that is going to be run foreach (VirtualMachineConfig vm in _configuration.VirtualMachines) { DriverTaskCollection tasks = new DriverTaskCollection(); if (vm.Snapshots.Count == 0) { throw new InvalidConfigurationException(string.Format("Missing snapshots in {0}. Define a 'current' snapshot with <snapshot name='*' />.", vm.Name)); } switch (_configuration.Installers.Sequence) { case InstallersSequence.alternate: tasks.Add(new DriverTasks.DriverTask_Alternate(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers, true, true)); break; case InstallersSequence.install: tasks.Add(new DriverTasks.DriverTask_Alternate(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers, true, false)); break; case InstallersSequence.uninstall: tasks.Add(new DriverTasks.DriverTask_Alternate(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers, false, true)); break; case InstallersSequence.fifo: tasks.Add(new DriverTasks.DriverTask_Fifo(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers)); break; case InstallersSequence.lifo: tasks.Add(new DriverTasks.DriverTask_Lifo(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers)); break; case InstallersSequence.clean: default: tasks.Add(new DriverTasks.DriverTask_Clean(_configuration, _logpath, _simulationOnly, vm, _configuration.Installers)); break; } ptasks.Add(tasks); } // the number of threads in the pipeline is either user-defined // or the number of virtual machines (default) if (_pipelineCount > 0) { poolStartInfo.MaxWorkerThreads = _pipelineCount; } else { poolStartInfo.MaxWorkerThreads = ptasks.Count; } if (ptasks.Count == 0) { throw new InvalidConfigurationException("Number of tasks cannot be zero."); } ConsoleOutput.WriteLine(string.Format("Starting {0} parallel installation(s) ({1} max) ...", poolStartInfo.MaxWorkerThreads, ptasks.Count)); SmartThreadPool pool = new SmartThreadPool(poolStartInfo); ConsoleOutput.ShowThreadID = (poolStartInfo.MaxWorkerThreads > 1); foreach (DriverTaskCollections tasks in ptasks) { poolResults.Add(pool.QueueWorkItem <DriverTaskCollections, IList <IList <ResultsGroup> > >( RunTasks, tasks)); } // wait for the pool to finish all the work SmartThreadPool.WaitAll(poolResults.ToArray()); // collect results List <ResultsGroup> groups = new List <ResultsGroup>(); foreach (IWorkItemResult <IList <IList <ResultsGroup> > > poolResult in poolResults) { foreach (IList <ResultsGroup> poolResultItem in poolResult.GetResult()) { groups.AddRange(poolResultItem); } } ConsoleOutput.WriteLine("Finished installation(s) with {0} result(s)", groups.Count); return(groups); }
private void CopyToTestClient(CopyFileConfig copyFileConfig, CopyFileResult copyFileResult) { string destinationPath = Path.Combine(_installInstance.LogPath, copyFileConfig.DestinationPath); string destinationFileName = Path.Combine(destinationPath, Path.GetFileName(copyFileConfig.Name)); bool createDirectory = false; bool copyFile = false; if (!_installInstance.SimulationOnly) { if (!copyFileConfig.CheckIfExists || (_installInstance.VirtualMachine.FileExistsInGuest(copyFileConfig.File) || _installInstance.VirtualMachine.DirectoryExistsInGuest(copyFileConfig.File))) { if (!Directory.Exists(destinationPath)) { createDirectory = true; } copyFile = true; } } else { copyFile = true; createDirectory = true; } if (createDirectory) { ConsoleOutput.WriteLine("Creating 'Local:{0}'", destinationPath); Directory.CreateDirectory(destinationPath); } if (copyFile) { ConsoleOutput.WriteLine("Copying 'Remote:{0}' to 'Local:{1}'", copyFileConfig.File, destinationFileName); _installInstance.VirtualMachine.CopyFileFromGuestToHost(copyFileConfig.File, destinationFileName, copyFileConfig.Exclude); // local destination only exists when file was successfuly copied string destinationShortFileName = Path.Combine(_installInstance.ShortLogPath, copyFileConfig.DestinationPath); destinationShortFileName = Path.Combine(destinationShortFileName, Path.GetFileName(copyFileConfig.Name)); copyFileResult.DestFilename = destinationShortFileName; if (!_installInstance.SimulationOnly && File.Exists(destinationFileName)) { ConsoleOutput.WriteLine("Processing 'Local:{0}'", destinationFileName); string transformedData = File.ReadAllText(destinationFileName); if (!string.IsNullOrEmpty(copyFileConfig.XslTransform)) { // transform data XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(transformedData); XPathDocument xmlPathDocument = new XPathDocument(new XmlNodeReader(xmlDocument)); XslCompiledTransform xslTransform = new XslCompiledTransform(); xslTransform.Load(XmlReader.Create(new StreamReader(copyFileConfig.XslTransform))); StringWriter writer = new StringWriter(); xslTransform.Transform(xmlPathDocument, null, writer); writer.Close(); transformedData = writer.ToString(); File.WriteAllText(destinationFileName, transformedData); } // include contents in results, as is if (copyFileConfig.IncludeDataInResults) { copyFileResult.Data = transformedData; } } } }
public VMWareVirtualMachine.Process RunProgramInGuest(string path, string parameters, int options) { ConsoleOutput.WriteLine(" Executing 'Remote:{0} {1}'", path, parameters); return(_simulationOnly ? new VMWareVirtualMachine.Process(null) : _vm.RunProgramInGuest(path, parameters, options, VMWareInterop.Timeouts.RunProgramTimeout)); }
/// <summary> /// Execute a file from a remote vm. /// </summary> private TaskResult Execute(SnapshotTaskConfig snapshotConfig) { TaskResult snapshotTaskResult = new TaskResult(); snapshotTaskResult.CmdLine = string.Format("Snapshot: {0} '{1}'", snapshotConfig.Command, snapshotConfig.Name); snapshotTaskResult.Name = snapshotConfig.Name; try { ConsoleOutput.WriteLine(snapshotTaskResult.CmdLine); if (!_installInstance.SimulationOnly) { switch (snapshotConfig.Command) { case SnapshotCommand.create: _installInstance.VirtualMachine.Snapshots.CreateSnapshot( snapshotConfig.Name, snapshotConfig.Description, snapshotConfig.IncludeMemory ? Constants.VIX_SNAPSHOT_INCLUDE_MEMORY : 0, VMWareInterop.Timeouts.CreateSnapshotTimeout); break; case SnapshotCommand.remove: _installInstance.VirtualMachine.Snapshots.RemoveSnapshot( snapshotConfig.Name); break; case SnapshotCommand.removeifexists: VMWareSnapshot snapshot = _installInstance.VirtualMachine.Snapshots.FindSnapshotByName( snapshotConfig.Name); if (snapshot != null) { ConsoleOutput.WriteLine("Removing {0}", snapshotTaskResult.CmdLine); snapshot.RemoveSnapshot(); } else { ConsoleOutput.WriteLine("No {0}", snapshotTaskResult.CmdLine); } break; case SnapshotCommand.revert: _installInstance.VirtualMachine.Snapshots.FindSnapshotByName( snapshotConfig.Name).RevertToSnapshot(Constants.VIX_VMPOWEROP_SUPPRESS_SNAPSHOT_POWERON); break; default: throw new Exception(string.Format("Unsupported command '{0}'", snapshotConfig.Command)); } ConsoleOutput.WriteLine(string.Format("Finished {0}", snapshotTaskResult.CmdLine)); } } catch (Exception ex) { snapshotTaskResult.LastError = ex.Message; snapshotTaskResult.Success = false; ConsoleOutput.WriteLine(ex); } return(snapshotTaskResult); }
/// <summary> /// Install/uninstall MSI /// </summary> /// <returns></returns> public Result InstallUninstall(InstanceOptions options) { ConsoleOutput.WriteLine("Running 'Remote:{0}', '{1}'", _installerConfig.Name, _installerConfig.DestinationPath); // remote logfiles string install_logfile = string.Empty; string uninstall_logfile = string.Empty; // the remote install result Result result = new Result( _installerConfig.Name, _installerConfig.SvnRevision); if (!Directory.Exists(LogPath)) { ConsoleOutput.WriteLine("Creating directory '{0}'", LogPath); Directory.CreateDirectory(LogPath); } ConsoleOutput.WriteLine("Saving logs in '{0}'", LogPath); SequenceDrivers additionalSequences = new SequenceDrivers(); ExecuteDriver executeDriver = new ExecuteDriver(this); executeDriver.Add(_config.Tasks); executeDriver.Add(_config.VirtualMachines.Tasks); executeDriver.Add(_vmConfig.Tasks); executeDriver.Add(_vmConfig.Snapshots.Tasks); executeDriver.Add(_snapshotConfig.Tasks); executeDriver.Add(_config.Installers.Tasks); executeDriver.Add(_installerConfig.Tasks); additionalSequences.Add(executeDriver); CopyFilesDriver copyFilesDriver = new CopyFilesDriver(this); copyFilesDriver.Add(_config.CopyFiles); copyFilesDriver.Add(_config.VirtualMachines.CopyFiles); copyFilesDriver.Add(_vmConfig.CopyFiles); copyFilesDriver.Add(_vmConfig.Snapshots.CopyFiles); copyFilesDriver.Add(_snapshotConfig.CopyFiles); copyFilesDriver.Add(_config.Installers.CopyFiles); copyFilesDriver.Add(_installerConfig.CopyFiles); additionalSequences.Add(copyFilesDriver); // execute and copy files before all result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.beforeall)); DateTime start = DateTime.UtcNow; try { // execute the installers try { VirtualMachineDeployment deploy = null; if (!_simulationOnly) { deploy = _installerConfig.CreateDeployment(_vm); } // install if (options.Install) { // execute and copy files before install result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.beforeinstall)); ConsoleOutput.WriteLine("Installing 'Remote:{0}', '{1}'", _installerConfig.Name, _installerConfig.DestinationPath); result.SuccessfulInstall = InstallResult.False; if (!_simulationOnly) { deploy.Install(out install_logfile); } result.SuccessfulInstall = InstallResult.True; result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.aftersuccessfulinstall)); } // uninstall if (options.Uninstall) { // execute and copy files before uninstall result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.beforeuninstall)); DateTime startUnInstall = DateTime.UtcNow; ConsoleOutput.WriteLine("Uninstalling 'Remote:{0}', '{1}'", _installerConfig.Name, _installerConfig.DestinationPath); result.SuccessfulUnInstall = InstallResult.False; if (!_simulationOnly) { deploy.UnInstall(out uninstall_logfile); } result.SuccessfulUnInstall = InstallResult.True; result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.aftersuccessfuluninstall)); } if (!_simulationOnly && deploy != null && deploy.IsRebootRequired()) { ConsoleOutput.WriteLine("Reboot required after 'Remote:{0}'", _installerConfig.Name); result.RebootRequired = true; } } catch (Exception ex) { result.LastError = ex.Message; result.Success = false; ConsoleOutput.WriteLine(ex); result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.afterfailedinstalluninstall)); } } finally { result.Duration = DateTime.UtcNow.Subtract(start); ConsoleOutput.WriteLine("Done after '{0}'", result.Duration); } result.AddRange(additionalSequences.ExecuteSequence( SequenceWhen.afterall)); // copy the remote logfiles back if (!string.IsNullOrEmpty(install_logfile)) { string target_install_logfile = Path.Combine(LogPath, Path.GetFileName(install_logfile)); ConsoleOutput.WriteLine("Collecting 'Remote:{0}' => '{1}'", install_logfile, target_install_logfile); _vm.CopyFileFromGuestToHost(install_logfile, target_install_logfile); result.InstallLogfile = Path.Combine(ShortLogPath, Path.GetFileName(install_logfile)); } if (!string.IsNullOrEmpty(uninstall_logfile)) { string target_uninstall_logfile = Path.Combine(LogPath, Path.GetFileName(uninstall_logfile)); ConsoleOutput.WriteLine("Collecting 'Remote:{0}' => '{1}'", uninstall_logfile, target_uninstall_logfile); _vm.CopyFileFromGuestToHost(uninstall_logfile, target_uninstall_logfile); result.UnInstallLogfile = Path.Combine(ShortLogPath, Path.GetFileName(uninstall_logfile)); } return(result); }