Exemplo n.º 1
0
    def _fetch_external_net_id(self, force=False):
        """Find UUID of single external network for this agent."""
        if self.conf.gateway_external_network_id:
            return self.conf.gateway_external_network_id

        # L3 agent doesn't use external_network_bridge to handle external
        # networks, so bridge_mappings with provider networks will be used
        # and the L3 agent is able to handle any external networks.
        if not self.conf.external_network_bridge:
            return

        if not force and self.target_ex_net_id:
            return self.target_ex_net_id

        try:
            self.target_ex_net_id = self.plugin_rpc.get_external_network_id(
                self.context)
            return self.target_ex_net_id
        except rpc_common.RemoteError as e:
            with excutils.save_and_reraise_exception() as ctx:
                if e.exc_type == 'TooManyExternalNetworks':
                    ctx.reraise = False
                    msg = _(
                        "The 'gateway_external_network_id' option must be "
                        "configured for this agent as Crd has more than "
                        "one external network.")
                    raise Exception(msg)
Exemplo n.º 2
0
 def get_bridge_name_for_port_name(self, port_name):
     try:
         return self.run_vsctl(['port-to-br', port_name], check_error=True)
     except RuntimeError as e:
         with excutils.save_and_reraise_exception() as ctxt:
             if 'Exit code: 1\n' in str(e):
                 ctxt.reraise = False
Exemplo n.º 3
0
def get_bridges(root_helper):
    args = ["ovs-vsctl", "--timeout=%d" % cfg.CONF.ovs_vsctl_timeout,
            "list-br"]
    try:
        return utils.execute(args, root_helper=root_helper).strip().split("\n")
    except Exception as e:
        with excutils.save_and_reraise_exception():
            LOG.exception(_("Unable to retrieve bridges. Exception: %s"), e)
Exemplo n.º 4
0
    def __call__(self, target, creds):
        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.exception(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.exception(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
            f = getattr(manager.CrdManager.get_instance().plugin,
                        'get_%s' % parent_res)
            # f *must* exist, if not found it is better to let crd 
            # explode. Check will be performed with admin context
            context = importutils.import_module('crdservice.context')
            try:
                data = f(context.get_admin_context(),
                         target[parent_foreign_key],
                         fields=[parent_field])
                target[self.target_field] = data[parent_field]
            except Exception:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_('Policy check error while calling %s!'), f)
        match = self.match % target
        if self.kind in creds:
            return match == unicode(creds[self.kind])
        return False
Exemplo n.º 5
0
 def bridge_exists(self, bridge_name):
     try:
         self.run_vsctl(['br-exists', bridge_name], check_error=True)
     except RuntimeError as e:
         with excutils.save_and_reraise_exception() as ctxt:
             if 'Exit code: 2\n' in str(e):
                 ctxt.reraise = False
                 return False
     return True
Exemplo n.º 6
0
 def get_xapi_iface_id(self, xs_vif_uuid):
     args = ["xe", "vif-param-get", "param-name=other-config",
             "param-key=nicira-iface-id", "uuid=%s" % xs_vif_uuid]
     try:
         return utils.execute(args, root_helper=self.root_helper).strip()
     except Exception as e:
         with excutils.save_and_reraise_exception():
             LOG.error(_("Unable to execute %(cmd)s. "
                         "Exception: %(exception)s"),
                       {'cmd': args, 'exception': e})
Exemplo n.º 7
0
 def run_vsctl(self, args, check_error=False):
     full_args = ["ovs-vsctl", "--timeout=%d" % self.vsctl_timeout] + args
     try:
         return utils.execute(full_args, root_helper=self.root_helper)
     except Exception as e:
         with excutils.save_and_reraise_exception() as ctxt:
             LOG.error(_("Unable to execute %(cmd)s. "
                         "Exception: %(exception)s"),
                       {'cmd': full_args, 'exception': e})
             if not check_error:
                 ctxt.reraise = False
Exemplo n.º 8
0
def find_child_pids(pid):
    """Retrieve a list of the pids of child processes of the given pid."""

    try:
        raw_pids = execute(['ps', '--ppid', pid, '-o', 'pid='])
    except RuntimeError as e:
        # Unexpected errors are the responsibility of the caller
        with excutils.save_and_reraise_exception() as ctxt:
            # Exception has already been logged by execute
            no_children_found = 'Exit code: 1' in str(e)
            if no_children_found:
                ctxt.reraise = False
                return []
    return [x.strip() for x in raw_pids.split('\n') if x.strip()]
Exemplo n.º 9
0
    def __init__(self, conf):
        self.conf = conf

        dirname = os.path.dirname(cfg.CONF.metadata_proxy_socket)
        if os.path.isdir(dirname):
            try:
                os.unlink(cfg.CONF.metadata_proxy_socket)
            except OSError:
                with excutils.save_and_reraise_exception() as ctxt:
                    if not os.path.exists(cfg.CONF.metadata_proxy_socket):
                        ctxt.reraise = False
        else:
            os.makedirs(dirname, 0o755)

        self._init_state_reporting()
Exemplo n.º 10
0
 def _get_resource(self, context, model, id):
     try:
         r = self._get_by_id(context, model, id)
     except exc.NoResultFound:
         with excutils.save_and_reraise_exception(reraise=False) as ctx:
             if issubclass(model, Vip):
                 raise loadbalancer.VipNotFound(vip_id=id)
             elif issubclass(model, Pool):
                 raise loadbalancer.PoolNotFound(pool_id=id)
             elif issubclass(model, Member):
                 raise loadbalancer.MemberNotFound(member_id=id)
             elif issubclass(model, HealthMonitor):
                 raise loadbalancer.HealthMonitorNotFound(monitor_id=id)
             ctx.reraise = True
     return r
Exemplo n.º 11
0
 def _delete_db_pool(self, context, id):
     # proxy the call until plugin inherits from DBPlugin
     # rely on uuid uniqueness:
     try:
         with context.session.begin(subtransactions=True):
             self.service_type_manager.del_resource_associations(
                 context, [id])
             super(LoadBalancerPlugin, self).delete_pool(context, id)
     except Exception:
         # that should not happen
         # if it's still a case - something goes wrong
         # log the error and mark the pool as ERROR
         LOG.error(_('Failed to delete pool %s, putting it in ERROR state'),
                   id)
         with excutils.save_and_reraise_exception():
             self.update_status(context, ldb.Pool,
                                id, constants.ERROR)
Exemplo n.º 12
0
def load_drivers(service_type, plugin):
    """Loads drivers for specific service.

    Passes plugin instance to driver's constructor
    """
    service_type_manager = sdb.ServiceTypeManager.get_instance()
    providers = (service_type_manager.
                 get_service_providers(
                     None,
                     filters={'service_type': [service_type]})
                 )
    if not providers:
        msg = (_("No providers specified for '%s' service, exiting") %
               service_type)
        LOG.error(msg)
        raise SystemExit(msg)

    drivers = {}
    for provider in providers:
        try:
            drivers[provider['name']] = importutils.import_object(
                provider['driver'], plugin
#                provider['driver']
            )
            LOG.debug(_("Loaded '%(provider)s' provider for service "
                        "%(service_type)s"),
                      {'provider': provider['driver'],
                       'service_type': service_type})
        except ImportError:
            with excutils.save_and_reraise_exception():
                LOG.exception(_("Error loading provider '%(provider)s' for "
                                "service %(service_type)s"),
                              {'provider': provider['driver'],
                               'service_type': service_type})

    default_provider = None
    try:
        provider = service_type_manager.get_default_service_provider(
            None, service_type)
        default_provider = provider['name']
    except pconf.DefaultServiceProviderNotFound:
        LOG.info(_("Default provider is not specified for service type %s"),
                 service_type)

    return drivers, default_provider
Exemplo n.º 13
0
 def __iter__(self):
     """Return a result until we get a 'None' response from consumer"""
     if self._done:
         raise StopIteration
     while True:
         try:
             self._iterator.next()
         except Exception:
             with excutils.save_and_reraise_exception():
                 self.done()
         if self._got_ending:
             self.done()
             raise StopIteration
         result = self._result
         if isinstance(result, Exception):
             self.done()
             raise result
         yield result
Exemplo n.º 14
0
 def __iter__(self):
     """Return a result until we get a reply with an 'ending" flag"""
     if self._done:
         raise StopIteration
     while True:
         try:
             data = self._dataqueue.get(timeout=self._timeout)
             result = self._process_data(data)
         except queue.Empty:
             LOG.exception(_('Timed out waiting for RPC response.'))
             self.done()
             raise rpc_common.Timeout()
         except Exception:
             with excutils.save_and_reraise_exception():
                 self.done()
         if self._got_ending:
             self.done()
             raise StopIteration
         if isinstance(result, Exception):
             self.done()
             raise result
         yield result
Exemplo n.º 15
0
    def create_or_update_agent(self, context, agent):
        """Create or update agent according to report."""

        try:
            return self._create_or_update_agent(context, agent)
        except db_exc.DBDuplicateEntry as e:
            with excutils.save_and_reraise_exception() as ctxt:
                if e.columns == ["agent_type", "host"]:
                    # It might happen that two or more concurrent transactions
                    # are trying to insert new rows having the same value of
                    # (agent_type, host) pair at the same time (if there has
                    # been no such entry in the table and multiple agent status
                    # updates are being processed at the moment). In this case
                    # having a unique constraint on (agent_type, host) columns
                    # guarantees that only one transaction will succeed and
                    # insert a new agent entry, others will fail and be rolled
                    # back. That means we must retry them one more time: no
                    # INSERTs will be issued, because
                    # _get_agent_by_type_and_host() will return the existing
                    # agent entry, which will be updated multiple times
                    ctxt.reraise = False
                    return self._create_or_update_agent(context, agent)