def instance_for_image(imgfile, imgfmt, partition): LOG.debug( _("Instance for image imgfile=%(imgfile)s " "imgfmt=%(imgfmt)s partition=%(partition)s"), { 'imgfile': imgfile, 'imgfmt': imgfmt, 'partition': partition }) hasGuestfs = False try: LOG.debug(_("Trying to import guestfs")) importutils.import_module("guestfs") hasGuestfs = True except Exception: pass if hasGuestfs: LOG.debug(_("Using primary VFSGuestFS")) return importutils.import_object( "nova.virt.disk.vfs.guestfs.VFSGuestFS", imgfile, imgfmt, partition) else: LOG.debug(_("Falling back to VFSLocalFS")) return importutils.import_object( "nova.virt.disk.vfs.localfs.VFSLocalFS", imgfile, imgfmt, partition)
def __init__(self, virtapi, read_only=False): super(IronicDriver, self).__init__(virtapi) global ironic if ironic is None: ironic = importutils.import_module('ironicclient') # NOTE(deva): work around a lack of symbols in the current version. if not hasattr(ironic, 'exc'): ironic.exc = importutils.import_module('ironicclient.exc') if not hasattr(ironic, 'client'): ironic.client = importutils.import_module( 'ironicclient.client') self.firewall_driver = firewall.load_driver( default='nova.virt.firewall.NoopFirewallDriver') extra_specs = {} extra_specs["ironic_driver"] = \ "ironic.nova.virt.ironic.driver.IronicDriver" self.extra_specs = extra_specs self.node_cache = {} self.node_cache_time = 0 icli_log_level = CONF.ironic.client_log_level if icli_log_level: level = py_logging.getLevelName(icli_log_level) logger = py_logging.getLogger('ironicclient') logger.setLevel(level)
def _get_impl(): """Delay import of rpc_backend until configuration is loaded.""" global _RPCIMPL if _RPCIMPL is None: try: _RPCIMPL = importutils.import_module(cfg.CONF.rpc_backend) except ImportError: # For backwards compatibility with older nova config. impl = cfg.CONF.rpc_backend.replace("nova.rpc", "nova.openstack.common.rpc") _RPCIMPL = importutils.import_module(impl) return _RPCIMPL
def __init__(self, virtapi, read_only=False): super(IronicDriver, self).__init__(virtapi, read_only) self.ironicAgent = rpcapi.ironicAgentApi() global ironic if ironic is None: ironic = importutils.import_module("ironicclient") if not hasattr(ironic, "exc"): ironic.exc = importutils.import_module("ironicclient.exc") if not hasattr(ironic, "client"): ironic.client = importutils.import_module("ironicclient.client")
def __init__(self, virtapi, read_only=False): super(IronicDriver, self).__init__(virtapi, read_only) self.ironicAgent = rpcapi.ironicAgentApi() global ironic if ironic is None: ironic = importutils.import_module('ironicclient') if not hasattr(ironic, 'exc'): ironic.exc = importutils.import_module('ironicclient.exc') if not hasattr(ironic, 'client'): ironic.client = importutils.import_module( 'ironicclient.client')
def _get_impl(): """Delay import of rpc_backend until configuration is loaded.""" global _RPCIMPL if _RPCIMPL is None: try: _RPCIMPL = importutils.import_module(CONF.rpc_backend) except ImportError: # For backwards compatibility with older oslo.config. impl = CONF.rpc_backend.replace('nova.rpc', 'nova.openstack.common.rpc') _RPCIMPL = importutils.import_module(impl) return _RPCIMPL
def __init__(self): """Initialise the IronicClientWrapper for use. Initialise IronicClientWrapper by loading ironicclient dynamically so that ironicclient is not a dependency for Nova. """ global ironic if ironic is None: ironic = importutils.import_module('ironicclient') # NOTE(deva): work around a lack of symbols in the current version. if not hasattr(ironic, 'exc'): ironic.exc = importutils.import_module('ironicclient.exc') if not hasattr(ironic, 'client'): ironic.client = importutils.import_module( 'ironicclient.client')
def register_opts(conf): """Registration of options for this driver.""" #NOTE(ewindisch): ZMQ_CTX and matchmaker # are initialized here as this is as good # an initialization method as any. # We memoize through these globals global ZMQ_CTX global matchmaker global CONF if not CONF: conf.register_opts(zmq_opts) CONF = conf # Don't re-set, if this method is called twice. if not ZMQ_CTX: ZMQ_CTX = zmq.Context(conf.rpc_zmq_contexts) if not matchmaker: # rpc_zmq_matchmaker should be set to a 'module.Class' mm_path = conf.rpc_zmq_matchmaker.split('.') mm_module = '.'.join(mm_path[:-1]) mm_class = mm_path[-1] # Only initialize a class. if mm_path[-1][0] not in string.ascii_uppercase: LOG.error(_("Matchmaker could not be loaded.\n" "rpc_zmq_matchmaker is not a class.")) raise RPCException(_("Error loading Matchmaker.")) mm_impl = importutils.import_module(mm_module) mm_constructor = getattr(mm_impl, mm_class) matchmaker = mm_constructor()
def register_opts(conf): """Registration of options for this driver.""" #NOTE(ewindisch): ZMQ_CTX and matchmaker # are initialized here as this is as good # an initialization method as any. # We memoize through these globals global ZMQ_CTX global matchmaker global FLAGS if not FLAGS: conf.register_opts(zmq_opts) FLAGS = conf # Don't re-set, if this method is called twice. if not ZMQ_CTX: ZMQ_CTX = zmq.Context(conf.rpc_zmq_contexts) if not matchmaker: # rpc_zmq_matchmaker should be set to a 'module.Class' mm_path = conf.rpc_zmq_matchmaker.split('.') mm_module = '.'.join(mm_path[:-1]) mm_class = mm_path[-1] # Only initialize a class. if mm_path[-1][0] not in string.ascii_uppercase: LOG.error(_("Matchmaker could not be loaded.\n" "rpc_zmq_matchmaker is not a class.")) raise RPCException(_("Error loading Matchmaker.")) mm_impl = importutils.import_module(mm_module) mm_constructor = getattr(mm_impl, mm_class) matchmaker = mm_constructor()
def __init__(self): """Initialise the IronicClientWrapper for use. Initialise IronicClientWrapper by loading ironicclient dynamically so that ironicclient is not a dependency for Nova. """ global ironic if ironic is None: ironic = importutils.import_module('ironicclient') # NOTE(deva): work around a lack of symbols in the current version. if not hasattr(ironic, 'exc'): ironic.exc = importutils.import_module('ironicclient.exc') if not hasattr(ironic, 'client'): ironic.client = importutils.import_module( 'ironicclient.client')
def __init__(self, read_only=False): global libvirt if libvirt is None: libvirt = importutils.import_module('libvirt') self._wrapped_conn_lock = threading.Lock() self.read_only = read_only
def _get_drivers(): """Instantiates and returns drivers based on the flag values.""" global drivers if not drivers: drivers = [] for notification_driver in CONF.healthnmon_notification_drivers: drivers.append(importutils.import_module(notification_driver)) return drivers
def _print_module(mod_str): mod_obj = None if mod_str.endswith('.__init__'): mod_str = mod_str[:mod_str.rfind(".")] try: mod_obj = importutils.import_module(mod_str) except (ValueError, AttributeError), err: return
def __init__(self, imgfile, imgfmt='raw', partition=None): super(VFSGuestFS, self).__init__(imgfile, imgfmt, partition) global guestfs if guestfs is None: guestfs = importutils.import_module('guestfs') self.handle = None
def _load_backend(self): with self._lock: if not self._backend: # Import the untranslated name if we don't have a mapping backend_path = self._backend_mapping.get( self._backend_name, self._backend_name) backend_mod = importutils.import_module(backend_path) self._backend = backend_mod.get_backend()
def _print_module(mod_str): mod_obj = None if mod_str.endswith('.__init__'): mod_str = mod_str[:mod_str.rfind(".")] try: mod_obj = importutils.import_module(mod_str) except (ValueError, AttributeError), err: return
def __init__(self, imgfile, imgfmt='raw', partition=None): super(VFSGuestFS, self).__init__(imgfile, imgfmt, partition) global guestfs if guestfs is None: guestfs = importutils.import_module('guestfs') self.handle = None
def _load_backend(self): with self._lock: if not self._backend: # Import the untranslated name if we don't have a mapping backend_path = self._backend_mapping.get(self._backend_name, self._backend_name) backend_mod = importutils.import_module(backend_path) self._backend = backend_mod.get_backend()
def _get_filter_classes_from_module(module_name): """Get all filter classes from a module.""" classes = [] module = importutils.import_module(module_name) for obj_name in dir(module): itm = getattr(module, obj_name) if _is_filter_class(itm): classes.append(itm) return classes
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except (ValueError, AttributeError), err: return None
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except (ValueError, AttributeError), err: return None
def _get_filter_classes_from_module(module_name): """Get all filter classes from a module.""" classes = [] module = importutils.import_module(module_name) for obj_name in dir(module): itm = getattr(module, obj_name) if _is_filter_class(itm): classes.append(itm) return classes
def _service_admin_creds(api_version=2): # Import auth_token to have keystone_authtoken settings setup. importutils.import_module('keystoneclient.middleware.auth_token') creds = { 'username': cfg.CONF.keystone_authtoken.admin_user, 'password': cfg.CONF.keystone_authtoken.admin_password, } if api_version >= 3: creds['auth_url'] =\ cfg.CONF.keystone_authtoken.auth_uri.replace('v2.0', 'v3') creds['project_name'] =\ cfg.CONF.keystone_authtoken.admin_tenant_name else: creds['auth_url'] = cfg.CONF.keystone_authtoken.auth_uri creds['tenant_name'] =\ cfg.CONF.keystone_authtoken.admin_tenant_name return creds
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except Exception as e: sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e))) return None
def _service_admin_creds(api_version=2): # Import auth_token to have keystone_authtoken settings setup. importutils.import_module('keystoneclient.middleware.auth_token') creds = { 'username': cfg.CONF.keystone_authtoken.admin_user, 'password': cfg.CONF.keystone_authtoken.admin_password, } if api_version >= 3: creds['auth_url'] =\ cfg.CONF.keystone_authtoken.auth_uri.replace('v2.0', 'v3') creds['project_name'] =\ cfg.CONF.keystone_authtoken.admin_tenant_name else: creds['auth_url'] = cfg.CONF.keystone_authtoken.auth_uri creds['tenant_name'] =\ cfg.CONF.keystone_authtoken.admin_tenant_name return creds
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except Exception as e: sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e))) return None
def load_kvmha_driver(kvmha_driver=None): if not kvmha_driver: kvmha_driver = CONF.kvmha_driver if not kvmha_driver: LOG.error(_("KVM HA driver option required, but not specified")) sys.exit(1) LOG.info(_("Loading KVM HA driver '%s'") % kvmha_driver) return importutils.import_module(kvmha_driver)
def load_network_driver(network_driver=None): if not network_driver: network_driver = CONF.network_driver if not network_driver: LOG.error(_("Network driver option required, but not specified")) sys.exit(1) LOG.info(_("Loading network driver '%s'") % network_driver) return importutils.import_module(network_driver)
def _get_drivers(): """Instantiates and returns drivers based on the flag values.""" global drivers if drivers is None: drivers = [] for notification_driver in CONF.list_notifier_drivers: try: drivers.append(importutils.import_module(notification_driver)) except ImportError as e: drivers.append(ImportFailureNotifier(e)) return drivers
def _get_drivers(): """Instantiates and returns drivers based on the flag values.""" global drivers if not drivers: drivers = [] for notification_driver in FLAGS.list_notifier_drivers: try: drivers.append(importutils.import_module(notification_driver)) except ImportError as e: drivers.append(ImportFailureNotifier(e)) return drivers
def _get_classes_from_module(self, module_name): """Get the classes from a module that match the type we want.""" classes = [] module = importutils.import_module(module_name) for obj_name in dir(module): # Skip objects that are meant to be private. if obj_name.startswith('_'): continue itm = getattr(module, obj_name) if self._is_correct_class(itm): classes.append(itm) return classes
def __init__(self, imgfile, imgfmt='raw', partition=None): super(VFSGuestFS, self).__init__(imgfile, imgfmt, partition) global guestfs if guestfs is None: try: guestfs = importutils.import_module('guestfs') except Exception as e: raise exception.NovaException( _("libguestfs is not installed (%s)") % e) self.handle = None
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except ImportError as ie: sys.stderr.write("%s\n" % str(ie)) return None except Exception: return None
def __init__(self, imgfile, imgfmt='raw', partition=None): super(VFSGuestFS, self).__init__(imgfile, imgfmt, partition) global guestfs if guestfs is None: try: guestfs = importutils.import_module('guestfs') except Exception as e: raise exception.NovaException( _("libguestfs is not installed (%s)") % e) self.handle = None
def _get_classes_from_module(self, module_name): """Get the classes from a module that match the type we want.""" classes = [] module = importutils.import_module(module_name) for obj_name in dir(module): # Skip objects that are meant to be private. if obj_name.startswith('_'): continue itm = getattr(module, obj_name) if self._is_correct_class(itm): classes.append(itm) return classes
def __init__(self, virtapi, get_connection, **kwargs): super(NWFilterFirewall, self).__init__(virtapi) global libvirt if libvirt is None: try: libvirt = importutils.import_module('libvirt') except ImportError: LOG.warn(_LW("Libvirt module could not be loaded. " "NWFilterFirewall will not work correctly.")) self._libvirt_get_connection = get_connection self.static_filters_configured = False self.handle_security_groups = False
def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except ImportError as ie: sys.stderr.write("%s\n" % str(ie)) return None except Exception: return None
def notify(context, publisher_id, event_type, priority, payload): """Sends a notification using the specified driver :param publisher_id: the source worker_type.host of the message :param event_type: the literal type of event (ex. Instance Creation) :param priority: patterned after the enumeration of Python logging levels in the set (DEBUG, WARN, INFO, ERROR, CRITICAL) :param payload: A python dictionary of attributes Outgoing message format includes the above parameters, and appends the following: message_id a UUID representing the id for this notification timestamp the GMT timestamp the notification was sent at The composite message will be constructed as a dictionary of the above attributes, which will then be sent via the transport mechanism defined by the driver. Message example:: {'message_id': str(uuid.uuid4()), 'publisher_id': 'compute.host1', 'timestamp': utils.utcnow(), 'priority': 'WARN', 'event_type': 'compute.create_instance', 'payload': {'instance_id': 12, ... }} """ if priority not in log_levels: raise BadPriorityException( _('%s not in valid priorities') % priority) # Ensure everything is JSON serializable. payload = jsonutils.to_primitive(payload, convert_instances=True) driver = importutils.import_module(FLAGS.notification_driver) msg = dict(message_id=str(uuid.uuid4()), publisher_id=publisher_id, event_type=event_type, priority=priority, payload=payload, timestamp=str(utils.utcnow())) try: driver.notify(context, msg) except Exception, e: LOG.exception(_("Problem '%(e)s' attempting to " "send to notification system. Payload=%(payload)s") % locals())
def __init__(self, virtapi, read_only=False): super(IronicDriver, self).__init__(virtapi) global ironic if ironic is None: ironic = importutils.import_module("ironicclient") # NOTE(deva): work around a lack of symbols in the current version. if not hasattr(ironic, "exc"): ironic.exc = importutils.import_module("ironicclient.exc") if not hasattr(ironic, "client"): ironic.client = importutils.import_module("ironicclient.client") self.firewall_driver = firewall.load_driver(default="nova.virt.firewall.NoopFirewallDriver") self.node_cache = {} self.node_cache_time = 0 # TODO(mrda): Bug ID 1365230 Logging configurability needs # to be addressed icli_log_level = CONF.ironic.client_log_level if icli_log_level: level = py_logging.getLevelName(icli_log_level) logger = py_logging.getLogger("ironicclient") logger.setLevel(level)
def __init__(self, virtapi, get_connection, **kwargs): super(NWFilterFirewall, self).__init__(virtapi) global libvirt if libvirt is None: try: libvirt = importutils.import_module('libvirt') except ImportError: LOG.warn( _LW("Libvirt module could not be loaded. " "NWFilterFirewall will not work correctly.")) self._libvirt_get_connection = get_connection self.static_filters_configured = False self.handle_security_groups = False
def add_driver(notification_driver): """Add a notification driver at runtime.""" # Make sure the driver list is initialized. _get_drivers() if isinstance(notification_driver, basestring): # Load and add try: drivers.append(importutils.import_module(notification_driver)) except ImportError as e: drivers.append(ImportFailureNotifier(e)) else: # Driver is already loaded; just add the object. drivers.append(notification_driver)
def add_driver(notification_driver): """Add a notification driver at runtime.""" # Make sure the driver list is initialized. _get_drivers() if isinstance(notification_driver, basestring): # Load and add try: drivers.append(importutils.import_module(notification_driver)) except ImportError as e: drivers.append(ImportFailureNotifier(e)) else: # Driver is already loaded; just add the object. drivers.append(notification_driver)
def _get_drivers(): """Instantiates and returns drivers based on the flag values.""" global drivers if not drivers: drivers = [] for notification_driver in CONF.healthnmon_notification_drivers: drivers.append(importutils.import_module(notification_driver)) # try: # drivers.append(importutils.import_module(notification_driver)) # except exception.ClassNotFound as e: # LOG.exception(_("Problem in importing notification driver %(notification_driver)s." # % locals())) return drivers
def instance_for_image(imgfile, imgfmt, partition): LOG.debug(_("Instance for image imgfile=%(imgfile)s " "imgfmt=%(imgfmt)s partition=%(partition)s") % locals()) hasGuestfs = False try: LOG.debug(_("Trying to import guestfs")) importutils.import_module("guestfs") hasGuestfs = True except Exception: pass if hasGuestfs: LOG.debug(_("Using primary VFSGuestFS")) return importutils.import_object( "nova.virt.disk.vfs.guestfs.VFSGuestFS", imgfile, imgfmt, partition) else: LOG.debug(_("Falling back to VFSLocalFS")) return importutils.import_object( "nova.virt.disk.vfs.localfs.VFSLocalFS", imgfile, imgfmt, partition)
def _get_drivers(): """Instantiate, cache, and return drivers based on the CONF.""" global _drivers if _drivers is None: _drivers = {} for notification_driver in CONF.notification_driver: try: driver = importutils.import_module(notification_driver) _drivers[notification_driver] = driver except ImportError: LOG.exception(_("Failed to load notifier %s. " "These notifications will not be sent.") % notification_driver) return _drivers.values()
def __init__(self, compute_rmcontext): self.is_active = True self.attempt = 0 self.last_seen = datetime.datetime.min self.last_exception = None self.last_exception_time = None self.compute_rmcontext = compute_rmcontext self.compute_info = {} inventory_driver = importutils.import_module(CONF._compute_inventory_driver) self.driver = utils.check_isinstance( inventory_driver.get_connection(self.compute_rmcontext.rmType), driver.ComputeInventoryDriver ) self.driver.init_rmcontext(compute_rmcontext) self.compute_id = None
def _import_module(mod_str): try: if mod_str.startswith("bin."): imp.load_source(mod_str[4:], os.path.join("bin", mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except (ValueError, AttributeError) as err: return None except ImportError as ie: sys.stderr.write("%s\n" % str(ie)) return None except Exception as e: return None
def __init__(self, virtapi, read_only=False): super(IronicDriver, self).__init__(virtapi) global ironic if ironic is None: ironic = importutils.import_module('ironicclient') # NOTE(deva): work around a lack of symbols in the current version. if not hasattr(ironic, 'exc'): ironic.exc = importutils.import_module('ironicclient.exc') if not hasattr(ironic, 'client'): ironic.client = importutils.import_module( 'ironicclient.client') self.firewall_driver = firewall.load_driver( default='nova.virt.firewall.NoopFirewallDriver') self.node_cache = {} self.node_cache_time = 0 # TODO(mrda): Bug ID 1365230 Logging configurability needs # to be addressed icli_log_level = CONF.ironic.client_log_level if icli_log_level: level = py_logging.getLevelName(icli_log_level) logger = py_logging.getLogger('ironicclient') logger.setLevel(level)
def add_driver(notification_driver): """Add a notification driver at runtime.""" # Make sure the driver list is initialized. _get_drivers() if isinstance(notification_driver, basestring): # Load and add try: driver = importutils.import_module(notification_driver) _drivers[notification_driver] = driver except ImportError: LOG.exception(_("Failed to load notifier %s. " "These notifications will not be sent.") % notification_driver) else: # Driver is already loaded; just add the object. _drivers[notification_driver] = notification_driver
def add_driver(notification_driver): """Add a notification driver at runtime.""" # Make sure the driver list is initialized. _get_drivers() if isinstance(notification_driver, basestring): # Load and add try: driver = importutils.import_module(notification_driver) _drivers[notification_driver] = driver except ImportError: LOG.exception(_("Failed to load notifier %s. " "These notifications will not be sent.") % notification_driver) else: # Driver is already loaded; just add the object. _drivers[notification_driver] = notification_driver
def __init__(self, compute_rmcontext): self.is_active = True self.attempt = 0 self.last_seen = datetime.datetime.min self.last_exception = None self.last_exception_time = None self.compute_rmcontext = compute_rmcontext self.compute_info = {} inventory_driver = \ importutils.import_module(CONF._compute_inventory_driver) self.driver = \ utils.check_isinstance( inventory_driver.get_connection(self.compute_rmcontext.rmType), driver.ComputeInventoryDriver) self.driver.init_rmcontext(compute_rmcontext) self.compute_id = None
def setUp(self): super(LinuxNetworkTestCase, self).setUp() network_driver = FLAGS.network_driver self.driver = importutils.import_module(network_driver) self.driver.db = db self.context = context.RequestContext('testuser', 'testproject', is_admin=True) def get_vifs(_context, instance_id): return [vif for vif in vifs if vif['instance_id'] == instance_id] def get_instance(_context, instance_id): return instances[instance_id] self.stubs.Set(db, 'virtual_interface_get_by_instance', get_vifs) self.stubs.Set(db, 'instance_get', get_instance) self.stubs.Set(db, 'network_get_associated_fixed_ips', get_associated)
def setUp(self): super(LinuxNetworkTestCase, self).setUp() network_driver = FLAGS.network_driver self.driver = importutils.import_module(network_driver) self.driver.db = db self.context = context.RequestContext('testuser', 'testproject', is_admin=True) def get_vifs(_context, instance_id): return [vif for vif in vifs if vif['instance_id'] == instance_id] def get_instance(_context, instance_id): return instances[instance_id] self.stubs.Set(db, 'virtual_interface_get_by_instance', get_vifs) self.stubs.Set(db, 'instance_get', get_instance) self.stubs.Set(db, 'network_get_associated_fixed_ips', get_associated)
def deserialize_remote_exception(conf, data): failure = jsonutils.loads(str(data)) trace = failure.get('tb', []) message = failure.get('message', "") + "\n" + "\n".join(trace) name = failure.get('class') module = failure.get('module') # NOTE(ameade): We DO NOT want to allow just any module to be imported, in # order to prevent arbitrary code execution. if module not in conf.allowed_rpc_exception_modules: return RemoteError(name, failure.get('message'), trace) try: mod = importutils.import_module(module) klass = getattr(mod, name) if not issubclass(klass, Exception): raise TypeError("Can only deserialize Exceptions") failure = klass(*failure.get('args', []), **failure.get('kwargs', {})) except (AttributeError, TypeError, ImportError): return RemoteError(name, failure.get('message'), trace) ex_type = type(failure) str_override = lambda self: message new_ex_type = type(ex_type.__name__ + _REMOTE_POSTFIX, (ex_type, ), { '__str__': str_override, '__unicode__': str_override }) new_ex_type.__module__ = '%s%s' % (module, _REMOTE_POSTFIX) try: # NOTE(ameade): Dynamically create a new exception type and swap it in # as the new type for the exception. This only works on user defined # Exceptions and not core python exceptions. This is important because # we cannot necessarily change an exception message so we must override # the __str__ method. failure.__class__ = new_ex_type except TypeError: # NOTE(ameade): If a core exception then just add the traceback to the # first exception argument. failure.args = (message, ) + failure.args[1:] return failure
def get_instance_by_floating_ip(self, context, address, floating_ip): if floating_ip['fixed_ip_id'] is None: return None db_driver = FLAGS.db_driver db = importutils.import_module(db_driver) fixed_ip = db.fixed_ip_get(context, floating_ip['fixed_ip_id']) # NOTE(tr3buchet): this can be None # NOTE(mikal): we need to return the instance id here because its used # by ec2 (and possibly others) uuid = fixed_ip['instance_uuid'] instance = db.instance_get_by_uuid(context, uuid) compute_api.check_policy(context, 'get', instance) inst = dict(instance.iteritems()) inst['name'] = instance['name'] return inst
def deserialize_remote_exception(conf, data): failure = jsonutils.loads(str(data)) trace = failure.get('tb', []) message = failure.get('message', "") + "\n" + "\n".join(trace) name = failure.get('class') module = failure.get('module') # NOTE(ameade): We DO NOT want to allow just any module to be imported, in # order to prevent arbitrary code execution. if module not in conf.allowed_rpc_exception_modules: return RemoteError(name, failure.get('message'), trace) try: mod = importutils.import_module(module) klass = getattr(mod, name) if not issubclass(klass, Exception): raise TypeError("Can only deserialize Exceptions") failure = klass(*failure.get('args', []), **failure.get('kwargs', {})) except (AttributeError, TypeError, ImportError): return RemoteError(name, failure.get('message'), trace) ex_type = type(failure) str_override = lambda self: message new_ex_type = type(ex_type.__name__ + _REMOTE_POSTFIX, (ex_type,), {'__str__': str_override, '__unicode__': str_override}) new_ex_type.__module__ = '%s%s' % (module, _REMOTE_POSTFIX) try: # NOTE(ameade): Dynamically create a new exception type and swap it in # as the new type for the exception. This only works on user defined # Exceptions and not core python exceptions. This is important because # we cannot necessarily change an exception message so we must override # the __str__ method. failure.__class__ = new_ex_type except TypeError: # NOTE(ameade): If a core exception then just add the traceback to the # first exception argument. failure.args = (message,) + failure.args[1:] return failure