def __init__(self, libvirt_uri=None, objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {'objstore': self.objstore, 'conn': self.conn} if self.conn.isQemuURI(): for pool_name, pool_arg in DEFAULT_POOLS.iteritems(): self._default_pool_check(pool_name, pool_arg) this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module('model.' + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith('Model'): models.append(instance(**kargs)) return super(Model, self).__init__(models)
class Model(BaseModel): def __init__(self, libvirt_uri=None, objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {'objstore': self.objstore, 'conn': self.conn} if self.conn.isQemuURI(): for pool_name, pool_arg in DEFAULT_POOLS.iteritems(): self._default_pool_check(pool_name, pool_arg) this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module('model.' + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith('Model'): models.append(instance(**kargs)) return super(Model, self).__init__(models) def _default_pool_check(self, pool_name, pool_arg): conn = self.conn.get() pool = E.pool(E.name(pool_name), type='dir') pool.append(E.target(E.path(pool_arg['path']))) xml = ET.tostring(pool) try: pool = conn.storagePoolLookupByName(pool_name) except libvirt.libvirtError: try: pool = conn.storagePoolDefineXML(xml, 0) # Add build step to make sure target directory created pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW) pool.setAutostart(1) except libvirt.libvirtError, e: cherrypy.log.error("Fatal: Cannot create default pool because " "of %s, exit kimchid" % e.message, severity=logging.ERROR) sys.exit(1) if pool.isActive() == 0: try: pool.create(0) except libvirt.libvirtError, e: err = "Fatal: Default pool cannot be activated, exit kimchid" cherrypy.log.error(err, severity=logging.ERROR) sys.exit(1)
def _rollback_on_failure(self, iface): ''' Called by the Timer in a new thread to cancel wrong network configuration and rollback to previous configuration. ''' conn = LibvirtConnection("qemu:///system").get() try: conn.changeRollback() if iface.isActive(): iface.destroy() iface.create() except libvirt.libvirtError as e: # In case the timeout thread is preempted, and confirm_change() is # called before our changeRollback(), we can just ignore the # VIR_ERR_OPERATION_INVALID error. if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID: raise
def __init__(self, libvirt_uri="qemu:///system", objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {"objstore": self.objstore, "conn": self.conn} if "qemu:///" in libvirt_uri: for pool_name, pool_arg in DEFAULT_POOLS.iteritems(): self._default_pool_check(pool_name, pool_arg) this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module("model." + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith("Model"): models.append(instance(**kargs)) return super(Model, self).__init__(models)
def __init__(self, libvirt_uri='qemu:///system', objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {'objstore': self.objstore, 'conn': self.conn} if 'qemu:///' in libvirt_uri: self._default_pool_check() self._default_network_check() this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module('model.' + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith('Model'): models.append(instance(**kargs)) return super(Model, self).__init__(models)
class Model(BaseModel): def __init__(self, libvirt_uri='qemu:///system', objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {'objstore': self.objstore, 'conn': self.conn} if 'qemu:///' in libvirt_uri: self._default_pool_check() self._default_network_check() this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module('model.' + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith('Model'): models.append(instance(**kargs)) return super(Model, self).__init__(models) def _default_network_check(self): conn = self.conn.get() xml = """ <network> <name>default</name> <forward mode='nat'/> <bridge name='virbr0' stp='on' delay='0' /> <ip address='192.168.122.1' netmask='255.255.255.0'> <dhcp> <range start='192.168.122.2' end='192.168.122.254' /> </dhcp> </ip> </network> """ try: net = conn.networkLookupByName("default") except libvirt.libvirtError: try: net = conn.networkDefineXML(xml) except libvirt.libvirtError, e: cherrypy.log.error("Fatal: Cannot create default network " "because of %s, exit kimchid" % e.message, severity=logging.ERROR) sys.exit(1) if net.isActive() == 0: try: net.create() except libvirt.libvirtError, e: cherrypy.log.error("Fatal: Cannot activate default network " "because of %s, exit kimchid" % e.message, severity=logging.ERROR) sys.exit(1)
def _create_libvirt_network_iface(self, iface_xml): conn = LibvirtConnection("qemu:///system").get() # Only one active transaction is allowed in the system level. # It implies that we can use changeBegin() as a synchronized point. conn.changeBegin() try: iface = conn.interfaceDefineXML(iface_xml) self._rollback_timer = Timer( self._confirm_timout, self._rollback_on_failure, args=[iface]) if iface.isActive(): iface.destroy() iface.create() self._rollback_timer.start() except Exception as e: self._rollback_on_failure(iface) raise OperationFailed('GINNET0004E', {'err': e.message})
def _create_libvirt_network_iface(self, iface_xml): conn = LibvirtConnection("qemu:///system").get() # Only one active transaction is allowed in the system level. # It implies that we can use changeBegin() as a synchronized point. conn.changeBegin() try: iface = conn.interfaceDefineXML(iface_xml) self._rollback_timer = Timer(self._confirm_timout, self._rollback_on_failure, args=[iface]) if iface.isActive(): iface.destroy() iface.create() self._rollback_timer.start() except Exception as e: self._rollback_on_failure(iface) raise OperationFailed('GINNET0004E', {'err': e.message})
def _rollback_on_failure(self, gateway): _, err, rc = run_command(['ip', 'route', 'del', 'default']) if rc and not ('No such process' in err): raise OperationFailed('GINNET0010E', {'reason': err}) if gateway: _, err, rc = run_command(['ip', 'route', 'add', 'default', 'via', gateway]) if rc: raise OperationFailed('GINNET0011E', {'reason': err}) conn = LibvirtConnection("qemu:///system").get() try: conn.changeRollback() except libvirt.libvirtError as e: # In case the timeout thread is preempted, and confirm_change() is # called before our changeRollback(), we can just ignore the # VIR_ERR_OPERATION_INVALID error. if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID: raise
def _rollback_on_failure(self, gateway): _, err, rc = run_command(['ip', 'route', 'del', 'default']) if rc and not ('No such process' in err): raise OperationFailed('GINNET0010E', {'reason': err}) if gateway: _, err, rc = run_command( ['ip', 'route', 'add', 'default', 'via', gateway]) if rc: raise OperationFailed('GINNET0011E', {'reason': err}) conn = LibvirtConnection("qemu:///system").get() try: conn.changeRollback() except libvirt.libvirtError as e: # In case the timeout thread is preempted, and confirm_change() is # called before our changeRollback(), we can just ignore the # VIR_ERR_OPERATION_INVALID error. if e.get_error_code() != libvirt.VIR_ERR_OPERATION_INVALID: raise
class Model(BaseModel): def __init__(self, libvirt_uri='qemu:///system', objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {'objstore': self.objstore, 'conn': self.conn} if 'qemu:///' in libvirt_uri: self._default_pool_check() this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module('model.' + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith('Model'): models.append(instance(**kargs)) return super(Model, self).__init__(models) def _default_pool_check(self): conn = self.conn.get() xml = """ <pool type='dir'> <name>default</name> <target> <path>/var/lib/libvirt/images</path> </target> </pool> """ try: pool = conn.storagePoolLookupByName("default") except libvirt.libvirtError: try: pool = conn.storagePoolDefineXML(xml, 0) pool.setAutostart(1) except libvirt.libvirtError, e: cherrypy.log.error("Fatal: Cannot create default pool because " "of %s, exit kimchid" % e.message, severity=logging.ERROR) sys.exit(1) if pool.isActive() == 0: try: pool.create(0) except libvirt.libvirtError, e: err = "Fatal: Default pool cannot be activated, exit kimchid" cherrypy.log.error(err, severity=logging.ERROR) sys.exit(1)
class Model(BaseModel): def __init__(self, libvirt_uri="qemu:///system", objstore_loc=None): self.objstore = ObjectStore(objstore_loc) self.conn = LibvirtConnection(libvirt_uri) kargs = {"objstore": self.objstore, "conn": self.conn} if "qemu:///" in libvirt_uri: for pool_name, pool_arg in DEFAULT_POOLS.iteritems(): self._default_pool_check(pool_name, pool_arg) this = os.path.basename(__file__) this_mod = os.path.splitext(this)[0] models = [] for mod_name in listPathModules(os.path.dirname(__file__)): if mod_name.startswith("_") or mod_name == this_mod: continue module = import_module("model." + mod_name) members = inspect.getmembers(module, inspect.isclass) for cls_name, instance in members: if inspect.getmodule(instance) == module: if cls_name.endswith("Model"): models.append(instance(**kargs)) return super(Model, self).__init__(models) def _default_pool_check(self, pool_name, pool_arg): conn = self.conn.get() pool = E.pool(E.name(pool_name), type="dir") pool.append(E.target(E.path(pool_arg["path"]))) xml = ET.tostring(pool) try: pool = conn.storagePoolLookupByName(pool_name) except libvirt.libvirtError: try: pool = conn.storagePoolDefineXML(xml, 0) # Add build step to make sure target directory created pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW) pool.setAutostart(1) except libvirt.libvirtError, e: cherrypy.log.error( "Fatal: Cannot create default pool because " "of %s, exit kimchid" % e.message, severity=logging.ERROR, ) sys.exit(1) if pool.isActive() == 0: try: pool.create(0) except libvirt.libvirtError, e: err = "Fatal: Default pool cannot be activated, exit kimchid" cherrypy.log.error(err, severity=logging.ERROR) sys.exit(1)
def _save_gateway_changes(self, old_iface, old_gateway): def save_config(conn, iface, gateway=None): n = IPv4Network(get_dev_netaddr(iface)) net_params = {'ipaddr': str(n.ip), 'netmask': str(n.netmask)} if gateway: net_params['gateway'] = gateway iface_xml = InterfaceModel()._create_iface_xml(iface, net_params) iface = conn.interfaceDefineXML(iface_xml) route = self._get_default_route_entry() gateway = route.gateway new_iface = route.dev conn = LibvirtConnection("qemu:///system").get() conn.changeBegin() save_config(conn, new_iface, gateway) if old_iface and new_iface != old_iface: save_config(conn, old_iface) self._rollback_timer = Timer(self._confirm_timeout, self._rollback_on_failure, args=[old_gateway]) self._rollback_timer.start()
def _save_gateway_changes(self, old_iface, old_gateway): def save_config(conn, iface, gateway=None): n = IPv4Network(get_dev_netaddr(iface)) net_params = {'ipaddr': str(n.ip), 'netmask': str(n.netmask)} if gateway: net_params['gateway'] = gateway iface_xml = InterfaceModel()._create_iface_xml(iface, net_params) iface = conn.interfaceDefineXML(iface_xml) route = self._get_default_route_entry() gateway = route.gateway new_iface = route.dev conn = LibvirtConnection("qemu:///system").get() conn.changeBegin() save_config(conn, new_iface, gateway) if old_iface and new_iface != old_iface: save_config(conn, old_iface) self._rollback_timer = Timer( self._confirm_timeout, self._rollback_on_failure, args=[old_gateway]) self._rollback_timer.start()
def _get_static_config_interface_address(self, name): def _get_ipaddr_info(libvirt_interface_xml): search_ip = \ xpath_get_text(libvirt_interface_xml, "/interface/protocol[@family='ipv4']" "/ip/@address") if not len(search_ip): return '', '' search_prefix = \ xpath_get_text(libvirt_interface_xml, "/interface/protocol[@family='ipv4']" "/ip/@prefix") ip_obj = ipaddr.IPv4Network('%s/%s' % (search_ip[0], search_prefix[0])) return str(ip_obj.ip), str(ip_obj.netmask) conn = LibvirtConnection("qemu:///system").get() iface_obj = conn.interfaceLookupByName(name) iface_libvirt_xml = \ iface_obj.XMLDesc(libvirt.VIR_INTERFACE_XML_INACTIVE) return _get_ipaddr_info(iface_libvirt_xml)
def confirm_change(self, _name): self._rollback_timer.cancel() conn = LibvirtConnection("qemu:///system").get() conn.changeCommit()
def _get_all_libvirt_interfaces(self): conn = LibvirtConnection("qemu:///system").get() return [iface.name() for iface in conn.listAllInterfaces()]
def confirm_change(self, _name): conn = LibvirtConnection("qemu:///system").get() self._rollback_timer.cancel() conn.changeCommit()
children = node['children'] del node['children'] except KeyError: children = [] lines = [] lines.extend([' ~' + line for line in pformat(node).split('\n')]) count = len(children) for i, child in enumerate(children): if count == 1: lines.append(' \-----------------') else: lines.append(' +-----------------') clines = _format_dev_node(child) if i == count - 1: p = ' ' else: p = ' |' lines.extend([p + cline for cline in clines]) lines.append('') return lines if __name__ == '__main__': libvirt_conn = LibvirtConnection('qemu:///system').get() _print_host_dev_tree(libvirt_conn) print 'Eligible passthrough devices:' pprint(get_passthrough_dev_infos(libvirt_conn))