using System; using System.Collections.Generic; using System.IO; using Interop.VixCOM; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Drawing; namespace Vestris.VMWareLib { /// /// Virtual machine clone type. /// public enum VMWareVirtualMachineCloneType { /// /// A full, independent clone of the virtual machine. /// Full = Constants.VIX_CLONETYPE_FULL, /// /// A linked clone is a copy of a virtual machine that shares virtual disks with the parent virtual /// machine in an ongoing manner. /// Linked = Constants.VIX_CLONETYPE_LINKED } /// /// A VMWare Virtual Machine. /// public class VMWareVirtualMachine : VMWareVixHandle { /// /// Guest file info. /// public class GuestFileInfo { private int _flags = 0; private long _fileSize = 0; private Nullable _lastModified = null; private string _guestPathName; /// /// File size in bytes, zero for directories. /// public long FileSize { get { return _fileSize; } set { _fileSize = value; } } /// /// File attributes/flags. /// public int Flags { get { return _flags; } set { _flags = value; } } /// /// True if directory. /// public bool IsDirectory { get { return (_flags & Constants.VIX_FILE_ATTRIBUTES_DIRECTORY) > 0; } } /// /// True if symbolic link. /// public bool IsSymLink { get { return (_flags & Constants.VIX_FILE_ATTRIBUTES_SYMLINK) > 0; } } /// /// Last modified time. /// public Nullable LastModified { get { return _lastModified; } set { _lastModified = value; } } /// /// Guest file or directory name. /// public string GuestPathName { get { return _guestPathName; } set { _guestPathName = value; } } } /// /// An indexer for variables. /// public class VariableIndexer { private IVM2 _handle; private int _variableType; /// /// A variables indexer. /// /// Virtual machine's variables to index. /// Variable type, one of the following. /// /// Constants.VIX_VM_GUEST_VARIABLE /// Constants.VIX_VM_CONFIG_RUNTIME_ONLY /// Constants.VIX_GUEST_ENVIRONMENT_VARIABLE /// /// public VariableIndexer(IVM2 vm, int variableType) { _handle = vm; _variableType = variableType; } /// /// Environment, guest and runtime variables. /// /// Name of the variable. [IndexerName("Variables")] public string this[string name] { get { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.ReadVariable( _variableType, name, 0, callback), callback)) { return job.Wait( Constants.VIX_PROPERTY_JOB_RESULT_VM_VARIABLE_STRING, VMWareInterop.Timeouts.ReadVariableTimeout); } } catch (Exception ex) { throw new Exception( string.Format("Failed to get virtual machine variable: name=\"{0}\"", name), ex); } } set { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.WriteVariable( _variableType, name, value, 0, callback), callback)) { job.Wait(VMWareInterop.Timeouts.WriteVariableTimeout); } } catch (Exception ex) { throw new Exception( string.Format("Failed to set virtual machine variable: name=\"{0}\" value=\"{1}\"", name, value), ex); } } } } /// /// A process running in the guest operating system. /// public class Process { /// /// Process ID. /// public long Id; /// /// Process name. /// public string Name; /// /// Process owner. /// public string Owner; /// /// Process start date/time. /// public DateTime StartDateTime; /// /// Process command line. /// public string Command; /// /// True if process is being debugged. /// public bool IsBeingDebugged = false; /// /// Process exit code for finished processes. /// public int ExitCode = 0; private IVM2 _vm; /// /// A process running in the guest operating system on a virtual machine. /// /// Virtual machine. public Process(IVM2 vm) { _vm = vm; } /// /// Kill a process in the guest operating system. /// public void KillProcessInGuest() { KillProcessInGuest(VMWareInterop.Timeouts.KillProcessTimeout); } /// /// Kill a process in the guest operating system. /// /// Timeout in seconds. public void KillProcessInGuest(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_vm.KillProcessInGuest( Convert.ToUInt64(Id), 0, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to kill process in guest: processId={0}", Id), ex); } } } private VariableIndexer _guestEnvironmentVariables = null; private VariableIndexer _runtimeConfigVariables = null; private VariableIndexer _guestVariables = null; private VMWareRootSnapshotCollection _snapshots = null; private VMWareSharedFolderCollection _sharedFolders = null; /// /// A VMWare Virtual Machine. /// /// A handle to a virtual machine. public VMWareVirtualMachine(IVM2 vm) : base(vm) { _guestEnvironmentVariables = new VariableIndexer(_handle, Constants.VIX_GUEST_ENVIRONMENT_VARIABLE); _runtimeConfigVariables = new VariableIndexer(_handle, Constants.VIX_VM_CONFIG_RUNTIME_ONLY); _guestVariables = new VariableIndexer(_handle, Constants.VIX_VM_GUEST_VARIABLE); _sharedFolders = new VMWareSharedFolderCollection(_handle); _snapshots = new VMWareRootSnapshotCollection(_handle); } /// /// The path to the virtual machine configuration file. /// public string PathName { get { return GetProperty(Constants.VIX_PROPERTY_VM_VMX_PATHNAME); } } /// /// Returns true if the virtual machine is running. /// public bool IsRunning { get { return GetProperty(Constants.VIX_PROPERTY_VM_IS_RUNNING); } } /// /// Returns virtual machine powerstate, an OR-ed set of VIX_POWERSTATE_* values. /// public int PowerState { get { return GetProperty(Constants.VIX_PROPERTY_VM_POWER_STATE); } } /// /// Returns true if the virtual machine is paused. /// public bool IsPaused { get { return (PowerState & Constants.VIX_POWERSTATE_PAUSED) > 0; } } /// /// Returns true if the virtual machine is suspended. /// public bool IsSuspended { get { return (PowerState & Constants.VIX_POWERSTATE_SUSPENDED) > 0; } } /// /// The memory size of the virtual machine. /// public int MemorySize { get { return GetProperty(Constants.VIX_PROPERTY_VM_MEMORY_SIZE); } } /// /// The number of virtual CPUs configured for the virtual machine. /// public int CPUCount { get { return GetProperty(Constants.VIX_PROPERTY_VM_NUM_VCPUS); } } /// /// Power on a virtual machine. /// public void PowerOn() { PowerOn(VMWareInterop.Timeouts.PowerOnTimeout); } /// /// Power on a virtual machine. /// /// Timeout in seconds. public void PowerOn(int timeoutInSeconds) { PowerOn(Constants.VIX_VMPOWEROP_NORMAL | Constants.VIX_VMPOWEROP_LAUNCH_GUI, timeoutInSeconds); } /// /// Power on a virtual machine. /// /// Additional power options. /// Timeout in seconds. public void PowerOn(int powerOnOptions, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.PowerOn( powerOnOptions, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to power on virtual machine: powerOnOptions={0} timeoutInSeconds={1}", powerOnOptions, timeoutInSeconds), ex); } } /// /// This function returns when VMware Tools has successfully started in the guest operating system. /// VMware Tools is a collection of services that run in the guest. /// public void WaitForToolsInGuest() { WaitForToolsInGuest(VMWareInterop.Timeouts.WaitForToolsTimeout); } /// /// This function returns when VMware Tools has successfully started in the guest operating system. /// VMware Tools is a collection of services that run in the guest. /// /// Timeout in seconds. public void WaitForToolsInGuest(int timeoutInSeconds) { try { // wait till the machine boots or times out with an error VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob( _handle.WaitForToolsInGuest(timeoutInSeconds, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to wait for tools in guest: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Get all snapshots. /// /// A list of snapshots. public VMWareRootSnapshotCollection Snapshots { get { return _snapshots; } } /// /// This function establishes a guest operating system authentication context. /// /// The name of a user account on the guest operating system. /// The password of the account identified by userName. public void LoginInGuest(string username, string password) { LoginInGuest(username, password, VMWareInterop.Timeouts.LoginTimeout); } /// /// This function establishes a guest operating system authentication context. /// /// The name of a user account on the guest operating system. /// The password of the account identified by userName. /// Timeout in seconds. public void LoginInGuest(string username, string password, int timeoutInSeconds) { LoginInGuest(username, password, 0, timeoutInSeconds); } /// /// This function establishes a guest operating system authentication context. /// /// The name of a user account on the guest operating system. /// The password of the account identified by userName. /// /// Must be 0 or VixCOM.Constants.VIX_LOGIN_IN_GUEST_REQUIRE_INTERACTIVE_ENVIRONMENT, which forces interactive /// guest login within a graphical session that is visible to the user. On Linux, interactive environment /// requires that the X11 window system be running to start the vmware-user process. Without X11, pass 0 as /// options to start the vmware-guestd process instead. /// /// Timeout in seconds. /// /// Logins are supported on Linux and Windows. To log in as a Windows Domain user, specify the "userName" parameter in /// the form "domain\username". Other guest operating systems are not supported for login, including Solaris, FreeBSD, /// and Netware. /// public void LoginInGuest(string username, string password, int options, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.LoginInGuest( username, password, options, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to login in guest: username=\"{0}\" options={1} timeoutInSeconds={2}", username, options, timeoutInSeconds), ex); } } /// /// This function waits for the vmwareuser process to exist in the guest. /// /// The name of a user account on the guest operating system. /// The password of the account identified by userName. /// Timeout in seconds. public void WaitForVMWareUserProcessInGuest(string username, string password, int timeoutInSeconds) { //http://communities.vmware.com/message/1154264 bool loggedIn = false; try { LoginInGuest(username, password, timeoutInSeconds); loggedIn = true; DateTime dtStart = DateTime.Now; while (true) { VMWareProcessCollection guestProcesses = this.GuestProcesses; Process vmwareUserExeProcess = guestProcesses.FindProcess("vmwareuser.exe", StringComparison.OrdinalIgnoreCase); if (vmwareUserExeProcess != null) { break; } vmwareUserExeProcess = guestProcesses.FindProcess("vmware-user", StringComparison.OrdinalIgnoreCase); if (vmwareUserExeProcess != null) { break; } TimeSpan ts = DateTime.Now.Subtract(dtStart); if (ts.TotalSeconds >= timeoutInSeconds) { throw new VMWareException(Constants.VIX_E_TIMEOUT_WAITING_FOR_TOOLS, "vmwareuser"); } } } finally { if (loggedIn) { try { LogoutFromGuest(timeoutInSeconds); } catch { //ignore this exception so that it does not swallow any previous exceptions } } } } /// /// This function waits for the vmwareuser process to exist in the guest. /// /// The name of a user account on the guest operating system. /// The password of the account identified by userName. public void WaitForVMWareUserProcessInGuest(string username, string password) { WaitForVMWareUserProcessInGuest(username, password, VMWareInterop.Timeouts.WaitForToolsTimeout); } /// /// Copies a file or directory from the local system (where the Vix client is running) to the guest operating system. /// /// File location on the host operating system. /// File location on the guest operating system. public void CopyFileFromHostToGuest(string hostPathName, string guestPathName) { CopyFileFromHostToGuest(hostPathName, guestPathName, VMWareInterop.Timeouts.CopyFileTimeout); } /// /// Copies a file or directory from the local system (where the Vix client is running) to the guest operating system. /// You must call LoginInGuest() before calling this procedure. /// Only absolute paths should be used for files in the guest; the resolution of relative paths is not specified. /// /// File location on the host operating system. /// File location on the guest operating system. /// Timeout in seconds. public void CopyFileFromHostToGuest(string hostPathName, string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.CopyFileFromHostToGuest( hostPathName, guestPathName, 0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to copy file from host to guest: hostPathName=\"{0}\" guestPathName=\"{1}\" timeoutInSeconds={2}", hostPathName, guestPathName, timeoutInSeconds), ex); } } /// /// Deletes a file from guest file system. /// /// File location on the guest operating system. public void DeleteFileFromGuest(string guestPathName) { DeleteFileFromGuest(guestPathName, VMWareInterop.Timeouts.DeleteFileTimeout); } /// /// Deletes a file from guest file system. /// /// File location on the guest operating system. /// Timeout in seconds. public void DeleteFileFromGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.DeleteFileInGuest( guestPathName, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to delete file from guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Deletes a directory from guest directory system. /// /// Directory location on the guest operating system. public void DeleteDirectoryFromGuest(string guestPathName) { DeleteDirectoryFromGuest(guestPathName, VMWareInterop.Timeouts.DeleteDirectoryTimeout); } /// /// Deletes a directory from guest directory system. /// /// Directory location on the guest operating system. /// Timeout in seconds. public void DeleteDirectoryFromGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.DeleteDirectoryInGuest( guestPathName, 0, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to delete directory from guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Copies a file or directory from the guest operating system to the local system (where the Vix client is running). /// /// File location on the guest operating system. /// File location on the host operating system. public void CopyFileFromGuestToHost(string guestPathName, string hostPathName) { CopyFileFromGuestToHost(guestPathName, hostPathName, VMWareInterop.Timeouts.CopyFileTimeout); } /// /// Copies a file or directory from the guest operating system to the local system (where the Vix client is running). /// You must call LoginInGuest() before calling this procedure. /// Only absolute paths should be used for files in the guest; the resolution of relative paths is not specified. /// /// File location on the guest operating system. /// File location on the host operating system. /// Timeout in seconds. public void CopyFileFromGuestToHost(string guestPathName, string hostPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.CopyFileFromGuestToHost( guestPathName, hostPathName, 0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to copy file from guest to host: guestPathName=\"{0}\" hostPathName=\"{1}\" timeoutInSeconds={2}", guestPathName, hostPathName, timeoutInSeconds), ex); } } /// /// Creates a directory on the guest operating system. /// /// Directory location on the guest operating system. public void CreateDirectoryInGuest(string guestPathName) { CreateDirectoryInGuest(guestPathName, VMWareInterop.Timeouts.CreateDirectoryTimeout); } /// /// Creates a directory on the guest operating system. /// /// Directory location on the guest operating system. /// Timeout in seconds. public void CreateDirectoryInGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.CreateDirectoryInGuest( guestPathName, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to create directory in guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Creates a temp file on the guest operating system. /// /// Name of the temporary file created. public string CreateTempFileInGuest() { return CreateTempFileInGuest(VMWareInterop.Timeouts.CreateTempFileTimeout); } /// /// Creates a temp file on the guest operating system. /// /// Timeout in seconds. /// Name of the temporary file created. public string CreateTempFileInGuest(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.CreateTempFileInGuest( 0, null, callback), callback)) { return job.Wait(Constants.VIX_PROPERTY_JOB_RESULT_ITEM_NAME, timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to create temp file in guest: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Return information about a file or directory in the guest operating system. /// /// File or path in the guest operating system. /// Guest file information. public GuestFileInfo GetFileInfoInGuest(string guestPathName) { return GetFileInfoInGuest(guestPathName, VMWareInterop.Timeouts.GetFileInfoTimeout); } /// /// Return information about a file or directory in the guest operating system. /// /// File or path in the guest operating system. /// Timeout in seconds. /// Guest file information. public GuestFileInfo GetFileInfoInGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.GetFileInfoInGuest(guestPathName, callback), callback)) { object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_FILE_SIZE, Constants.VIX_PROPERTY_JOB_RESULT_FILE_FLAGS, Constants.VIX_PROPERTY_JOB_RESULT_FILE_MOD_TIME }; object[] propertyValues = job.Wait(properties, timeoutInSeconds); GuestFileInfo fileInfo = new GuestFileInfo(); fileInfo.GuestPathName = guestPathName; fileInfo.FileSize = (long)propertyValues[0]; fileInfo.Flags = (int)propertyValues[1]; fileInfo.LastModified = VMWareInterop.FromUnixEpoch((long)propertyValues[2]); return fileInfo; } } catch (Exception ex) { throw new Exception( string.Format("Failed to get file info in guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Runs a program in the guest operating system. /// /// Program to execute. /// Process information. public Process RunProgramInGuest(string guestProgramName) { return RunProgramInGuest(guestProgramName, string.Empty); } /// /// Run a program in the guest operating system. /// /// Additional command line arguments. /// Program to execute. /// Process information. public Process RunProgramInGuest(string guestProgramName, string commandLineArgs) { return RunProgramInGuest(guestProgramName, commandLineArgs, Constants.VIX_RUNPROGRAM_ACTIVATE_WINDOW, VMWareInterop.Timeouts.RunProgramTimeout); } /// /// Run a detached program in the guest operating system. /// /// Program to execute. /// Process information. public Process DetachProgramInGuest(string guestProgramName) { return DetachProgramInGuest(guestProgramName, string.Empty); } /// /// Run a detached program in the guest operating system. /// /// Program to execute. /// Additional command line arguments. /// Process information. public Process DetachProgramInGuest(string guestProgramName, string commandLineArgs) { return DetachProgramInGuest(guestProgramName, commandLineArgs, VMWareInterop.Timeouts.RunProgramTimeout); } /// /// Run a detached program in the guest operating system. /// /// Program to execute. /// Additional command line arguments. /// Timeout in seconds. /// Process information. public Process DetachProgramInGuest(string guestProgramName, string commandLineArgs, int timeoutInSeconds) { return RunProgramInGuest(guestProgramName, commandLineArgs, Constants.VIX_RUNPROGRAM_ACTIVATE_WINDOW | Constants.VIX_RUNPROGRAM_RETURN_IMMEDIATELY, timeoutInSeconds); } /// /// Run a program in the guest operating system. /// /// Guest program to run. /// Additional command line arguments. /// Timeout in seconds. /// Process information. public Process RunProgramInGuest(string guestProgramName, string commandLineArgs, int timeoutInSeconds) { return RunProgramInGuest(guestProgramName, commandLineArgs, 0, timeoutInSeconds); } /// /// Run a program in the guest operating system. /// /// Guest program to run. /// Additional command line arguments. /// Additional options, one of VIX_RUNPROGRAM_RETURN_IMMEDIATELY or VIX_RUNPROGRAM_ACTIVATE_WINDOW. /// Timeout in seconds. /// Process information. public Process RunProgramInGuest(string guestProgramName, string commandLineArgs, int options, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.RunProgramInGuest( guestProgramName, commandLineArgs, options, null, callback), callback)) { object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_ID, // Constants.VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_ELAPSED_TIME }; object[] propertyValues = job.Wait(properties, timeoutInSeconds); Process process = new Process(_handle); process.Name = Path.GetFileName(guestProgramName); process.Command = guestProgramName; if (!string.IsNullOrEmpty(commandLineArgs)) { process.Command += " "; process.Command += commandLineArgs; } process.ExitCode = (int)propertyValues[0]; process.Id = (long)propertyValues[1]; return process; } } catch (Exception ex) { throw new Exception( string.Format("Failed to run program in guest: guestProgramName=\"{0}\" commandLineArgs=\"{1}\"", guestProgramName, commandLineArgs), ex); } } /// /// Run a script in the guest operating system. /// /// The path to the script interpreter. /// The text of the script. /// Process information. public Process RunScriptInGuest(string interpreter, string scriptText) { return RunScriptInGuest(interpreter, scriptText, 0, VMWareInterop.Timeouts.RunScriptTimeout); } /// /// Detach a script in the guest operating system. /// /// The path to the script interpreter. /// The text of the script. /// Process information. public Process DetachScriptInGuest(string interpreter, string scriptText) { return DetachScriptInGuest(interpreter, scriptText, VMWareInterop.Timeouts.RunScriptTimeout); } /// /// Detach a script in the guest operating system. /// /// The path to the script interpreter. /// The text of the script. /// Timeout in seconds. /// Process information. public Process DetachScriptInGuest(string interpreter, string scriptText, int timeoutInSeconds) { return RunScriptInGuest(interpreter, scriptText, Constants.VIX_RUNPROGRAM_RETURN_IMMEDIATELY, timeoutInSeconds); } /// /// Run a script in the guest operating system. /// /// The path to the script interpreter. /// The text of the script. /// Run options for the program. /// Timeout in seconds. /// Process information. public Process RunScriptInGuest(string interpreter, string scriptText, int options, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.RunScriptInGuest( interpreter, scriptText, options, null, callback), callback)) { object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_ID, // Constants.VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_ELAPSED_TIME }; object[] propertyValues = job.Wait(properties, timeoutInSeconds); Process process = new Process(_handle); process.Name = Path.GetFileName(interpreter); process.Command = interpreter; process.ExitCode = (int)propertyValues[0]; process.Id = (long)propertyValues[1]; return process; } } catch (Exception ex) { throw new Exception( string.Format("Failed to run script in guest: interpreter=\"{0}\" scriptText=\"{1}\" options={2} timeoutInSeconds={3}", interpreter, scriptText, options, timeoutInSeconds), ex); } } /// /// Open a browser window on the specified URL in the guest operating system. /// /// The url to be opened. [Obsolete] public void OpenUrlInGuest(string url) { OpenUrlInGuest(url, VMWareInterop.Timeouts.OpenUrlTimeout); } /// /// Open a browser window on the specified URL in the guest operating system. /// /// The url to be opened. /// Timeout in seconds. [Obsolete] public void OpenUrlInGuest(string url, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.OpenUrlInGuest(url, 0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to open url in guest: url=\"{0}\" timeoutInSeconds={1}", url, timeoutInSeconds), ex); } } /// /// Tests the existence of a file in the guest operating system. /// /// Path to a file in the guest operating system. /// True if the file exists in the guest operating system. public bool FileExistsInGuest(string guestPathName) { return FileExistsInGuest(guestPathName, VMWareInterop.Timeouts.FileExistsTimeout); } /// /// Tests the existence of a file in the guest operating system. /// /// Path to a file in the guest operating system. /// Timeout in seconds. /// True if the file exists in the guest operating system. public bool FileExistsInGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.FileExistsInGuest( guestPathName, callback), callback)) { return job.Wait(Constants.VIX_PROPERTY_JOB_RESULT_GUEST_OBJECT_EXISTS, timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to check if file exists in guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Tests the existence of a directory in the guest operating system. /// /// Path to a directory in the guest operating system. /// True if the directory exists in the guest operating system. public bool DirectoryExistsInGuest(string guestPathName) { return DirectoryExistsInGuest(guestPathName, VMWareInterop.Timeouts.DirectoryExistsTimeout); } /// /// Tests the existence of a directory in the guest operating system. /// /// Path to a directory in the guest operating system. /// Timeout in seconds. /// True if the directory exists in the guest operating system. public bool DirectoryExistsInGuest(string guestPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.DirectoryExistsInGuest( guestPathName, callback), callback)) { return job.Wait(Constants.VIX_PROPERTY_JOB_RESULT_GUEST_OBJECT_EXISTS, timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to check if directory exists in guest: guestPathName=\"{0}\" timeoutInSeconds={1}", guestPathName, timeoutInSeconds), ex); } } /// /// Remove any guest operating system authentication context created by a previous call to LoginInGuest(), ie. Logout. /// public void LogoutFromGuest() { LogoutFromGuest(VMWareInterop.Timeouts.LogoutTimeout); } /// /// Remove any guest operating system authentication context created by a previous call to LoginInGuest(), ie. Logout. /// /// Timeout in seconds. public void LogoutFromGuest(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.LogoutFromGuest(callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to logout from guest: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Power off a virtual machine. The virtual machine will be powered off at the hardware level. /// Any state of the guest that has not been committed to disk will be lost. /// public void PowerOff() { PowerOff(Constants.VIX_VMPOWEROP_NORMAL, VMWareInterop.Timeouts.PowerOffTimeout); } /// /// Power off a virtual machine. The virtual machine will be powered off at the hardware level. /// Any state of the guest that has not been committed to disk will be lost. /// public void ShutdownGuest() { ShutdownGuest(VMWareInterop.Timeouts.PowerOffTimeout); } /// /// Power off a virtual machine. The virtual machine will be powered off at the hardware level. /// Any state of the guest that has not been committed to disk will be lost. /// /// Timeout in seconds. public void ShutdownGuest(int timeoutInSeconds) { PowerOff(Constants.VIX_VMPOWEROP_FROM_GUEST, timeoutInSeconds); } /// /// Power off or shutdown a virtual machine. /// If you call this function while the virtual machine is powered off or suspended, the operation will throw an /// exception with a VIX_E_VM_NOT_RUNNING error. /// /// Power-off options. Passing the VIX_VMPOWEROP_FROM_GUEST flag will cause the function /// to try to power off the guest OS. This will ensure a clean shutdown of the guest. This option requires that the /// VMware Tools be installed and running in the guest. If VIX_VMPOWEROP_NORMAL is passed as the "powerOffOptions" parameter, /// then the virtual machine will be powered off at the hardware level. Any state of the guest that has not been committed /// to disk will be lost. /// /// Timeout in seconds. public void PowerOff(int powerOffOptions, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.PowerOff(powerOffOptions, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to power off virtual machine: powerOffOptions={0} timeoutInSeconds={1}", powerOffOptions, timeoutInSeconds), ex); } } /// /// Hardware reset the virtual machine. /// public void Reset() { Reset(Constants.VIX_VMPOWEROP_NORMAL); } /// /// Hardware reset the virtual machine. /// /// Reset options. /// Passing VIX_VMPOWEROP_NORMAL will force a hardware reset. /// Passing VIX_VMPOWEROP_FROM_GUEST will attempt a clean shutdown of the guest operating system. /// public void Reset(int resetOptions) { Reset(resetOptions, VMWareInterop.Timeouts.ResetTimeout); } /// /// Reset a virtual machine. /// /// Reset options. /// Passing VIX_VMPOWEROP_NORMAL will force a hardware reset. /// Passing VIX_VMPOWEROP_FROM_GUEST will attempt a clean shutdown of the guest operating system. /// /// Timeout in seconds. public void Reset(int resetOptions, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Reset(resetOptions, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to reset virtual machine: resetOptions={0} timeoutInSeconds={1}", resetOptions, timeoutInSeconds), ex); } } /// /// Suspend the virtual machine. /// public void Suspend() { Suspend(VMWareInterop.Timeouts.SuspendTimeout); } /// /// Suspend a virtual machine. /// /// Timeout in seconds. public void Suspend(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Suspend(0, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to suspend virtual machine: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Pause the virtual machine. /// public void Pause() { Pause(VMWareInterop.Timeouts.PauseTimeout); } /// /// Pause a virtual machine. /// This stops execution of the virtual machine. /// Call Unpause to continue execution of the virtual machine. /// /// Timeout in seconds. public void Pause(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Pause(0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to pause virtual machine: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Continue execution of a virtual machine that was stopped using Pause. /// public void Unpause() { Unpause(VMWareInterop.Timeouts.UnpauseTimeout); } /// /// Continue execution of a virtual machine that was stopped using Pause. /// /// Timeout in seconds. public void Unpause(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Unpause(0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to unpause virtual machine: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// List files in the guest operating system. /// /// Path in the guest operating system to list. /// Recruse into subdirectories. /// A list of files and directories with full paths. public List ListDirectoryInGuest(string pathName, bool recurse) { return ListDirectoryInGuest(pathName, recurse, VMWareInterop.Timeouts.ListDirectoryTimeout); } /// /// List files in the guest operating system. /// /// Path in the guest operating system to list. /// Recruse into subdirectories. /// Timeout in seconds. /// /// The function throws an exception if pathName doesn't exist. /// /// A list of files and directories with full paths. public List ListDirectoryInGuest(string pathName, bool recurse, int timeoutInSeconds) { // ListDirectoryInGuest behaves differently on VMWare Workstation (returns empty list) and // ESX (throws an exception) for directories or files that don't exist. if (!DirectoryExistsInGuest(pathName)) throw new VMWareException(2); try { List results = new List(); VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.ListDirectoryInGuest( pathName, 0, callback), callback)) { object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_ITEM_NAME, Constants.VIX_PROPERTY_JOB_RESULT_FILE_FLAGS }; try { foreach (object[] fileProperties in job.YieldWait(properties, timeoutInSeconds)) { string fileName = (string)fileProperties[0]; int flags = (int)fileProperties[1]; if ((flags & 1) > 0) { if (recurse) { results.AddRange(ListDirectoryInGuest(Path.Combine(pathName, fileName), true, timeoutInSeconds)); } } else { results.Add(Path.Combine(pathName, fileName)); } } } catch (VMWareException ex) { switch (ex.ErrorCode) { case 2: // file not found? empty directory in ESX case Constants.VIX_E_UNRECOGNIZED_PROPERTY: // unrecognized property returned by GetNumProperties, the directory exists, but contains no files break; default: throw; } } } return results; } catch (Exception ex) { throw new Exception( string.Format("Failed to list directory in guest: pathName=\"{0}\" recurse={1} timeoutInSeconds={2}", pathName, recurse, timeoutInSeconds), ex); } } /// /// An environment variable in the guest of the VM. On a Windows NT series guest, writing these /// values is saved persistently so they are immediately visible to every process. On a Linux or Windows 9X guest, /// writing these values is not persistent so they are only visible to the VMware tools process. /// public VariableIndexer GuestEnvironmentVariables { get { return _guestEnvironmentVariables; } } /// /// A "Guest Variable". This is a runtime-only value; it is never stored persistently. /// This is the same guest variable that is exposed through the VMControl APIs, and is a simple /// way to pass runtime values in and out of the guest. /// VMWare doesn't publish a list of known variables, the following guest variables have been observed. /// /// ip: IP address of the guest operating system. /// /// public VariableIndexer GuestVariables { get { return _guestVariables; } } /// /// The configuration state of the virtual machine. This is the .vmx file that is stored on the host. /// You can read this and it will return the persistent data. If you write to this, it will only be a /// runtime change, so changes will be lost when the VM powers off. /// public VariableIndexer RuntimeConfigVariables { get { return _runtimeConfigVariables; } } /// /// Shared folders on this virtual machine. /// public VMWareSharedFolderCollection SharedFolders { get { return _sharedFolders; } } /// /// Captures the screen of the guest operating system. /// /// A object holding the captured screen image. public Image CaptureScreenImage() { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.CaptureScreenImage( Constants.VIX_CAPTURESCREENFORMAT_PNG, null, callback), callback)) { byte[] imageBytes = job.Wait( Constants.VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_DATA, VMWareInterop.Timeouts.CaptureScreenImageTimeout); return Image.FromStream(new MemoryStream(imageBytes)); } } catch (Exception ex) { throw new Exception("Failed to capture screen image", ex); } } /// /// Running processes in the guest operating system. /// public VMWareProcessCollection GuestProcesses { get { try { VMWareProcessCollection processes = new VMWareProcessCollection(); VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.ListProcessesInGuest( 0, callback), callback)) { object[] properties = { Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_ID, Constants.VIX_PROPERTY_JOB_RESULT_ITEM_NAME, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_OWNER, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_START_TIME, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_COMMAND, Constants.VIX_PROPERTY_JOB_RESULT_PROCESS_BEING_DEBUGGED, }; foreach (object[] processProperties in job.YieldWait(properties, VMWareInterop.Timeouts.ListProcessesTimeout)) { Process process = new Process(_handle); process.Id = (long)processProperties[0]; process.Name = (string)processProperties[1]; process.Owner = (string)processProperties[2]; process.StartDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((int)processProperties[3]); process.Command = (string)processProperties[4]; process.IsBeingDebugged = (bool)processProperties[5]; processes.Add(process.Id, process); } return processes; } } catch (Exception ex) { throw new Exception("Failed to list processes in guest", ex); } } } /// /// Returns true if the virtual machine is in the process of recording. /// public bool IsRecording { get { return GetProperty(Constants.VIX_PROPERTY_VM_IS_RECORDING); } } /// /// Returns true if the virtual machine is in the process of replaying. /// public bool IsReplaying { get { return GetProperty(Constants.VIX_PROPERTY_VM_IS_REPLAYING); } } /// /// Records a virtual machine's activity as a snapshot object. /// /// Snapshot name. /// Resulting snapshot. public VMWareSnapshot BeginRecording(string name) { return BeginRecording(name, string.Empty); } /// /// Records a virtual machine's activity as a snapshot object. /// /// Snapshot name. /// Snapshot description. /// Resulting snapshot. public VMWareSnapshot BeginRecording(string name, string description) { return BeginRecording(name, description, VMWareInterop.Timeouts.RecordingTimeout); } /// /// Records a virtual machine's activity as a snapshot object. /// /// Snapshot name. /// Snapshot description. /// Timeout in seconds. /// Resulting snapshot. public VMWareSnapshot BeginRecording(string name, string description, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.BeginRecording(name, description, 0, null, callback), callback)) { VMWareSnapshot snapshot = new VMWareSnapshot(_handle, job.Wait(Constants.VIX_PROPERTY_JOB_RESULT_HANDLE, timeoutInSeconds), null); _snapshots.Add(snapshot); return snapshot; } } catch (Exception ex) { throw new Exception( string.Format("Failed to begin recording: name=\"{0}\" description=\"{1}\" timeoutInSeconds={2}", name, description, timeoutInSeconds), ex); } } /// /// This function stops recording a virtual machine's activity. /// public void EndRecording() { EndRecording(VMWareInterop.Timeouts.RecordingTimeout); } /// /// This function stops recording a virtual machine's activity. /// /// Timeout in seconds. public void EndRecording(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.EndRecording( 0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to end recording: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Upgrades the virtual hardware version of the virtual machine to match the version of the VIX library. /// This has no effect if the virtual machine is already at the same version or at a newer version than the VIX library. /// public void UpgradeVirtualHardware() { UpgradeVirtualHardware(VMWareInterop.Timeouts.UpgradeVirtualHardwareTimeout); } /// /// Upgrades the virtual hardware version of the virtual machine to match the version of the VIX library. /// This has no effect if the virtual machine is already at the same version or at a newer version than the VIX library. /// /// Timeout in seconds. public void UpgradeVirtualHardware(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.UpgradeVirtualHardware( 0, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to upgrade virtual hardware: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Creates a copy of the virtual machine at current state. /// /// Virtual Machine clone type. /// The path name of the virtual machine configuration file that will be created. public void Clone(VMWareVirtualMachineCloneType cloneType, string destConfigPathName) { Clone(cloneType, destConfigPathName, VMWareInterop.Timeouts.CloneTimeout); } /// /// Creates a copy of the virtual machine at current state. /// /// Virtual Machine clone type. /// The path name of the virtual machine configuration file that will be created. /// Timeout in seconds. public void Clone(VMWareVirtualMachineCloneType cloneType, string destConfigPathName, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Clone( null, (int)cloneType, destConfigPathName, 0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to clone virtual machine: cloneType=\"{0}\" destConfigPathName=\"{1}\" timeoutInSeconds={2}", Enum.GetName(cloneType.GetType(), cloneType), destConfigPathName, timeoutInSeconds), ex); } } /// /// Permanently deletes a virtual machine from the host system. /// /// /// Does not delete all associated files. /// public void Delete() { Delete(0, VMWareInterop.Timeouts.DeleteTimeout); } /// /// Permanently deletes a virtual machine from the host system. /// /// Delete options. /// /// VixCOM.Constants.VIX_VMDELETE_DISK_FILES: delete all associated files. /// /// public void Delete(int deleteOptions) { Delete(deleteOptions, VMWareInterop.Timeouts.DeleteTimeout); } /// /// Permanently deletes a virtual machine from the host system. /// /// /// /// VixCOM.Constants.VIX_VMDELETE_DISK_FILES: delete all associated files. /// /// /// Timeout in seconds. public void Delete(int deleteOptions, int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.Delete(deleteOptions, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to delete virtual machine: deleteOptions={0} timeoutInSeconds={1}", deleteOptions, timeoutInSeconds), ex); } } /// /// Prepares to install VMware Tools on the guest operating system. /// /// /// Prepares an ISO image to install VMware Tools on the guest operating system. /// If autorun is enabled, as it often is on Windows, installation begins, otherwise /// you must initiate installation. If VMware Tools is already installed, this function /// prepares to upgrade it to the version matching the product. /// public void InstallTools() { InstallTools(VMWareInterop.Timeouts.InstallToolsTimeout); } /// /// Prepares to install VMware Tools on the guest operating system. /// /// /// Prepares an ISO image to install VMware Tools on the guest operating system. /// If autorun is enabled, as it often is on Windows, installation begins, otherwise /// you must initiate installation. If VMware Tools is already installed, this function /// prepares to upgrade it to the version matching the product. /// /// Timeout in seconds. public void InstallTools(int timeoutInSeconds) { try { VMWareJobCallback callback = new VMWareJobCallback(); using (VMWareJob job = new VMWareJob(_handle.InstallTools(0, null, callback), callback)) { job.Wait(timeoutInSeconds); } } catch (Exception ex) { throw new Exception( string.Format("Failed to install tools: timeoutInSeconds={0}", timeoutInSeconds), ex); } } /// /// Dispose the virtual machine object. /// public override void Dispose() { _guestVariables = null; _runtimeConfigVariables = null; _guestEnvironmentVariables = null; if (_snapshots != null) { _snapshots.Dispose(); _snapshots = null; } _sharedFolders = null; base.Dispose(); } } }