nrvr.vm.vmware
index
/usr/lib/python2.7/site-packages/nrvr/vm/vmware.py

nrvr.vm.vmware - Create and manipulate VMware virtual machines
 
Classes provided by this module include
VmdkFile
VmxFileContent
VmxFile
VMwareHypervisor
VMwareMachine
 
The file path of the .vmx file is used as identifier,
which seems reasonably consistent with VMware APIs.
What really is used is the normalized, absolutized, possibly expanded::
 
    os.path.abspath(os.path.expanduser(vmxFilePath))
 
Files related to a machine are essentially expected to be in the same directory.
 
The purpose is automation.
The purpose isn't to support all features of the hypervisor.
As implemented only known to support VMware Workstation 9, VMware Player 5, and VMware Fusion 5.
As implemented requires vmrun, which is known to be available when installing VMware VIX 1.12.
As implemented only tested with VMware Workstation 9.0.2, VMware Player 5.0.2, VIX 1.12.2, and VMware Fusion 5.0.3.
Should work with newer versions VMware Workstation, VMware Player, and VIX.
Other hypervisors may be added as needed.
 
As implemented works in Linux.
As implemented requires vmrun, and vmware-vdiskmanager or qemu-img commands.
Nevertheless essential.  To be improved as needed.
 
Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
 
Contributor - Nora Baschy
 
Public repository - https://github.com/srguiwiz/nrvr-commander
 
Copyright (c) Nirvana Research 2006-2015.
Simplified BSD License

 
Modules
       
codecs
os
re
shutil
sys
tempfile
time

 
Classes
       
__builtin__.object
VMwareHypervisor
VMwareMachine
VmdkFile
VmxFile
VmxFileContent

 
class VMwareHypervisor(__builtin__.object)
    A VMware hypervisor.
 
  Methods defined here:
__init__(self, hostType)
Create new VMware hypervisor descriptor.
cloneSnapshot(self, vmxFilePath, snapshot, clonedVmxFilePath, linked=True, tolerateRunning=False)
Create clone of virtual machine at snapshot.
 
As implemented raises exception if running, unless asked to tolerate.
 
linked
    whether to create a linked clone or a full clone.
createSnapshot(self, vmxFilePath, snapshot, tolerateRunning=False, tolerateDuplicate=False)
Create new snapshot of virtual machine.
 
As implemented raises exception if running or if duplicate name,
unless asked to tolerate.
 
As implemented omits leading and trailing whitespace if any.
deleteDescendantsOfSnapshot(self, vmxFilePath, snapshot)
Delete descendants of snapshot of virtual machine.
 
Keeps snapshot.
 
As implemented raises exception if running.
deleteSnapshot(self, vmxFilePath, snapshot, andDeleteChildren=False, tolerateRunning=False)
Delete snapshot of virtual machine.
 
As implemented raises exception if running, unless asked to tolerate.
isRunning(self, vmxFilePath)
Return whether .vmx file listed as running.
listRunning(self)
Return list of paths of .vmx files of all running virtual machines.
listSnapshots(self, vmxFilePath)
Return list of snapshots of virtual machine.
 
As implemented omits leading and trailing whitespace if any.
local = <nrvr.vm.vmware.VMwareHypervisor object> localHostOnlyIPAddress = '172.16.224.1'
notRunningRequired(self, vmxFilePath)
Raises exception if .vmx file listed as running.
revertToSnapshot(self, vmxFilePath, snapshot, tolerateRunning=False)
Revert to snapshot of virtual machine.
 
As implemented raises exception if running, unless asked to tolerate.
revertToSnapshotAndDeleteDescendants(self, vmxFilePath, snapshot)
Revert to snapshot of virtual machine and delete any and all descendants of snapshot.
 
As implemented raises exception if running.
sleepUntilNotRunning(self, vmxFilePath, checkIntervalSeconds=5.0, ticker=False)
If not running return, else loop sleeping for checkIntervalSeconds.
start(self, vmxFilePath, gui=False, extraSleepSeconds=10.0)
Start virtual machine.
 
extraSleepSeconds
    extra time for this process to sleep while virtual machine is starting up,
    unless None.
startAndStopWithIdeDrivesDisabled(self, vmxFilePath, gui=False, extraSleepSeconds=3.0)
Start and stop virtual machine while all virtual IDE drives are disabled.
 
The raison d'etre of this method is,
generated MAC addresses are available only after first start of a virtual machine.
 
extraSleepSeconds
    extra time for this process to sleep while virtual machine is starting up,
    unless None.
stop(self, vmxFilePath, hard=False, tolerateNotRunning=True, extraSleepSeconds=7.0)
Stop virtual machine.
 
Ideally virtual machines would stop from shutting down from within the virtual machine
to ensure proper shutdown.
If VMware Tools are installed then a soft stop should effect such shutting down from within.
 
If VMware Tools isn't installed then other mechanisms, e.g. issuing a command over ssh
would seem appropriate.
 
After some tasks, e.g. after a properly configured operating system install with kickstart,
a machine should shut down by itself.
 
A hard stop appears to be the least desirable option, even though it has the highest
probability of succeeding at stopping the virtual machine it also has the highest
probability of leaving behind virtual disk content as if after a crash.
 
extraSleepSeconds
    extra time for this process to sleep after stopping virtual machine,
    unless None.

Class methods defined here:
commandsUsedInImplementation(cls) from __builtin__.type
Return a list to be passed to SystemRequirements.commandsRequired().
 
This class can be passed to SystemRequirements.commandsRequiredByImplementations().
localHostType(cls) from __builtin__.type
Determine and return host type of VMware hypervisor available locally.
localNotRunningRequired(cls, vmxFilePath) from __builtin__.type
May raise exception if .vmx file locally listed as running.
 
Only checks::
 
    VMwareHypervisor.local.notRunningRequired(vmxFilePath)
 
Not perfect.  Nevertheless can help avoid trouble.
localRequired(cls) from __builtin__.type
Raises exception if no supported VMware hypervisor available locally.
snapshotsRequired(cls) from __builtin__.type
Raises exception if not supporting snapshots in VMware hypervisor available locally.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
hostCapabilities
Host list of capabilities of VMware hypervisor.
 
As little as an empty list for VMware Player.
As much as [VMwareHypervisor.SNAPSHOTS, VMwareHypervisor.CLONING] for VMware Workstation.
Regrettably [VMwareHypervisor.SNAPSHOTS] only for VMware Fusion.
hostType
Host type of VMware hypervisor.
suggestedDirectory
Suggest a parent directory for virtual machine directories.
 
For those who don't want to decide themselves.

Data and other attributes defined here:
CLONING = 'cloning'
PLAYER = 'player'
SNAPSHOTS = 'snapshots'
UNKNOWN = 'unknown'
WORKSTATION = 'ws'

 
class VMwareMachine(__builtin__.object)
    A VMware virtual machine.
 
  Methods defined here:
__init__(self, vmxFilePath)
Create new VMware virtual machine descriptor.
 
A descriptor can describe a VMware virtual machine that does or doesn't yet exist on the host disk.
acceptKnownHostKey(self, user=None)
Accept host's key.
 
Will wait until completed.
 
Assumes .ports file to exist and to have at least one entry for ssh for the user.
 
Needs virtual machine to be running already, ready to accept ssh connections, duh.
 
user
    a string.
    
    If None then any.
create(self, memsizeMegabytes=512, guestOS='centos', ideDrives=None, template='#!/usr/bin/vmware\n.encoding = "UTF-8"\nconfig.ver... automatically answer all questions when booting\n')
Create a VMware virtual machine.
 
For some parameters see documentation of class VmxFile method create.
 
As implemented only supports a limited number of features.
Nevertheless essential.  To be improved as needed.
hasAcceptedKnownHostKey(self, user=None)
Return whether attempts to acceptKnownHostKey() succeed.
 
Will wait until completed with success or failure.
 
Assumes .ports file to exist and to have at least one entry for ssh for the user.
 
user
    a string.
    
    If None then any.
 
return
    whether success.
listOfSshParametersForAcceptingKnownHostKey(self, user='root')
Return a list to use for accepting host's key.
 
No duplicates.
 
Assumes .ports file to exist and to have at least one entry for ssh for the user.
 
user
    a string.
    
    If None then any.
 
return
    a list of SshParameters instances.
mkdir(self, mode=493)
Create directory .vmx file will be in.
 
Useful to have directory to put other files into early.
remove(self)
Remove (delete) VMware virtual machine from the host disk.
 
As implemented completely deletes the directory containing the .vmx file,
which often is correct but not necessarily always.
scpGetCommand(self, fromGuestPath, toHostPath, guestUser='root', recurseDirectories=False, preserveTimes=True)
Return an ScpCommand instance.
 
Will wait until completed.
 
Assumes .ports file to exist and to have an entry for ssh for the user.
 
Needs virtual machine to be running already, ready to accept ssh connections, duh.
scpPutCommand(self, fromHostPath, toGuestPath, guestUser='root', preserveTimes=True)
Return an ScpCommand instance.
 
Will wait until completed.
 
Assumes .ports file to exist and to have an entry for ssh for the user.
 
Needs virtual machine to be running already, ready to accept ssh connections, duh.
shutdownCommand(self, firstSleepSeconds=5.0, extraSleepSeconds=7.0, ignoreException=False)
Send shutdown command.
 
Assumes .ports file to exist and to have an entry for shutdown.
 
Needs virtual machine to be running already, ready to accept ssh connections, duh.
 
Example use::
 
    vmwareMachine1.shutdownCommand()
    VMwareHypervisor.local.sleepUntilNotRunning(vmwareMachine1.vmxFilePath, ticker=True)
 
firstSleepSeconds
    time for this process to sleep before shutting down virtual machine,
    unless None.
 
extraSleepSeconds
    extra time for this process to sleep after shutting down virtual machine,
    unless None.
sleepUntilHasAcceptedKnownHostKey(self, user=None, checkIntervalSeconds=3.0, ticker=False, extraSleepSeconds=5.0)
If available return, else loop sleeping for checkIntervalSeconds.
 
Assumes .ports file to exist and to have at least one entry for ssh for the user.
 
user
    a string.
    
    If None then any.
sleepUntilSshIsAvailable(self, checkIntervalSeconds=3.0, ticker=False, user='root', probingCommand='hostname', extraSleepSeconds=5.0)
If available return, else loop sleeping for checkIntervalSeconds.
 
Assumes .ports file to exist and to have an entry for ssh for the user.
sshCommand(self, argv, user='root', exceptionIfNotZero=True, maxConnectionRetries=10, tickerForRetry=True)
Return an SshCommand instance.
 
Will wait until completed.
 
Output may contain extraneous leading or trailing newlines and whitespace.
 
Example use::
 
    sshCommand1 = vmwareMachine.sshCommand(["ls", "-al"])
    print "output=" + sshCommand1.output
 
Assumes .ports file to exist and to have an entry for ssh for the user.
 
Needs virtual machine to be running already, ready to accept ssh connections, duh.
 
argv
    list of command and arguments passed to ssh.
    
    Can accept a string instead of a list.
 
user
    a string.
sshIsAvailable(self, user=None, probingCommand='hostname')
Return whether probingCommand succeeds.
 
Will wait until completed.
 
Assumes .ports file to exist and to have an entry for ssh for the user.
 
user
    a string.
    
    If None then any.
 
return
    whether success.
sshParameters(self, user='root')
Return SshParameters instance for user.
 
Assumes .ports file to exist and to have an entry for ssh for the user.
 
user
    a string.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
basenameStem
Stem of basename of .vmx file.
 
Used as default for displayName.
Useful for making names of related files.
directory
Directory .vmx file is in.
portsFile
A PortsFile instance.
 
If needed.
regularUser
A regular user.
Often the main user.
 
Can be None.
vmxFile
A VmxFile instance.
 
If needed.
vmxFilePath
Path of the .vmx file.

 
class VmdkFile(__builtin__.object)
    A .vmdk file for VMware.
 
  Methods defined here:
__init__(self, vmdkFilePath)
Create new .vmdk file descriptor.
 
A descriptor can describe a .vmdk file that does or doesn't yet exist on the host disk.
compliantDiskSize(self, megabytes=1000)
Disk size must be a multiple of 4.
 
If necessary rounds up to next multiple of 4.
 
Is megabytes.
create(self, megabytes=1000, preallocated=False)
Create a .vmdk file.
 
As implemented only supports a limited number of features.
Nevertheless essential.  To be improved as needed.
exists(self)
Return True if file exists on the host disk.

Class methods defined here:
commandsUsedInImplementation(cls) from __builtin__.type
Return a list to be passed to SystemRequirements.commandsRequired().
 
This class can be passed to SystemRequirements.commandsRequiredByImplementations().

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
vmdkFilePath
Path of the .vmdk file.

 
class VmxFile(__builtin__.object)
    A .vmx file for VMware.
 
  Methods defined here:
__init__(self, vmxFilePath)
Create new .vmx file descriptor.
 
A descriptor can describe a .vmx file that does or doesn't yet exist on the host disk.
create(self, memsizeMegabytes=512, guestOS='centos', ideDrives=None, displayName=None, template='#!/usr/bin/vmware\n.encoding = "UTF-8"\nconfig.ver... automatically answer all questions when booting\n')
Create a .vmx file.
 
As implemented only supports a limited number of features.
Nevertheless essential.  To be improved as needed.
 
ideDrives
    a list of at most four VmdkFile or IsoImage.
    If given a number as an element then make a VmdkFile with that many megabytes capactiy.
    If None then default to one VmdkFile with 40000 megabytes capacity.
 
displayName
    defaults to self.basenameStem.
 
template
    a string.
disableAllIdeDrives(self)
Disable all virtual IDE drives, while keeping them for later enabling again.
enableAllIdeDrives(self)
Enable all virtual IDE drives again.
exists(self)
Return True if file exists on the host disk.
getEthernetMacAddress(self, adapter=0)
Get MAC address of a virtual Ethernet adapter.
 
Generated MAC addresses are available only after first start of a virtual machine.
 
As implemented forces reading of vmxFile, in case of change after first start of virtual machine.
 
return
    e.g. "01:23:45:67:89:ab", or None.
modify(self, vmxFileContentModifyingMethod)
Recommended safe wrapper to modify .vmx file.
 
May raise exception if .vmx file locally listed as running.
removeAllIdeCdromImages(self)
Remove all .vmx file parameters for all virtual IDE CD-ROM drives served from image files.
setAccelerate3D(self, accelerate3D=True)
Set .vmx file parameter for enabling accelerated 3D graphics.
 
accelerate3D
    whether to accelerate 3D graphics.
setEthernetAdapter(self, adapter=0, connectionType='bridged', change='enable')
Set .vmx file parameters for a virtual Ethernet adapter.
 
connectionType
    "bridged", "hostonly", or "nat".
 
change
    "enable", "disable", or "remove".
setIdeCdromIsoFile(self, pathOnHost, bus=0, device=0)
Set .vmx file parameters for a virtual IDE CD-ROM drive served from an .iso image file.
setMemorySize(self, memsizeMegabytes)
Set .vmx file parameter for memory size.
 
memsizeMegabytes
    memory size in megabytes.  E.g. 1000.
    
    Will be rounded up to a multiple of 4, if necessary.
setNumberOfProcessorCores(self, cores=1, processors=1)
Set .vmx file parameters for number of processor cores.
 
cores
    e.g. 2.
 
processors
    e.g. 1.
setVideoMemorySize(self, vramSizeMegabytes)
Set .vmx file parameter for video RAM size.
 
vramSizeMegabytes
    video RAM size in megabytes.  E.g. 64.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
basenameStem
Stem of basename of .vmx file.
 
Used as default for displayName.
Useful for making names of related files.
directory
Directory .vmx file is in.
vmxFileContent
A VmxFileContent instance.
 
If not exists() may be None.
 
Auxiliary.
vmxFilePath
Path of the .vmx file.

 
class VmxFileContent(__builtin__.object)
    The text content of a .vmx file for VMware.
 
VMware describes the .vmx file as the primary configuration file.
 
  Methods defined here:
__init__(self, string)
Create new .vmx file content container.
 
Does unicode(string), as befits the 21st century.
disableAllIdeDrives(self)
Disable all virtual IDE drives, while keeping them for later enabling again.
 
As implemented sets all .vmx file parameters ide*:*.present="FALSE".
enableAllIdeDrives(self)
Enable all virtual IDE drives again.
 
As implemented sets all .vmx file parameters ide*:*.present="TRUE".
getEthernetMacAddress(self, adapter=0)
Get MAC address of a virtual Ethernet adapter.
 
Generated MAC addresses are available only after first start of a virtual machine.
 
return
    e.g. "01:23:45:67:89:ab", or None.
getSettingValue(self, name)
Get setting value.
 
If no setting by that name then return None.
 
If double quoted then return without double quotes.
 
return
    value as string, or None.
normalizeLineRuns(self)
Normalize empty line runs.
 
One empty line is made from two newlines.  Reduce any more than two down to two.
 
At the end make exactly two newlines, so that lines added by VMware will be separated.
 
Auxiliary.
removeAllIdeCdromImages(self)
Remove all .vmx file parameters for all virtual IDE CD-ROM drives served from image files.
removeIdeDrive(self, bus=0, device=0)
Remove all .vmx file parameters for a virtual IDE drive.
removeSetting(self, name)
Remove a setting.
removeSettingsStartingWith(self, prefix)
Remove settings having prefix in front of name.
replaceSettingValue(self, name, newValue, placeholder=None)
Replace one setting value.
 
Tolerates string or number for newValue because it does unicode(newValue).
 
As implemented would have problems with backslash escapes in newValue.
Don't use \ in newValue.
 
E.g. if original containts a line::
 
    memsize="_MEMSIZE_" # megabytes, must be multiple of 4
 
then would call::
 
    vmxFile.replaceSettingValue("memsize", 256, "_MEMSIZE_")
setAccelerate3D(self, accelerate3D=True)
Set .vmx file parameter for enabling accelerated 3D graphics.
 
accelerate3D
    whether to accelerate 3D graphics.
setEthernetAdapter(self, adapter=0, connectionType='bridged', change='enable')
Set .vmx file parameters for a virtual Ethernet adapter.
 
connectionType
    "bridged", "hostonly", or "nat".
 
change
    "enable", "disable", or "remove".
 
E.g.::
 
    ethernet0.present = "TRUE"
    ethernet0.connectionType = "bridged"
    ethernet0.virtualDev = "e1000"
    ethernet0.startConnected = "TRUE"
    ethernet0.wakeOnPcktRcv = "FALSE"
    ethernet0.allowGuestConnectionControl = "FALSE"
    ethernet0.disableMorphToVmxnet = "TRUE"
setIdeCdromIsoFile(self, pathOnHost, bus=0, device=0)
Set .vmx file parameters for a virtual IDE CD-ROM drive served from an .iso image file.
setIdeDiskVmdkFile(self, pathOnHost, bus=0, device=0)
Set .vmx file parameters for a virtual IDE hard disk drive served from a .vmdk disk file.
setIdeDrive(self, pathOnHost, deviceType, bus=0, device=0)
Set .vmx file parameters for a virtual IDE drive served from a file.
 
pathOnHost
    can be relative.
 
E.g.::
 
    ide0:0.present = "TRUE"
    ide0:0.deviceType = "disk"
    ide0:0.fileName = "demomachine01-0.vmdk"
setMemorySize(self, memsizeMegabytes)
Set .vmx file parameter for memory size.
 
memsizeMegabytes
    memory size in megabytes.  E.g. 1000.
    
    Will be rounded up to a multiple of 4, if necessary.
setNumberOfProcessorCores(self, cores=1, processors=1)
Set .vmx file parameters for number of processor cores.
 
cores
    e.g. 2.
 
processors
    e.g. 1.
setSettingValue(self, name, newValue, extraEmptyLine=False)
Replace one setting value or create and append that setting.
 
See method replaceSettingValue.
setVideoMemorySize(self, vramSizeMegabytes)
Set .vmx file parameter for video RAM size.
 
vramSizeMegabytes
    video RAM size in megabytes.  E.g. 64.

Class methods defined here:
compliantMemsize(cls, given) from __builtin__.type
.vmx file parameter memsize must be a multiple of 4.
 
If necessary rounds up to next multiple of 4.
 
Unit is megabytes.
ethernetSettingPrefix(cls, adapter=0) from __builtin__.type
.vmx file parameters for Ethernet adapters have a naming convention.
 
Return e.g. "ethernet0" for adapter=0.
ideBusDevice(cls, driveNumber) from __builtin__.type
Return IDE bus 0 or 1 device 0 or 1 for IDE drive number 0, 1, 2 or 3.
 
Return e.g. (0,0).
ideDriveNumber(cls, bus, device) from __builtin__.type
For IDE bus 0 or 1 device 0 or 1 return IDE drive number 0, 1, 2 or 3.
 
Return e.g. 0.
ideSettingPrefix(cls, bus=0, device=0) from __builtin__.type
.vmx file parameters for IDE drives have a naming convention.
 
Return e.g. "ide0:0" for bus=0 and device=0.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
newline
Sample which kind of newline.

Data and other attributes defined here:
newlineRegex = <_sre.SRE_Pattern object>