本文整理汇总了Python中psphere.managedobjects.VirtualMachine类的典型用法代码示例。如果您正苦于以下问题:Python VirtualMachine类的具体用法?Python VirtualMachine怎么用?Python VirtualMachine使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VirtualMachine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: vsphere_check_with_api
def vsphere_check_with_api(api, run_time, text):
"""Uses api to perform checking of vms on vsphere-type provider.
Args:
api: api endpoint to vsphere
run_time: when this run time is exceeded for the VM, it will be deleted
text: when this string is found in the name of VM, it may be deleted
"""
vms = VirtualMachine.all(api.api)
vms_to_delete = []
templates_to_delete = []
nightly_templates = [VirtualMachine.get(api.api, name=x)
for x in api.list_template() if "miq-nightly" in x]
nightly_templates.sort(key=lambda x: datetime.datetime.strptime(x.name[-12:], "%Y%m%d%H%M"))
if len(nightly_templates) > MRU_NIGHTLIES:
for template in nightly_templates[:-MRU_NIGHTLIES]:
templates_to_delete.append(template.name)
for vm in vms:
vm_name = vm.name
running_for = vm.summary.quickStats.uptimeSeconds / SEC_IN_DAY
if running_for >= run_time and is_affected(vm_name, text):
print("To delete: {} with runtime: {}".format(vm_name, running_for))
vms_to_delete.append(vm_name)
return (vms_to_delete, templates_to_delete)
示例2: check_template_exists
def check_template_exists(hostname, username, password, name):
client = Client(server=hostname, username=username, password=password)
try:
VirtualMachine.get(client, name=name)
print "VSPHERE: A Machine with that name already exists"
except ObjectNotFoundError:
return False
client.logout()
return True
示例3: get_host
def get_host(self, hostname):
'''
Read info about a specific host or VM from cache or VMware API.
'''
inv = self._get_cache(hostname, None)
if inv is not None:
return inv
if not self.guests_only:
try:
host = HostSystem.get(self.client, name=hostname)
inv = self._get_host_info(host)
except ObjectNotFoundError:
pass
if inv is None:
try:
vm = VirtualMachine.get(self.client, name=hostname)
inv = self._get_vm_info(vm)
except ObjectNotFoundError:
pass
if inv is not None:
self._put_cache(hostname, inv)
return inv or {}
示例4: changevmMemory
def changevmMemory(self,vm_name,memory):
try:
new_config = self.client.create("VirtualMachineConfigSpec")
new_config.memoryMB = memory
vm = VirtualMachine.get(self.client, name=vm_name)
print("Reconfiguring %s" % vm_name)
if vm.config.hardware.memoryMB== vm_name:
print("Not reconfiguring %s as it already has %s memory" % (vm_name,memory))
sys.exit()
task = vm.ReconfigVM_Task(spec=new_config)
while task.info.state in ["queued", "running"]:
print("Waiting 5 more seconds for VM starting")
time.sleep(5)
task.update()
if task.info.state == "success":
elapsed_time = task.info.completeTime - task.info.startTime
print("Successfully reconfigured VM %s. Server took %s seconds." %
(vm_name, elapsed_time.seconds))
elif task.info.state == "error":
print("ERROR: The task for reconfiguring the VM has finished with"
" an error. If an error was reported it will follow.")
print("ERROR: %s" % task.info.error.localizedMessage)
except VimFault, e:
print("Failed to reconfigure %s: " % e)
sys.exit()
示例5: upload_ova
def upload_ova(hostname, username, password, name, datastore,
cluster, datacenter, url, host):
client = Client(server=hostname, username=username, password=password)
try:
VirtualMachine.get(client, name=name)
print "VSPHERE: A Machine with that name already exists"
sys.exit(127)
except ObjectNotFoundError:
pass
client.logout()
cmd_args = ['ovftool']
cmd_args.append("--datastore=%s" % datastore)
cmd_args.append("--name=%s" % name)
cmd_args.append("--vCloudTemplate=True")
cmd_args.append(url)
cmd_args.append("vi://%[email protected]%s/%s/host/%s" % (username, hostname, datacenter, cluster))
print "VSPHERE: Running OVFTool..."
proc = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out_string = ""
while "'yes' or 'no'" not in out_string and "Password:" not in out_string:
out_string += proc.stdout.read(1)
if "'yes' or 'no'" in out_string:
proc.stdin.write("yes\n")
proc.stdin.flush()
print "VSPHERE: Added host to SSL hosts"
out_string = ""
while "Password:" not in out_string:
out_string += proc.stdout.read(1)
proc.stdin.write(password + "\n")
output = proc.stdout.read()
error = proc.stderr.read()
if "successfully" in output:
print " VSPHERE: Upload completed"
return 0, output
else:
print "VSPHERE: Upload did not complete"
return -1, "\n".join([output, error])
示例6: make_template
def make_template(client, name, provider):
print("VSPHERE:{} Marking as Template".format(provider))
vm = VirtualMachine.get(client.api, name=name)
try:
vm.MarkAsTemplate()
print(" VSPHERE:{} Successfully templatized machine".format(provider))
except:
print(" VSPHERE:{} Failed to templatize machine".format(provider))
sys.exit(127)
示例7: make_template
def make_template(client, name):
print("VSPHERE: Marking as Template")
vm = VirtualMachine.get(client.api, name=name)
try:
vm.MarkAsTemplate()
print(" VSPHERE: Successfully templatized machine")
except:
print(" VSPHERE: Failed to templatize machine")
sys.exit(127)
示例8: make_template
def make_template(client, name, hostname, username, password):
print "VSPHERE: Marking as Template"
client = Client(server=hostname, username=username, password=password)
vm = VirtualMachine.get(client, name=name)
try:
vm.MarkAsTemplate()
print " VSPHERE: Successfully templatized machine"
except:
print " VSPHERE: Failed to templatize machine"
sys.exit(127)
示例9: vsphere_is_vm_down
def vsphere_is_vm_down(api, vm_name):
"""Returns True if VM on vsphere is down.
Args:
api: api endpoint to vsphere
vm_name: name og the vm
"""
vm = VirtualMachine.get(api.api, name=vm_name)
if vm.runtime.powerState == 'poweredOff':
return True
return False
示例10: vsphere_is_vm_up
def vsphere_is_vm_up(api, vm_name):
"""Returns True if VM on vsphere is up.
Args:
api: api endpoint to vsphere
vm_name: name of the vm
"""
vm = VirtualMachine.get(api.api, name=vm_name)
if vm.runtime.powerState == "poweredOn":
return True
return False
示例11: stop
def stop(self, vmname):
vm = VirtualMachine.get(self.client, name=vmname)
print 'Attempting to shut down ' + vmname
try:
shutdown = vm.ShutdownGuest()
self.task(vm, shutdown)
except suds.WebFault as e:
if self.force:
print 'Attempting to forcefully power off ' + vmname
pass
else:
raise e
print 'Attempting to power off ' + vmname
poweroff = vm.PowerOffVM_Task()
self.task(vm, poweroff)
示例12: add_disk
def add_disk(client, name):
print "VSPHERE: Beginning disk add..."
backing = client.create("VirtualDiskFlatVer2BackingInfo")
backing.datastore = None
backing.diskMode = "persistent"
backing.thinProvisioned = True
disk = client.create("VirtualDisk")
disk.backing = backing
disk.controllerKey = 1000
disk.key = 3000
disk.unitNumber = 1
disk.capacityInKB = 8388608
disk_spec = client.create("VirtualDeviceConfigSpec")
disk_spec.device = disk
file_op = client.create("VirtualDeviceConfigSpecFileOperation")
disk_spec.fileOperation = file_op.create
operation = client.create("VirtualDeviceConfigSpecOperation")
disk_spec.operation = operation.add
devices = []
devices.append(disk_spec)
nc = client.create("VirtualMachineConfigSpec")
nc.deviceChange = devices
vm = VirtualMachine.get(client, name=name)
task = vm.ReconfigVM_Task(spec=nc)
def check_task(task):
task.update()
return task.info.state
wait_for(check_task, [task], fail_condition="running")
if task.info.state == "success":
print " VSPHERE: Successfully added new disk"
client.logout()
else:
client.logout()
print " VSPHERE: Failed to add disk"
sys.exit(127)
示例13: vsphere_delete_vm
def vsphere_delete_vm(api, vm_name):
"""Deletes VM from vsphere-type provider.
If needed, stops the VM first, then deletes it.
Args:
api: api endpoint to vsphere
vm_name: name of the vm
"""
vm = VirtualMachine.get(api.api, name=vm_name)
vm_status = vsphere_vm_status(api, vm_name)
if vm_status != "poweredOn" and vm_status != "poweredOff":
# something is wrong, locked image etc
exc_msg = "VM status: {}".format(vm_status)
raise Exception(exc_msg)
print("status: {}".format(vm_status))
if vm_status == "poweredOn":
print("Powering down: {}".format(vm.name))
vm.PowerOffVM_Task()
wait_for(vsphere_is_vm_down, [api, vm_name], fail_condition=False, delay=10, num_sec=120)
print("Deleting: {}".format(vm_name))
vm.Destroy_Task()
示例14: clone
def clone(self,cursor,payload):
''' clone the template with our payload '''
while payload:
data = payload.pop(0)
try:
cluster = ClusterComputeResource.get(cursor, name=data['cluster'])
except Exception, e:
log.error("Unable to locate a cluster resource witht the name {}. Omitting build".format(data['cluster']))
else:
pool = cluster.resourcePool
esxhost = choice(cluster.host)
datastore = choice(cluster.datastore)
log.info("Cloning virtual machine named {} into cluster {} from template {}".format(data['vm_name'],data['cluster'],data['template']))
template = VirtualMachine.get(cursor, name=data['template'])
folder = cluster.parent.parent.vmFolder
_ip_spec = self._vm_ip_spec(cursor, domain = data['domain'],
dns = data['dns'],
gateway = data['gateway'],
ip = data['ip'],
netmask = data['netmask'])
_adapter_spec = self._vm_adapter_spec(cursor,_ip_spec)
_net_spec = self._vm_net_spec(cursor,cluster.network, vlan = data['vlan'])
_custom_spec = self._vm_custom_spec(cursor, _adapter_spec, template = data['template'],
domain = data['domain'], name = data['vm_name'],
ip = data['ip'], gateway = data['gateway'],
netmask = data['netmask'], dns = data['dns'])
_config_spec = self._vm_config_spec(cursor, _net_spec, memory = data['memory'],
cpus = data['cpus'], cores = data['cores'],
name = data['vm_name'])
_relo_spec = self._vm_relo_spec(cursor,esxhost,datastore,pool)
_clone_spec = self._vm_clone_spec(cursor, _relo_spec, _config_spec, _custom_spec)
try:
#self.wait_for_task(template.CloneVM_Task(folder = folder, name = data['vm_name'], spec=_clone_spec))
template.CloneVM_Task(folder = folder, name = data['vm_name'], spec=_clone_spec)
except VimFault, e:
print e
示例15: start
def start(self, vmname):
vm = VirtualMachine.get(self.client, name=vmname)
print 'Attempting to power on %s' % (vmname)
poweron = vm.PowerOnVM_Task()
self.task(vm, poweron)