本文整理汇总了Python中libvirt.openReadOnly方法的典型用法代码示例。如果您正苦于以下问题:Python libvirt.openReadOnly方法的具体用法?Python libvirt.openReadOnly怎么用?Python libvirt.openReadOnly使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类libvirt
的用法示例。
在下文中一共展示了libvirt.openReadOnly方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __enter__
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [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)
示例2: main
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def main():
args = parse_args()
conn = libvirt.openReadOnly(None)
now = str(int(time()))
core2node = get_cpu_core_to_numa_node_mapping()
total_mem_used = 0
for dom in conn.listAllDomains():
name = dom.name()
if args.trim_domain:
if name.endswith('.' + args.trim_domain):
name = name[:-len('.' + args.trim_domain)]
# Strip objectid from domain name to get the hostname
if '_' in name:
name = name.split('_', 1)[1]
# Make hostname save for graphite
name = name.replace('.', '_')
dom_state, dom_reason = dom.state()
if dom_state == libvirt.VIR_DOMAIN_RUNNING:
get_dom_vcpu_stats(dom, args.prefix, name, now, core2node)
get_dom_network_stats(dom, args.prefix, name, now)
get_dom_disk_stats(dom, args.prefix, name, now)
total_mem_used += get_dom_memory_stats(dom, args.prefix, name, now)
get_dom_storage_usage(conn, dom, args.prefix, name, now)
get_hv_storage_usage(conn, args.prefix, now)
get_hv_memory_usage(conn, args.prefix, now, total_mem_used)
示例3: register_close
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def register_close(params):
global logger
logger = params['logger']
if not version_compare("libvirt-python", 3, 8, 0, logger):
eventLoopPure(logger)
conn = libvirt.openReadOnly("qemu:///system")
conn.registerCloseCallback(connCloseCallback, None)
time.sleep(1)
t = threading.Thread(target=restart_libvirtd, args=(conn, logger))
t.start()
t.join()
count = 0
while count < 5:
count += 1
if callback:
logger.info("PASS: registerCloseCallback successful.")
break
time.sleep(2)
if count == 5:
logger.error("FAIL: registerCloseCallback failed.")
return 1
return 0
示例4: _connect
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def _connect(self):
url = self.config.get('server', "")
self.logger.info("Using libvirt url: %s", url if url else '""')
try:
if self.config.get('password', None):
auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], libvirt_cred_request, self.config]
v = libvirt.openAuth(url, auth, libvirt.VIR_CONNECT_RO)
else:
v = libvirt.openReadOnly(url)
except libvirt.libvirtError as e:
self.logger.exception("Error in libvirt backend")
raise VirtError(str(e))
v.domainEventRegister(self._callback, None)
v.setKeepAlive(5, 3)
return v
示例5: connect
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def connect(self, uri = None):
if uri is None:
uri = self.uri
try:
self.conn = libvirt.openReadOnly(uri)
except:
print("There was an error connecting to the local libvirt daemon using '%s'." % uri, file=sys.stderr)
self.conn = None
return self.conn
示例6: libvirt_conn
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def libvirt_conn(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
conn = libvirt.openReadOnly('qemu:///system')
return f(conn, *args, **kwargs)
return wrapper
示例7: main
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def main():
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, default=1024)
parser.add_argument('-c', '--connect', dest='libvirt_connection_string', default='qemu:///system')
parser.add_argument('--enable-xheaders', default=False, action='store_true')
parser.add_argument('--load-edited-domain-xml', default=False, action='store_true',
help='Use this flag to make changes to Domain XML to be reflected immediately (opposed ' +
'to requiring a restart of the domain)')
parser.add_argument('--plugin', action='append', help='Load this plugin. This simply imports the module. ' +
'See example for more details')
args = parser.parse_args()
if args.plugin:
for plugin in args.plugin:
__import__(plugin)
application = tornado.web.Application(
handlers.routes,
machine_resolver=utils.machine_resolver.LibvirtMachineResolver(
libvirt.openReadOnly(args.libvirt_connection_string),
args.load_edited_domain_xml)
)
http_server = tornado.httpserver.HTTPServer(application)
http_server.xheaders = args.enable_xheaders
http_server.listen(args.port)
tornado.ioloop.IOLoop.instance().start()
示例8: get_inventory
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def get_inventory(self):
''' Construct the inventory '''
inventory = dict(_meta=dict(hostvars=dict()))
conn = libvirt.openReadOnly(self.libvirt_uri)
if conn is None:
print "Failed to open connection to %s" % self.libvirt_uri
sys.exit(1)
domains = conn.listAllDomains()
if domains is None:
print "Failed to list domains for connection %s" % self.libvirt_uri
sys.exit(1)
for domain in domains:
hostvars = dict(libvirt_name=domain.name(),
libvirt_id=domain.ID(),
libvirt_uuid=domain.UUIDString())
domain_name = domain.name()
# TODO: add support for guests that are not in a running state
state, _ = domain.state()
# 2 is the state for a running guest
if state != 1:
continue
hostvars['libvirt_status'] = 'running'
root = ET.fromstring(domain.XMLDesc())
ansible_ns = {'ansible': 'https://github.com/ansible/ansible'}
for tag_elem in root.findall('./metadata/ansible:tags/ansible:tag', ansible_ns):
tag = tag_elem.text
_push(inventory, "tag_%s" % tag, domain_name)
_push(hostvars, 'libvirt_tags', tag)
# TODO: support more than one network interface, also support
# interface types other than 'network'
interface = root.find("./devices/interface[@type='network']")
if interface is not None:
source_elem = interface.find('source')
mac_elem = interface.find('mac')
if source_elem is not None and \
mac_elem is not None:
# Adding this to disable pylint check specifically
# ignoring libvirt-python versions that
# do not include DHCPLeases
# This is needed until we upgrade the build bot to
# RHEL7 (>= 1.2.6 libvirt)
# pylint: disable=no-member
dhcp_leases = conn.networkLookupByName(source_elem.get('network')) \
.DHCPLeases(mac_elem.get('address'))
if len(dhcp_leases) > 0:
ip_address = dhcp_leases[0]['ipaddr']
hostvars['ansible_ssh_host'] = ip_address
hostvars['libvirt_ip_address'] = ip_address
inventory['_meta']['hostvars'][domain_name] = hostvars
return inventory
示例9: hypervisor_connecting_test
# 需要导入模块: import libvirt [as 别名]
# 或者: from libvirt import openReadOnly [as 别名]
def hypervisor_connecting_test(uri, unix_sock_group, auth_unix_ro, auth_unix_rw, logger):
"""connect to hypervisor"""
logger.info("connect to hypervisor")
orginal_user = os.geteuid()
testing_user_id = getpwnam(TESTING_USER)[2]
logger.info("the testing_user id is %d" % testing_user_id)
logger.info("set euid to %d" % testing_user_id)
os.seteuid(testing_user_id)
if utils.version_compare("libvirt", 3, 2, 0, logger):
cmd = "klist -A | grep 'Ticket cache: FILE:' | awk '{print $3}'"
ret, out = utils.exec_cmd(cmd, shell=True)
if ret:
logger.error("get ticket cache file failed.")
logger.error("cmd: %s" % cmd)
logger.error("out: %s" % out)
return 1
TICKET_CACHE = out[0].split(':')[1]
cmd = "chown %s:%s %s" % (TESTING_USER, unix_sock_group, TICKET_CACHE)
ret, out = utils.exec_cmd(cmd, shell=True)
if ret:
logger.error("change %s owner failed." % TICKET_CACHE)
return 1
try:
if auth_unix_ro == 'none':
conn = libvirt.openReadOnly(uri)
elif auth_unix_ro == 'sasl':
user_data = [TESTING_USER, TESTING_USER]
auth = [[libvirt.VIR_CRED_AUTHNAME,
libvirt.VIR_CRED_PASSPHRASE],
request_credentials, user_data]
conn = libvirt.openAuth(uri, auth, 0)
if auth_unix_rw == 'none':
conn = libvirt.open(uri)
elif auth_unix_rw == 'sasl':
user_data = [TESTING_USER, TESTING_USER]
auth = [[libvirt.VIR_CRED_AUTHNAME,
libvirt.VIR_CRED_PASSPHRASE],
request_credentials, user_data]
conn = libvirt.openAuth(uri, auth, 0)
conn.close()
except libvirtError as e:
logger.error("API error message: %s, error code is %s"
% (e.get_error_message(), e.get_error_code()))
logger.info("set euid back to %d" % orginal_user)
os.seteuid(orginal_user)
conn.close()
return 1
logger.info("set euid back to %d" % orginal_user)
os.seteuid(orginal_user)
return 0