Пример #1
0
def load_class_by_alias_or_classname(namespace, name):
    """Load class using stevedore alias or the class name

    Load class using the stevedore driver manager
    :param namespace: namespace where the alias is defined
    :param name: alias or class name of the class to be loaded
    :returns class if calls can be loaded
    :raises ImportError if class cannot be loaded
    """

    if not name:
        LOG.error(_LE("Alias or class name is not set"))
        raise ImportError(_("Class not found."))
    try:
        # Try to resolve class by alias
        mgr = driver.DriverManager(namespace, name)
        class_to_load = mgr.driver
    except RuntimeError:
        e1_info = sys.exc_info()
        # Fallback to class name
        try:
            class_to_load = importutils.import_class(name)
        except (ImportError, ValueError):
            LOG.error(_LE("Error loading class by alias"),
                      exc_info=e1_info)
            LOG.error(_LE("Error loading class by class name"),
                      exc_info=True)
            raise ImportError(_("Class not found."))
    return class_to_load
Пример #2
0
def load_class_by_alias_or_classname(namespace, name):
    """Load class using stevedore alias or the class name

    Load class using the stevedore driver manager
    :param namespace: namespace where the alias is defined
    :param name: alias or class name of the class to be loaded
    :returns class if calls can be loaded
    :raises ImportError if class cannot be loaded
    """

    if not name:
        LOG.error(_LE("Alias or class name is not set"))
        raise ImportError(_("Class not found."))
    try:
        # Try to resolve class by alias
        mgr = driver.DriverManager(namespace, name)
        class_to_load = mgr.driver
    except RuntimeError:
        e1_info = sys.exc_info()
        # Fallback to class name
        try:
            class_to_load = importutils.import_class(name)
        except (ImportError, ValueError):
            LOG.error(_LE("Error loading class by alias"), exc_info=e1_info)
            LOG.error(_LE("Error loading class by class name"), exc_info=True)
            raise ImportError(_("Class not found."))
    return class_to_load
Пример #3
0
 def delete(self, plugin, context, vnf_id):
     nova = self._nova_client()
     try:
         instance = nova.servers.get(vnf_id)
     except self._novaclient.exceptions.NotFound:
         LOG.error(_LE("server %s is not found") % vnf_id)
         return
     instance.delete()
Пример #4
0
 def delete(self, plugin, context, vnf_id):
     nova = self._nova_client()
     try:
         instance = nova.servers.get(vnf_id)
     except self._novaclient.exceptions.NotFound:
         LOG.error(_LE("server %s is not found") %
                   vnf_id)
         return
     instance.delete()
Пример #5
0
    def _create_device_wait(self, context, device_dict, auth_attr):
        driver_name = self._infra_driver_name(device_dict)
        device_id = device_dict['id']
        instance_id = self._instance_id(device_dict)
        create_failed = False

        try:
            self._device_manager.invoke(
                driver_name, 'create_wait', plugin=self, context=context,
                device_dict=device_dict, device_id=instance_id,
                auth_attr=auth_attr)
        except vnfm.DeviceCreateWaitFailed as e:
            LOG.error(_LE("VNF Create failed for vnf_id %s"), device_id)
            create_failed = True
            device_dict['status'] = constants.ERROR
            self.set_device_error_status_reason(context, device_id,
                                                six.text_type(e))

        if instance_id is None or create_failed:
            mgmt_url = None
        else:
            # mgmt_url = self.mgmt_url(context, device_dict)
            # FIXME(yamahata):
            mgmt_url = device_dict['mgmt_url']

        self._create_device_post(
            context, device_id, instance_id, mgmt_url, device_dict)
        self.mgmt_create_post(context, device_dict)

        if instance_id is None or create_failed:
            return

        device_dict['mgmt_url'] = mgmt_url

        kwargs = {
            mgmt_constants.KEY_ACTION: mgmt_constants.ACTION_CREATE_DEVICE,
            mgmt_constants.KEY_KWARGS: {'device': device_dict},
        }
        new_status = constants.ACTIVE
        try:
            self.mgmt_call(context, device_dict, kwargs)
        except MgmtDriverException:
            LOG.error(_('VNF configuration failed'))
            new_status = constants.ERROR
            self.set_device_error_status_reason(context, device_id,
            'Unable to configure VDU')
        device_dict['status'] = new_status
        mgmt_url = ast.literal_eval(device_dict['mgmt_url'])
        if new_status == 'ACTIVE':
            for VDU, vnfc_info in device_dict['vnfc'].items():
                vnfc_info['mgmt_url'] = mgmt_url[VDU]
                self._vnfc_driver_manager.invoke('ssh', 'vnfc_call',device=device_dict,kwargs=vnfc_info)
        self._create_device_status(context, device_id, new_status)
Пример #6
0
    def _create_vnf_wait(self, context, vnf_dict, auth_attr, driver_name):
        vnf_id = vnf_dict['id']
        instance_id = self._instance_id(vnf_dict)
        create_failed = False

        try:
            self._vnf_manager.invoke(driver_name,
                                     'create_wait',
                                     plugin=self,
                                     context=context,
                                     vnf_dict=vnf_dict,
                                     vnf_id=instance_id,
                                     auth_attr=auth_attr)
        except vnfm.VNFCreateWaitFailed as e:
            LOG.error(_LE("VNF Create failed for vnf_id %s"), vnf_id)
            create_failed = True
            evt_details = "VNF create wait failed"
            vnf_dict['status'] = constants.ERROR
            self.set_vnf_error_status_reason(context, vnf_id, six.text_type(e))

        if instance_id is None or create_failed:
            mgmt_url = None
        else:
            # mgmt_url = self.mgmt_url(context, vnf_dict)
            # FIXME(yamahata):
            mgmt_url = vnf_dict['mgmt_url']

        self._create_vnf_post(context, vnf_id, instance_id, mgmt_url, vnf_dict)
        self.mgmt_create_post(context, vnf_dict)

        if instance_id is None or create_failed:
            return

        vnf_dict['mgmt_url'] = mgmt_url

        kwargs = {
            mgmt_constants.KEY_ACTION: mgmt_constants.ACTION_CREATE_VNF,
            mgmt_constants.KEY_KWARGS: {
                'vnf': vnf_dict
            },
        }
        new_status = constants.ACTIVE
        try:
            self.mgmt_call(context, vnf_dict, kwargs)
        except exceptions.MgmtDriverException:
            LOG.error(_('VNF configuration failed'))
            new_status = constants.ERROR
            self.set_vnf_error_status_reason(context, vnf_id,
                                             'Unable to configure VDU')
        vnf_dict['status'] = new_status
        self._create_vnf_status(context, vnf_id, new_status)
        evt_details = "VNF Configuration Failed, unable to configure VDU"
Пример #7
0
    def _create_vnf_wait(self, context, vnf_dict, auth_attr, driver_name):
        vnf_id = vnf_dict["id"]
        instance_id = self._instance_id(vnf_dict)
        create_failed = False

        try:
            self._vnf_manager.invoke(
                driver_name,
                "create_wait",
                plugin=self,
                context=context,
                vnf_dict=vnf_dict,
                vnf_id=instance_id,
                auth_attr=auth_attr,
            )
        except vnfm.VNFCreateWaitFailed as e:
            LOG.error(_LE("VNF Create failed for vnf_id %s"), vnf_id)
            create_failed = True
            vnf_dict["status"] = constants.ERROR
            self.set_vnf_error_status_reason(context, vnf_id, six.text_type(e))

        if instance_id is None or create_failed:
            mgmt_url = None
        else:
            # mgmt_url = self.mgmt_url(context, vnf_dict)
            # FIXME(yamahata):
            mgmt_url = vnf_dict["mgmt_url"]

        self._create_vnf_post(context, vnf_id, instance_id, mgmt_url, vnf_dict)
        self.mgmt_create_post(context, vnf_dict)

        if instance_id is None or create_failed:
            return

        vnf_dict["mgmt_url"] = mgmt_url

        kwargs = {
            mgmt_constants.KEY_ACTION: mgmt_constants.ACTION_CREATE_VNF,
            mgmt_constants.KEY_KWARGS: {"vnf": vnf_dict},
        }
        new_status = constants.ACTIVE
        try:
            self.mgmt_call(context, vnf_dict, kwargs)
        except exceptions.MgmtDriverException:
            LOG.error(_("VNF configuration failed"))
            new_status = constants.ERROR
            self.set_vnf_error_status_reason(context, vnf_id, "Unable to configure VDU")
        vnf_dict["status"] = new_status
        self._create_vnf_status(context, vnf_id, new_status)
Пример #8
0
    def __call__(self, target, creds, enforcer):
        if self.target_field not in target:
            # policy needs a plugin check
            # target field is in the form resource:field
            # however if they're not separated by a colon, use an underscore
            # as a separator for backward compatibility

            def do_split(separator):
                parent_res, parent_field = self.target_field.split(
                    separator, 1)
                return parent_res, parent_field

            for separator in (':', '_'):
                try:
                    parent_res, parent_field = do_split(separator)
                    break
                except ValueError:
                    LOG.debug("Unable to find ':' as separator in %s.",
                              self.target_field)
            else:
                # If we are here split failed with both separators
                err_reason = (_("Unable to find resource name in %s") %
                              self.target_field)
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(
                    policy="%s:%s" % (self.kind, self.match),
                    reason=err_reason)
            parent_foreign_key = attributes.RESOURCE_FOREIGN_KEYS.get(
                "%ss" % parent_res, None)
            if not parent_foreign_key:
                err_reason = (_("Unable to verify match:%(match)s as the "
                                "parent resource: %(res)s was not found") %
                              {'match': self.match, 'res': parent_res})
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(
                    policy="%s:%s" % (self.kind, self.match),
                    reason=err_reason)
            # NOTE(salv-orlando): This check currently assumes the parent
            # resource is handled by the core plugin. It might be worth
            # having a way to map resources to plugins so to make this
            # check more general
            # NOTE(ihrachys): if import is put in global, circular
            # import failure occurs
            manager = importutils.import_module('tacker.manager')
            f = getattr(manager.TackerManager.get_instance().plugin,
                        'get_%s' % parent_res)
            # f *must* exist, if not found it is better to let tacker
            # explode. Check will be performed with admin context
            context = importutils.import_module('tacker.context')
            try:
                data = f(context.get_admin_context(),
                         target[parent_foreign_key],
                         fields=[parent_field])
                target[self.target_field] = data[parent_field]
            except exceptions.NotFound as e:
                # NOTE(kevinbenton): a NotFound exception can occur if a
                # list operation is happening at the same time as one of
                # the parents and its children being deleted. So we issue
                # a RetryRequest so the API will redo the lookup and the
                # problem items will be gone.
                raise db_exc.RetryRequest(e)
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_LE('Policy check error while calling %s!'),
                                  f)
        match = self.match % target
        if self.kind in creds:
            return match == six.text_type(creds[self.kind])
        return False
    def __call__(self, target, creds, enforcer):
        if self.target_field not in target:
            # policy needs a plugin check
            # target field is in the form resource:field
            # however if they're not separated by a colon, use an underscore
            # as a separator for backward compatibility

            def do_split(separator):
                parent_res, parent_field = self.target_field.split(
                    separator, 1)
                return parent_res, parent_field

            for separator in (':', '_'):
                try:
                    parent_res, parent_field = do_split(separator)
                    break
                except ValueError:
                    LOG.debug("Unable to find ':' as separator in %s.",
                              self.target_field)
            else:
                # If we are here split failed with both separators
                err_reason = (_("Unable to find resource name in %s") %
                              self.target_field)
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(policy="%s:%s" %
                                                  (self.kind, self.match),
                                                  reason=err_reason)
            parent_foreign_key = attributes.RESOURCE_FOREIGN_KEYS.get(
                "%ss" % parent_res, None)
            if not parent_foreign_key:
                err_reason = (_("Unable to verify match:%(match)s as the "
                                "parent resource: %(res)s was not found") % {
                                    'match': self.match,
                                    'res': parent_res
                                })
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(policy="%s:%s" %
                                                  (self.kind, self.match),
                                                  reason=err_reason)
            # NOTE(salv-orlando): This check currently assumes the parent
            # resource is handled by the core plugin. It might be worth
            # having a way to map resources to plugins so to make this
            # check more general
            # NOTE(ihrachys): if import is put in global, circular
            # import failure occurs
            manager = importutils.import_module('tacker.manager')
            f = getattr(manager.TackerManager.get_instance().plugin,
                        'get_%s' % parent_res)
            # f *must* exist, if not found it is better to let tacker
            # explode. Check will be performed with admin context
            context = importutils.import_module('tacker.context')
            try:
                data = f(context.get_admin_context(),
                         target[parent_foreign_key],
                         fields=[parent_field])
                target[self.target_field] = data[parent_field]
            except exceptions.NotFound as e:
                # NOTE(kevinbenton): a NotFound exception can occur if a
                # list operation is happening at the same time as one of
                # the parents and its children being deleted. So we issue
                # a RetryRequest so the API will redo the lookup and the
                # problem items will be gone.
                raise db_exc.RetryRequest(e)
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_LE('Policy check error while calling %s!'),
                                  f)
        match = self.match % target
        if self.kind in creds:
            return match == six.text_type(creds[self.kind])
        return False