本文整理汇总了Python中libvirt.open方法的典型用法代码示例。如果您正苦于以下问题:Python libvirt.open方法的具体用法?Python libvirt.open怎么用?Python libvirt.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类libvirt
的用法示例。
在下文中一共展示了libvirt.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: domain_create
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def domain_create(hypervisor, identifier, configuration, network_name=None):
"""libvirt Domain definition.
@raise: ConfigError, IOError, libvirt.libvirtError.
"""
mounts = []
with open(configuration['configuration']) as config_file:
domain_config = config_file.read()
if 'filesystem' in configuration:
if isinstance(configuration['filesystem'], (list, tuple)):
for mount in configuration['filesystem']:
mounts.append(mountpoint(mount, identifier))
else:
mounts.append(mountpoint(configuration['filesystem'], identifier))
xml_config = domain_xml(identifier, domain_config, tuple(mounts), network_name=network_name)
return hypervisor.defineXML(xml_config)
示例2: _create_net_xml
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def _create_net_xml():
"""
Create a libvirt XML for the network bridge
"""
with open(os.path.join(os.path.dirname(__file__),
'libvirt-net.xml'), 'r') as fh:
xml_template = fh.read()
xml_info = {
'uuid': str(uuid.uuid4()),
'network_name': CONF.libvirt_network_name,
'bridge': CONF.libvirt_bridge_name,
'ip': CONF.libvirt_bridge_ip,
'dhcp_start': '.'.join(CONF.libvirt_bridge_ip.split('.')[0:3] + ['2']),
'dhcp_end': '.'.join(CONF.libvirt_bridge_ip.split('.')[0:3] + ['254']),
}
return Template(xml_template).substitute(xml_info)
示例3: updateDataForHost
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def updateDataForHost(currentDataList):
# Open connection with the Hypervisor
libvertConn = libvirt.open('qemu:///system')
if libvertConn == None:
print('Failed to open connection to '
'', file=sys.stderr)
exit(1)
currentTimeStamp = str(int(time.time() * 1000))
CPUDataMap = libvertConn.getCPUMap()
mem = libvertConn.getFreeMemory()
stats = libvertConn.getCPUStats(-1)
currentDataList.append(currentTimeStamp)
currentDataList.append(str(round(mem / 1048576., 2)))
currentDataList.append(str(CPUDataMap[0]))
currentDataList.append(str(stats['kernel'] / 10 ** 9))
currentDataList.append(str(stats['idle'] / 10 ** 9))
currentDataList.append(str(stats['user'] / 10 ** 9))
currentDataList.append(str(stats['iowait'] / 10 ** 9))
libvertConn.close()
示例4: getVMDomains
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def getVMDomains():
# Open connection with the Hypervisor
libvertConn = libvirt.open('qemu:///system')
if libvertConn == None:
print('Failed to open connection to '
'', file=sys.stderr)
exit(1)
# Get the information about the various guest VMs
vmIdentities = libvertConn.listDomainsID()
vmDomains = []
if len(vmIdentities) == 1:
vmDomains.append(libvertConn.lookupByID(vmIdentities[0]))
if len(vmDomains) == 0:
print('Failed to find the domain ', file=sys.stderr)
exit(1)
else:
# Handle for multiple domains
for id in vmIdentities:
vmDomains.append(libvertConn.lookupByID(id))
return vmDomains
示例5: checkNewVMs
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def checkNewVMs(vmDomains):
newVMNames = []
vmMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
for vmDomain in vmDomains:
newVMNames.append(vmDomain.name())
if os.path.isfile(vmMetaDataFilePath) == False:
towritePreviousVM = {}
towritePreviousVM["allVM"] = newVMNames
with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
json.dump(towritePreviousVM, vmMetaDataFile)
else:
with open(vmMetaDataFilePath, 'r') as vmMetaDataFile:
oldVMDomains = json.load(vmMetaDataFile)["allVM"]
if cmp(newVMNames, oldVMDomains) != 0:
towritePreviousVM = {}
towritePreviousVM["allVM"] = newVMNames
with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
json.dump(towritePreviousVM, vmMetaDataFile)
if os.path.isfile(os.path.join(homePath, dataDirectory + date + ".csv")) == True:
oldFile = os.path.join(homePath, dataDirectory + date + ".csv")
newFile = os.path.join(homePath, dataDirectory + date + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
os.rename(oldFile, newFile)
示例6: cpu_family_model
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def cpu_family_model(self):
"""Get CPU family and model"""
if self._cpu_family is None or self._cpu_model is None:
family = None
model = None
with open('/proc/cpuinfo') as cpuinfo:
for line in cpuinfo.readlines():
line = line.strip()
if not line:
# take info from the first core
break
field, value = line.split(':', 1)
if field.strip() == 'model':
model = int(value.strip())
elif field.strip() == 'cpu family':
family = int(value.strip())
self._cpu_family = family
self._cpu_model = model
return self._cpu_family, self._cpu_model
示例7: image
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def image(self):
path = "%s/%s" % (self.configuration.get(
'storage_pool_path').rstrip('/'), self.name.lstrip('/'))
if not os.path.exists(path):
raise FileNotFoundError(path)
hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'qemu:///system'))
try:
volume = hypervisor.storageVolLookupByPath(path)
return volume.path()
except libvirt.libvirtError:
pool = hypervisor.storagePoolDefineXML(POOL_CONFIG_XML.format(
self.configuration.get('storage_pool_path')))
pool.setAutostart(True)
pool.create()
pool.refresh()
return pool.storageVolLookupByName(self.name).path()
示例8: allocate
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def allocate(self):
"""Initializes libvirt resources."""
network_name = None
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'lxc:///'))
if 'network' in self.configuration:
self._network = network.create(self._hypervisor, self.identifier,
self.configuration['network'])
network_name = self._network.name()
self._domain = domain_create(self._hypervisor, self.identifier,
self.configuration['domain'],
network_name=network_name)
if self._network is None:
self._network = network.lookup(self._domain)
示例9: __enter__
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def __enter__(self):
try:
if self.sasl_username and self.sasl_password:
def request_cred(credentials, user_data):
for credential in credentials:
if credential[0] == libvirt.VIR_CRED_AUTHNAME:
credential[4] = self.sasl_username
elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
credential[4] = self.sasl_password
return 0
auth = [[libvirt.VIR_CRED_AUTHNAME,
libvirt.VIR_CRED_PASSPHRASE], request_cred, None]
flags = libvirt.VIR_CONNECT_RO if self.readonly else 0
self.conn = libvirt.openAuth(self.uri, auth, flags)
elif self.readonly:
self.conn = libvirt.openReadOnly(self.uri)
else:
self.conn = libvirt.open(self.uri)
return self.conn
except libvirt.libvirtError as e:
raise exception.LibvirtConnectionOpenError(uri=self.uri, error=e)
示例10: __init__
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def __init__(self, debug=0, dryrun=0, force=0, marvin_config=''):
self.config_section_name = None
self.DEBUG = debug
self.DRYRUN = dryrun
self.FORCE = force
self.marvin_config = marvin_config
self.marvin_data = False
# we can run as a user in the libvirt group
# self.check_root()
self.configfile = os.path.dirname(os.path.realpath(__file__)) + '/config'
self.config_data = { }
try:
self.conn = libvirt.open('qemu:///system')
except Exception as e:
print("ERROR: Could not connect to Qemu!")
print(e)
sys.exit(1)
self.print_welcome()
self.read_config_file(self.configfile)
# Check for root permissions
示例11: load_marvin_json
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def load_marvin_json(self):
try:
print("Note: Processing Marvin config '" + self.marvin_config + "'")
config_lines = []
with open(self.marvin_config) as file_pointer:
for line in file_pointer:
ws = line.strip()
if not ws.startswith("#"):
config_lines.append(ws)
self.marvin_data = json.loads("\n".join(config_lines))
return True
except:
print("Error: loading Marvin failed")
return False
# Get Marvin json
示例12: create_xml_with_files_clean
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def create_xml_with_files_clean(params):
logger = params['logger']
guestname = params['guestname']
for i in range(len(files)):
ret = utils.del_file("/tmp/libvirt-test-api-create-file-%d" % i, logger)
ret = utils.del_file("/tmp/libvirt_passfile_check", logger)
conn = libvirt.open("lxc:///")
dom = conn.lookupByName(guestname)
guest_state = dom.info()[0]
if guest_state == libvirt.VIR_DOMAIN_RUNNING:
logger.debug("destroy guest: %s." % guestname)
time.sleep(5)
dom.destroyFlags()
define_list = conn.listDefinedDomains()
if guestname in define_list:
time.sleep(3)
dom.undefine()
time.sleep(3)
elif guest_state == libvirt.VIR_DOMAIN_SHUTOFF:
time.sleep(5)
dom.undefine()
time.sleep(3)
示例13: create_with_files_clean
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def create_with_files_clean(params):
logger = params['logger']
for i in range(len(files)):
ret = utils.del_file("/tmp/libvirt-test-api-create-file-%d" % i, logger)
ret = utils.del_file("/tmp/libvirt_passfile_check", logger)
conn = libvirt.open("lxc:///")
dom = conn.lookupByName(guestname)
guest_state = dom.info()[0]
if guest_state == libvirt.VIR_DOMAIN_RUNNING:
logger.debug("destroy guest: %s." % guestname)
time.sleep(5)
dom.destroyFlags()
define_list = conn.listDefinedDomains()
if guestname in define_list:
time.sleep(3)
dom.undefine()
time.sleep(3)
elif guest_state == libvirt.VIR_DOMAIN_SHUTOFF:
time.sleep(5)
dom.undefine()
time.sleep(3)
示例14: checkpoint_lookup
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def checkpoint_lookup(params):
logger = params['logger']
guestname = params['guestname']
checkpoint_name = params.get('checkpoint_name', None)
logger.info("Checkpoint name: %s" % checkpoint_name)
if not utils.version_compare('libvirt-python', 5, 6, 0, logger):
logger.info("Current libvirt-python don't support checkpointLookupByName().")
return 0
try:
conn = libvirt.open()
dom = conn.lookupByName(guestname)
cp = dom.checkpointLookupByName(checkpoint_name, 0)
except libvirtError as err:
logger.error("API error message: %s" % err.get_error_message())
return 1
# check checkpoint
if cp.getName() == checkpoint_name:
logger.info("PASS: check checkpoint name successful.")
return 0
else:
logger.error("FAIL: check checkpoint name failed.")
return 1
示例15: list_all_children
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import open [as 别名]
def list_all_children(params):
logger = params['logger']
guestname = params['guestname']
checkpoint_name = params['checkpoint_name']
flag = utils.parse_flags(params)
if not utils.version_compare('libvirt-python', 5, 6, 0, logger):
logger.info("Current libvirt-python don't support listAllChildren().")
return 0
logger.info("Checkpoint name: %s" % checkpoint_name)
logger.info("flag: %s" % flag)
try:
conn = libvirt.open()
dom = conn.lookupByName(guestname)
cp = dom.checkpointLookupByName(checkpoint_name)
cp_lists = cp.listAllChildren(flag)
for cp_list in cp_lists:
logger.info("Checkpoint children list: %s" % cp_list.getName())
except libvirtError as err:
logger.error("API error message: %s" % err.get_error_message())
return 1
return 0