本文整理汇总了Python中ovirtsdk.api.API.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python API.disconnect方法的具体用法?Python API.disconnect怎么用?Python API.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ovirtsdk.api.API
的用法示例。
在下文中一共展示了API.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def run(**kwargs):
"""Calls all the functions needed to upload new template to RHEVM.
This is called either by template_upload_all script, or by main function.
Args:
**kwargs: Kwargs generated from cfme_data['template_upload']['template_upload_rhevm'].
"""
ovaname = get_ova_name(kwargs.get('image_url'))
mgmt_sys = cfme_data['management_systems'][kwargs.get('provider')]
rhevurl = mgmt_sys['hostname']
rhevm_credentials = mgmt_sys['credentials']
username = credentials[rhevm_credentials]['username']
password = credentials[rhevm_credentials]['password']
ssh_rhevm_creds = mgmt_sys['hosts'][0]['credentials']
sshname = credentials[ssh_rhevm_creds]['username']
sshpass = credentials[ssh_rhevm_creds]['password']
rhevip = mgmt_sys['ipaddress']
apiurl = 'https://%s:443/api' % rhevurl
ssh_client = make_ssh_client(rhevip, sshname, sshpass)
api = API(url=apiurl, username=username, password=password,
insecure=True, persistent_auth=False)
template_name = kwargs.get('template_name', None)
if template_name is None:
template_name = cfme_data['basic_info']['appliance_template']
kwargs = update_params_api(api, **kwargs)
check_kwargs(**kwargs)
if api.templates.get(template_name) is not None:
print "RHEVM: Found finished template with this name."
print "RHEVM: The script will now end."
else:
print "RHEVM: Downloading .ova file..."
download_ova(ssh_client, kwargs.get('image_url'))
try:
print "RHEVM: Templatizing .ova file..."
template_from_ova(api, username, password, rhevip, kwargs.get('edomain'),
ovaname, ssh_client)
print "RHEVM: Importing new template..."
import_template(api, kwargs.get('edomain'), kwargs.get('sdomain'),
kwargs.get('cluster'))
print "RHEVM: Making a temporary VM from new template..."
make_vm_from_template(api, kwargs.get('cluster'))
print "RHEVM: Adding disk to created VM..."
add_disk_to_vm(api, kwargs.get('sdomain'), kwargs.get('disk_size'),
kwargs.get('disk_format'), kwargs.get('disk_interface'))
print "RHEVM: Templatizing VM..."
templatize_vm(api, template_name, kwargs.get('cluster'))
finally:
cleanup(api, kwargs.get('edomain'), ssh_client, ovaname)
ssh_client.close()
api.disconnect()
print "RHEVM: Done."
示例2: main
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def main():
url='https://vm-rhevm01.infoplus-ot.ris:443/api'
username='[email protected]'
password=getpass.getpass("Supply password for user %s: " % username)
api = API(url=url, username=username, password=password,insecure=True)
vm_list=api.vms.list()
for vm in vm_list:
print vm.name
api.disconnect()
示例3: main
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def main():
URL='https://<ovirt-host>:443/api'
USERNAME='[email protected]'
PASSWORD='secretpass'
api = API(url=URL, username=USERNAME, password=PASSWORD,insecure=True)
vm_list=api.vms.list()
for vm in vm_list:
print vm.name
api.disconnect()
示例4: main
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def main():
URL = 'https://192.168.1.112:443/api'
USERNAME = '[email protected]'
PASSWORD = 'mprc'
api = API(url=URL, username=USERNAME, password=PASSWORD, insecure=True)
vm = api.vms.get(name="ubuntu14.04")
print vm.name
#vm_list = api.vms.list()
#for vm in vm_list:
# print vm.name
api.disconnect()
示例5: start_vm
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def start_vm(vm_name, host_ip):
try:
api = API(url="https://engine167.eayun.com", username="[email protected]", password="abc123", ca_file="ca.crt")
vm = api.vms.get(name=vm_name)
try:
vm.start(action=params.Action(vm=params.VM(host=params.Host(address=host_ip))))
print "Started '%s'." % vm.get_name()
except Exception as ex:
print "Unable to start '%s': %s" % (vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
示例6: process
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def process(api_url, username, password, cert_file=None):
api = API(url=api_url,
username=username,
password=password,
cert_file=cert_file,
insecure=(not cert_file))
print('Connected to %s' % api_url)
problematic_vms = list(iter_problematic_vms(api))
api.disconnect()
if problematic_vms:
print(build_search_criteria(problematic_vms, get_single_vm_criteria_by_name))
print(build_search_criteria(problematic_vms, get_single_vm_criteria_by_id))
else:
print('All MAC addresses are in range')
示例7: start_vms
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def start_vms(vmObj):
logging.info('Thread to start %s', vmObj.name)
try:
vmObj.start()
#time.sleep(5)
except Exception as e:
logging.debug('Exception caught on VM ( %s) start:\n%s' % (vmObj.name, str(e)))
failedVms.append(vmObj.name)
if __name__ == "__main__":
try:
api = API(url=APIURL,
username=APIUSER,
password=APIPASS,
ca_file=CAFILE)
print 'Connected to oVIRT API %s Successfully' % APIURL
logging.info ( 'Successfully Connected to %s' % APIURL)
try:
print ' \n I am logging in %s \n' % LOGFILENAME
vmsList = api.vms.list()
for i in vmsList:
print i.name
if i.status.state != 'up':
logging.warning('%s is not up, trying to start it' % i.name)
threadMe = Thread(target=start_vms, args=[i])
threadMe.start()
threads.append(threadMe)
except Exception as e:
logging.debug('Error:\n%s' % str(e))
logging.warning ('No of VMs to start : %s' % len(threads))
print 'No of VMs to start: %s' % len(threads)
for th in threads:
logging.info ('Waiting for %s to join' % th)
th.join (30)
if not th.isAlive():
logging.info ('Thread : %s terminated' % (th.getName()))
else:
logging.debug( 'Thread : %s is still alive, you may check this task..' % (th))
logging.debug (' Below Vms failed to start with an exception:%s' % (failedVms));
api.disconnect()
except Exception as ex:
logging.debug('Unexpected error: %s' % ex)
示例8: stop_vm
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
def stop_vm(vm_name):
try:
api = API(url="https://engine167.eayun.com",
username="[email protected]",
password="abc123",
ca_file="ca.crt")
vm = api.vms.get(name=vm_name)
try:
vm.stop()
print "Stoped '%s'." % vm.get_name()
except Exception as ex:
print "Unable to stop '%s': %s" % (vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
示例9: Thread
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
logging.info ( 'Successfully Connected to %s' % APIURL)
try:
print ' \n I am logging in %s \n' % LOGFILENAME
vmsList = api.vms.list()
for i in vmsList:
print i.name
if i.status.state != 'up':
logging.warning('%s is not up, trying to start it' % i.name)
threadMe = Thread(target=start_vms, args=[i])
threadMe.start()
threads.append(threadMe)
except Exception as e:
logging.debug('Error:\n%s' % str(e))
logging.warning ('No of VMs to start : %s' % len(threads))
print 'No of VMs to start: %s' % len(threads)
for th in threads:
logging.info ('Waiting for %s to join' % th)
th.join (30)
if not th.isAlive():
logging.info ('Thread : %s terminated' % (th.getName()))
else:
logging.debug( 'Thread : %s is still alive, you may check this task..' % (th))
logging.debug (' Below Vms failed to start with an exception:%s' % (failedVms));
api.disconnect()
except Exception as ex:
logging.debug('Unexpected error: %s' % ex)
示例10: ovirt_test
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
class ovirt_test( object ):
"""An instance represents ovirt test.
"""
def __init__ ( self, test_dict = {} ):
'''Constructor for ovirt_test.
self.ovirt_dict = {}
self.ovirt_dict['URL'] = url
self.ovirt_dict['VERSION'] = params.Version(major='3', minor='0')
self.ovirt_dict['CA_FILE'] = "/etc/pki/ovirt-engine/ca.pem"
self.ovirt_dict['USERINFO'] = {}
self.ovirt_dict['USERINFO']['NAME'] = '[email protected]'
self.ovirt_dict['USERINFO']['PASSWORD'] = 'admin'
self.ovirt_dict['DATACENTERS'] = [(name,type,cluster,storage,network),(name,...), ...]
network = [(name,type),(name, ...), ...]
storage = [(name,type,addr,path),(name, ...), ...]
cluster = [(name,type,hosts,vms,volumes),(name, ...), ...]
hosts = [(name,address),(name, ...), ...]
volumes = [(name,type),(name, ...), ...]
vms = [(name,type,ostype,display,nics,disks),(name, ...), ...]
nics = [(name,type,network),(name, ...), ...]
disks = [(name,type,size,storage),(name, ...), ...] '''
global iCLUSTERS
global iSTORAGES
global iHOSTS
iCLUSTERS = 2
iSTORAGES = 3
iHOSTS = 2
self.ovirt_dict = {}
self.ovirt_dict['URL'] = test_dict['URL']
self.ovirt_dict['VERSION'] = test_dict['VERSION']
self.ovirt_dict['CA_FILE'] = test_dict['CA_FILE']
self.ovirt_dict['USERINFOS'] = []
self.ovirt_dict['USERINFOS'].append(test_dict['USERINFOS'][0])
self.ovirt_dict['CONNECTION'] = False
self.ovirt_dict['DATACENTERS'] = []
self.ovirt_dict['CLUSTERS'] = []
self.ovirt_dict['HOSTS'] = []
self.ovirt_dict['STORAGES'] = []
self.ovirt_dict['VMS'] = []
self.ovirt_dict['NICS'] = []
self.ovirt_dict['DISKS'] = []
def connect_engine( self ):
'''Connect ovirt-engine, default connect local ovirt-engine
api = API(url="https://128.224.165.209:443/api", \
username="[email protected]", \
password="123456", \
ca_file="/etc/pki/ovirt-engine/ca.pem")
'''
try:
self.api = API(url=self.ovirt_dict['URL'],
username=self.ovirt_dict['USERINFOS'][0][0],
password=self.ovirt_dict['USERINFOS'][0][1],
ca_file=self.ovirt_dict['CA_FILE'])
print 'Connect ovirt-engine successfully'
self.ovirt_dict['CONNECTION'] = True
except Exception as e:
print 'Connect ovirt-engine failed:\n%s' % (str(e))
self.ovirt_dict['CONNECTION'] = False
return False
def disconnect( self ):
'''Disconnect ovirt-engine'''
try:
if self.api.disconnect() == None:
print 'Disconnect ovirt-engine successfully'
self.ovirt_dict['CONNECTION'] = False
except Exception as e:
print 'Disconnect ovirt-engine failed:\n%s' % (str(e))
self.ovirt_dict['CONNECTION'] = 1
return False
def check_item( self, group , item_name, Other = 'None' ):
'''Check the item(item_name) exist in group'''
try:
index = 0
length = len(group)
for index in range(0,length):
if group[index][0] == item_name:
if Other != 'None' and group[index][1] == Other:
return index
return index
if index + 1 >= length:
return None
except Exception as e:
print 'Check %s failed:\n%s' % (item_name,str(e))
return None
def add_user( self, UserInfo = ('[email protected]','admin') ):
'''add a new user'''
try:
self.ovirt_dict['USERINFOS'].append(UserInfo)
except Exception as e:
print 'Add new user failed:\n%s' % (str(e))
return False
def change_user( self, UserInfo = ('[email protected]','admin') ):
#.........这里部分代码省略.........
示例11: RHEVMHelper
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
class RHEVMHelper(object):
api_connections_lock = BoundedSemaphore()
def __init__(self, url, username, password):
self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
# The SDK allows only a single active connection object to be created, regardless of whether
# or not multiple RHEVM servers are being accessed. For now we need to have a global lock,
# create a connection object before each batch of API interactions and then disconnect it.
self.api_details = { 'url':url, 'username':username, 'password':password }
# TODO: When this limitation in the ovirt SDK is removed, get rid of these
def _init_api(self):
self.log.debug("Doing blocking acquire() on global RHEVM API connection lock")
self.api_connections_lock.acquire()
self.log.debug("Got global RHEVM API connection lock")
url = self.api_details['url']
username = self.api_details['username']
password = self.api_details['password']
self.api = API(url=url, username=username, password=password)
def _disconnect_api(self):
self.api.disconnect()
self.log.debug("Releasing global RHEVM API connection lock")
self.api_connections_lock.release()
# These are the only two genuinley public methods
# What we create is a VM template
def import_template(self, image_filename, nfs_host, nfs_path, nfs_dir, cluster,
ovf_name = None, ovf_desc = None):
if not ovf_desc:
self.ovf_desc = "Imported by Image Factory"
else:
self.ovf_desc = ovf_desc
self.log.debug("Preparing for RHEVM template import of image file (%s)" % (image_filename))
# API lock protected action
try:
self._init_api()
self.init_vm_import(image_filename, nfs_host, nfs_path, nfs_dir, cluster)
finally:
self._disconnect_api()
if not ovf_name:
self.ovf_name=str(self.tpl_uuid)
else:
self.ovf_name = ovf_name
self.log.debug("Staging files")
self.stage_files()
self.log.debug("Moving files to final export domain location")
self.move_files()
self.log.debug("Executing import")
# API lock protected action
try:
self._init_api()
self.execute_import()
finally:
self._disconnect_api()
return str(self.tpl_uuid)
def delete_template(self, template_uuid):
template = self.api.templates.get(id=template_uuid)
if template:
template.delete()
return True
else:
return False
# Begin Nuts and Bolts
# We don't want to run seteuid() in our main process as it will globally change the UID/GID for everything
# OTOH, we need to be root to access our image files and temp files
# We use stdin and Popen's preexec_fn via the helper functions below to deal with this
def become_nfs_user(self):
os.setegid(NFSGID)
os.seteuid(NFSUID)
def copy_as_nfs_user(self, sourcefile, destfile):
self.log.debug("Copying (%s) to (%s) as nfsuser" % (sourcefile, destfile))
f = open(sourcefile,"r")
(stdout, stderr, retcode) = subprocess_check_output([ 'dd', 'of=%s' % (destfile), 'bs=4k' ], stdin=f, preexec_fn=self.become_nfs_user)
f.close()
def move_as_nfs_user(self, sourcefile, destfile):
self.log.debug("Moving (%s) to (%s) as nfsuser" % (sourcefile, destfile))
(stdout, stderr, retcode) = subprocess_check_output([ 'mv', '%s' % (sourcefile), '%s' % (destfile)], preexec_fn=self.become_nfs_user)
def mkdir_as_nfs_user(self, directory):
self.log.debug("Making directory (%s) as nfsuser" % (directory))
(stdout, stderr, retcode) = subprocess_check_output([ 'mkdir', '%s' % (directory)], preexec_fn=self.become_nfs_user)
def rm_rf_as_nfs_user(self, directory):
self.log.debug("Recursive remove of dir (%s) as nfsuser" % (directory))
(stdout, stderr, retcode) = subprocess_check_output([ 'rm', '-rf', '%s' % (directory)], preexec_fn=self.become_nfs_user)
def get_storage_domain(self, nfs_host, nfs_path):
# Find the storage domain that matches the nfs details given
#.........这里部分代码省略.........
示例12: RHEVMHelper
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
class RHEVMHelper(object):
api_connections_lock = BoundedSemaphore()
def __init__(self, url, username, password):
self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
# The SDK allows only a single active connection object to be created, regardless of whether
# or not multiple RHEVM servers are being accessed. For now we need to have a global lock,
# create a connection object before each batch of API interactions and then disconnect it.
self.api_details = { 'url':url, 'username':username, 'password':password }
# TODO: When this limitation in the ovirt SDK is removed, get rid of these
def _init_api(self):
self.log.debug("Doing blocking acquire() on global RHEVM API connection lock")
self.api_connections_lock.acquire()
self.log.debug("Got global RHEVM API connection lock")
url = self.api_details['url']
username = self.api_details['username']
password = self.api_details['password']
self.api = API(url=url, username=username, password=password, insecure=True)
def _disconnect_api(self):
try:
self.log.debug("Attempting API disconnect")
if hasattr(self, 'api') and self.api is not None:
self.api.disconnect()
else:
self.log.debug("API connection was not initialized. Will not attempt to disconnect.")
finally:
# Must always do this
self.log.debug("Releasing global RHEVM API connection lock")
self.api_connections_lock.release()
# These are the only two genuinley public methods
# What we create is a VM template
def import_template(self, image_filename, nfs_host, nfs_path, nfs_dir, cluster,
ovf_name = None, ovf_desc = None):
if not ovf_desc:
self.ovf_desc = "Imported by Image Factory"
else:
self.ovf_desc = ovf_desc
self.log.debug("Preparing for RHEVM template import of image file (%s)" % (image_filename))
# API lock protected action
try:
self._init_api()
self.init_vm_import(image_filename, nfs_host, nfs_path, nfs_dir, cluster)
finally:
self._disconnect_api()
self.ovf_name = ovf_name
self.log.debug("Staging files")
self.stage_files()
self.log.debug("Moving files to final export domain location")
self.move_files()
self.ovf_pkg.delete()
self.log.debug("Executing import")
# API lock protected action
try:
self._init_api()
self.execute_import()
finally:
self._disconnect_api()
return str(self.ovf_pkg.tpl_uuid)
def delete_template(self, template_uuid):
template = self.api.templates.get(id=template_uuid)
if template:
template.delete()
return True
else:
return False
# Begin Nuts and Bolts
# We don't want to run seteuid() in our main process as it will globally change the UID/GID for everything
# OTOH, we need to be root to access our image files and temp files
# We use stdin and Popen's preexec_fn via the helper functions below to deal with this
def become_nfs_user(self):
os.setegid(NFSGID)
os.seteuid(NFSUID)
def copy_as_nfs_user(self, sourcefile, destfile):
self.log.debug("Copying (%s) to (%s) as nfsuser" % (sourcefile, destfile))
f = open(sourcefile,"r")
(stdout, stderr, retcode) = subprocess_check_output([ 'dd', 'of=%s' % (destfile), 'bs=4k' ], stdin=f, preexec_fn=self.become_nfs_user)
f.close()
def copy_dir_as_nfs_user(self, sourcefile, destfile):
self.log.debug("Copying directory (%s) to (%s) as nfsuser" % (sourcefile, destfile))
(stdout, stderr, retcode) = subprocess_check_output([ 'cp', '-r', '%s' % (sourcefile), '%s' % (destfile)], preexec_fn=self.become_nfs_user)
def move_as_nfs_user(self, sourcefile, destfile):
self.log.debug("Moving (%s) to (%s) as nfsuser" % (sourcefile, destfile))
(stdout, stderr, retcode) = subprocess_check_output([ 'mv', '%s' % (sourcefile), '%s' % (destfile)], preexec_fn=self.become_nfs_user)
def mkdir_as_nfs_user(self, directory):
#.........这里部分代码省略.........
示例13: vm_start
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
vm_start(oe_conn, opt.vm_name)
elif opt.action == 'stop':
vm_stop(oe_conn, opt.vm_name)
elif opt.action == 'delete':
vm_delete(oe_conn, opt.vm_name)
elif opt.action == 'create':
vm_create_from_tpl(oe_conn, opt.vm_name, opt.vm_template, opt.vm_cluster)
elif opt.action == 'init':
vm_run_once(oe_conn, opt.vm_name, opt.vm_password, opt.vm_nic_info)
elif opt.action == 'start-list':
for vm in opt.vm_list.replace(' ', '').split(','):
print('[I] try to start vm: {0}'.format(vm))
vm_start(oe_conn, vm)
elif opt.action == 'stop-list':
for vm in opt.vm_list.replace(' ', '').split(','):
print('[I] try to stop vm: {0}'.format(vm))
vm_stop(oe_conn, vm)
elif opt.action == 'delete-list':
for vm in opt.vm_list.replace(' ', '').split(','):
print('[I] try to delete: {0}'.format(vm))
vm_delete(oe_conn, vm)
elif opt.action == 'create-list':
for vm in opt.vm_list.replace(' ', '').split(','):
print('[I] try to create: {0}'.format(vm))
vm_create_from_tpl(oe_conn, vm, opt.vm_template, opt.vm_cluster)
except Exception as e:
print('[E] Failed to init API: {0}'.format(str(e)))
finally:
if oe_conn is not None:
oe_conn.disconnect()
示例14: RHEVMSystem
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
#.........这里部分代码省略.........
# print 'VM created'
# self.api.vms.get(vm_name).nics.add(params.NIC(name='eth0',
# network=params.Network(name='ovirtmgmt'), interface='virtio'))
# print 'NIC added to VM'
# self.api.vms.get(vm_name).disks.add(params.Disk(
# storage_domains=params.StorageDomains(
# storage_domain=[self.api.storagedomains.get(kwargs['storage_domain'])],
# size=512 * MB,
# status=None,
# interface='virtio',
# format='cow',
# sparse=True,
# bootable=True)))
# print 'Disk added to VM'
# print 'Waiting for VM to reach Down status'
# while self.api.vms.get(vm_name).status.state != 'down':
# time.sleep(1)
# except Exception as e:
# print 'Failed to create VM with disk and NIC\n%s' % str(e)
def restart_vm(self, vm_name):
if not self.stop_vm(vm_name):
return False
else:
return self.start_vm(vm_name)
def list_vm(self, **kwargs):
# list vm based on kwargs can be buggy
# i.e. you can't return a list of powered on vm
# but you can return a vm w/ a matched name
vm_list = self.api.vms.list(**kwargs)
return [vm.name for vm in vm_list]
def list_host(self, **kwargs):
host_list = self.api.hosts.list(**kwargs)
return [host.name for host in host_list]
def list_datastore(self, **kwargs):
datastore_list = self.api.storagedomains.list(**kwargs)
return [ds.name for ds in datastore_list if ds.get_status() is None]
def list_cluster(self, **kwargs):
cluster_list = self.api.clusters.list(**kwargs)
return [cluster.name for cluster in cluster_list]
def list_template(self, **kwargs):
'''
CFME ignores the 'Blank' template, so we do too
'''
template_list = self.api.templates.list(**kwargs)
return [template.name for template in template_list if template.name != "Blank"]
def list_flavor(self):
raise NotImplementedError('This function is not supported on this platform.')
def info(self):
# and we got nothing!
pass
def disconnect(self):
self.api.disconnect()
def vm_status(self, vm_name=None):
state = self._get_vm(vm_name).get_status().get_state()
return state
def is_vm_running(self, vm_name):
state = self.vm_status(vm_name)
return "up" == state
def is_vm_stopped(self, vm_name):
state = self.vm_status(vm_name)
return "down" == state
def is_vm_suspended(self, vm_name):
state = self.vm_status(vm_name)
return "suspended" == state
def suspend_vm(self, vm_name):
vm = self._get_vm(vm_name)
if vm.status.get_state() == 'down':
raise Exception('Could not suspend %s because it\'s not running.' % vm_name)
else:
ack = vm.suspend()
return ack.get_status().get_state() == 'complete'
def clone_vm(self, source_name, vm_name):
raise NotImplementedError('This function has not yet been implemented.')
def deploy_template(self, template, *args, **kwargs):
self.api.vms.add(params.VM(
name=kwargs['vm_name'],
cluster=self.api.clusters.get(kwargs['cluster_name']),
template=self.api.templates.get(template)))
while self.api.vms.get(kwargs['vm_name']).status.state != 'down':
time.sleep(5)
self.start_vm(kwargs['vm_name'])
while not self.is_vm_running(kwargs['vm_name']):
time.sleep(5)
return kwargs['vm_name']
示例15: RHEVMSystem
# 需要导入模块: from ovirtsdk.api import API [as 别名]
# 或者: from ovirtsdk.api.API import disconnect [as 别名]
#.........这里部分代码省略.........
""" RHEVMSystem implementation in _get_vm. """
if vm_name is None:
raise Exception('Could not find a VM named %s.' % vm_name)
else:
vm = self.api.vms.get(name=vm_name)
if vm is None:
raise Exception('Could not find a VM named %s.' % vm_name)
return vm
def start_vm(self, vm_name=None):
""" RHEVMSystem implementation of start_vm. """
vm = self._get_vm(vm_name)
if vm.status.get_state() == 'up':
raise Exception('Could not start %s because it\'s already running.' % vm_name)
else:
ack = vm.start()
if ack.get_status().get_state() == 'complete':
return True
return False
def stop_vm(self, vm_name):
""" RHEVMSystem implementation of stop_vm. """
vm = self._get_vm(vm_name)
if vm.status.get_state() == 'down':
raise Exception('Could not stop %s because it\'s not running.' % vm_name)
else:
ack = vm.stop()
if ack.get_status().get_state() == 'complete':
return True
return False
def delete_vm(self, vm_name):
""" RHEVMSystem implementation of delete_vm. """
vm = self._get_vm(vm_name)
if vm.status.get_state() == 'up':
raise Exception('Could not delete %s because it\'s still running.' % vm_name)
else:
ack = vm.delete()
if ack.get_status().get_state() == '':
return True
return False
def create_vm(self, vm_name):
""" RHEVMSystem implementation of create_vm. """
#Unfortunately, there are not enough smurf slaves in the village to build this functionality yet.
pass
def restart_vm(self, vm_name):
""" RHEVMSystem implementation of restart_vm. """
if not self.stop_vm(vm_name):
return False
else:
return self.start_vm(vm_name)
def list_vm(self, **kwargs):
""" RHEVMSystem implementation of list_vm. """
# list vm based on kwargs can be buggy
# i.e. you can't return a list of powered on vm
# but you can return a vm w/ a matched name
vm_list = self.api.vms.list(**kwargs)
return [vm.name for vm in vm_list]
def info(self):
""" RHEVMSystem implementation of info. """
# and we got nothing!
pass
def disconnect(self):
""" RHEVMSystem implementation of disconnect. """
self.api.disconnect()
def vm_status(self, vm_name=None):
""" RHEVMSystem implementation of vm_status. """
state = self._get_vm(vm_name).get_status().get_state()
print "vm " + vm_name + " status is " + state
return state
def is_vm_running(self, vm_name):
""" RHEVMSystem implementation of is_vm_running. """
state = self.vm_status(vm_name)
return "up" == state
def is_vm_stopped(self, vm_name):
""" RHEVMSystem implementation of is_vm_stopped. """
state = self.vm_status(vm_name)
return "down" == state
def is_vm_suspended(self, vm_name):
""" RHEVMSystem implementation of is_vm_suspended. """
state = self.vm_status(vm_name)
return "suspended" == state
def suspend_vm(self, vm_name):
""" RHEVMSystem implementation of suspend_vm. """
vm = self._get_vm(vm_name)
if vm.status.get_state() == 'down':
raise Exception('Could not suspend %s because it\'s not running.' % vm_name)
else:
ack = vm.suspend()
return ack.get_status().get_state() == 'complete'