コード例 #1
0
ファイル: services.py プロジェクト: Open-SFC/sfc
    def delete(self, service_id):
        """Delete this Network Service."""
        # ensure service exists before deleting
        services = list(self.conn.get_services(service_id=service_id))

        if len(services) < 1:
            services = list(self.conn.get_services(name=service_id))
            if len(services) < 1:
                raise EntityNotFound(_('Service'), service_id)
            else:
                self.conn.delete_service(name=service_id)
        else:
            self.conn.delete_service(service_id=service_id)

        #UCM Configuration Start
        service = services[0]
        record = {'name': {'type': constants.DATA_TYPES['string'], 'value': str(service.name)},
                  'tenant': {'type': constants.DATA_TYPES['string'], 'value': str(service.tenant)},
                  'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
        try:
            ret_val = ucm.delete_record(record)
            if ret_val != 0:
                error = _("Unable to delete service record from UCM")
                response.translatable_error = error
                raise wsme.exc.ClientSideError(unicode(error))
        except ucm.UCMException, msg:
            LOG.info(_("UCM Exception raised. %s"), msg)
            error = _("Unable to delete service record from UCM")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))
コード例 #2
0
ファイル: switch.py プロジェクト: Open-SFC/cns
    def delete(self, switch_id):
        """Delete this Switch."""
        # ensure switch exists before deleting

        switches = list(self.conn.get_switches(switch_id=switch_id))

        if len(switches) < 1:
            raise EntityNotFound(_('Switch'), switch_id)

        switch = switches[0]
        #UCM Configuration Start
        record = {'name': {'type': constants.DATA_TYPES['string'], 'value': str(switch.name)},
                  'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
        try:
            ret_val = _ucm.delete_record(record)
            LOG.debug(_("return value = %s"), str(ret_val))
            if ret_val != 0:
                error = _("Unable to delete Switch record from UCM")
                response.translatable_error = error
                raise wsme.exc.ClientSideError(unicode(error))
        except UCMException, msg:
            LOG.info(_("UCM Exception raised. %s"), msg)
            error = _("Unable to delete Switch record from UCM")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))
コード例 #3
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             if len(value) > 0:
                 json.loads(value)
             return value
         except Exception:
             raise ValueError(_("String not in JSON format: '%s'") % value)
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #4
0
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             if len(value) > 0:
                 json.loads(value)
             return value
         except Exception:
             raise ValueError(_("String not in JSON format: '%s'") % value)
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #5
0
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             dateutil.parser.parse(value)
             return value
         except Exception:
             raise ValueError(_("Invalid Date string: '%s'") % value)
         return value
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #6
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             dateutil.parser.parse(value)
             return value
         except Exception:
             raise ValueError(_("Invalid Date string: '%s'") % value)
         return value
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #7
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             if is_valid_uri(value):
                 return value
             else:
                 raise ValueError(_("Not valid URI format: '%s'") % value)
         except Exception:
             raise ValueError(_("Not valid URI format: '%s'") % value)
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #8
0
 def validate(value):
     if isinstance(value, six.string_types):
         try:
             if is_valid_uri(value):
                 return value
             else:
                 raise ValueError(_("Not valid URI format: '%s'") % value)
         except Exception:
             raise ValueError(_("Not valid URI format: '%s'") % value)
     raise ValueError(_("Expected String, got '%s'") % value)
コード例 #9
0
ファイル: vnetworks.py プロジェクト: Open-SFC/cns
    def put(self, nw_id, virtualnetwork):
        """
        This function implements update record functionality of the RESTful request.
        It converts the requested body in JSON format to dictionary in string representation and verifies whether
        required ATTRIBUTES are present in the PUT request body and adds the record to UCM if all the
        UCM_ATTRIBUTES are present.

        :return: Dictionary of the added record.
        """

        virtualnetwork.id = nw_id
        virtualnetworks = list(self.conn.get_virtualnetworks(nw_id=virtualnetwork.id))

        if len(virtualnetworks) < 1:
            raise EntityNotFound(_('Virtual Network'), nw_id)

        old_vn = VirtualNetwork.from_db_model(virtualnetworks[0]).as_dict(api_models.VirtualNetwork)
        updated_vn = virtualnetwork.as_dict(api_models.VirtualNetwork)
        old_vn.update(updated_vn)
        try:
            vn_in = api_models.VirtualNetwork(**old_vn)
        except Exception:
            LOG.exception("Error while putting virtual network: %s" % old_vn)
            error = _("Virtual Network incorrect")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        vn_out = self.conn.update_virtualnetwork(vn_in)
        
        #UCM Configuration Start
        if cfg.CONF.api.ucm_support:
            body = vn_out.as_dict()
            ucm_record = utils.generate_ucm_data(self, body, [])
            if UCM_LOADED:
                try:
                    req = {'name': {'type': constants.DATA_TYPES['string'], 'value': str(vn_out.name)},
                           'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
                    try:
                        rec = _ucm.get_exact_record(req)
                        if not rec:
                            error = _("Unable to find Virtual Network record in UCM")
                            response.translatable_error = error
                            raise wsme.exc.ClientSideError(unicode(error))
                    except UCMException, msg:
                        LOG.info(_("UCM Exception raised. %s\n"), msg)
                        error = _("Unable to find Virtual Network record in UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))

                    ret_val = _ucm.update_record(ucm_record)
                    if ret_val != 0:
                        error = _("Unable to add Virtual Network record to UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))
                except UCMException, msg:
                    LOG.info(_("UCM Exception raised. %s\n"), msg)
                    error = _("Unable to Update Virtual Network record to UCM")
                    response.translatable_error = error
                    raise wsme.exc.ClientSideError(unicode(error))
コード例 #10
0
ファイル: switch.py プロジェクト: Open-SFC/cns
    def put(self, switch_id, switch):
        """
        This function implements update record functionality of the RESTful request.
        It converts the requested body in JSON format to dictionary in string representation and verifies whether
        required ATTRIBUTES are present in the PUT request body and adds the record to UCM if all the
        UCM_ATTRIBUTES are present.

        :return: Dictionary of the updated record.
        """

        switch.id = switch_id
        switches = list(self.conn.get_switchs(switch_id=switch.id))

        if len(switches) < 1:
            raise EntityNotFound(_('Switch'), switch_id)

        old_switch = Switch.from_db_model(switches[0]).as_dict(api_models.Switch)
        updated_switch = switch.as_dict(api_models.Switch)
        old_switch.update(updated_switch)
        try:
            sw_in = api_models.Switch(**old_switch)
        except Exception:
            LOG.exception("Error while putting switch: %s" % old_switch)
            error = _("Switch incorrect")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        switch_out = self.conn.update_virtualmachine(sw_in)

        #UCM Support Start
        if cfg.CONF.api.ucm_support:
            body = switch_out.as_dict()
            ucm_record = utils.generate_ucm_data(self, body, [])
            if UCM_LOADED:
                try:
                    req = {'name': {'type': constants.DATA_TYPES['string'], 'value': str(switch.name)},
                           'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
                    try:
                        rec = _ucm.get_exact_record(req)
                        if not rec:
                            error = _("Unable to find Switch record in UCM")
                            response.translatable_error = error
                            raise wsme.exc.ClientSideError(unicode(error))
                    except UCMException, msg:
                        LOG.info(_("UCM Exception raised. %s\n"), msg)
                        error = _("Unable to find Switch record in UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))

                    ret_val = _ucm.update_record(ucm_record)
                    if ret_val != 0:
                        error = _("Unable to add Switch record to UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))
                except UCMException, msg:
                    LOG.info(_("UCM Exception raised. %s\n"), msg)
                    error = _("Unable to Update Switch record to UCM")
                    response.translatable_error = error
                    raise wsme.exc.ClientSideError(unicode(error))
コード例 #11
0
ファイル: domain.py プロジェクト: Open-SFC/cns
    def post(self, domain):
        """
        This function implements create record functionality of the RESTful request.
        It converts the requested body in JSON format to dictionary in string representation and verifies whether
        required ATTRIBUTES are present in the POST request body and adds the record to DB and UCM if all the
        UCM_ATTRIBUTES are present.

        :return: Dictionary of the added record.
        """
        change = domain.as_dict(api_models.Domain)
        change['ttp_name'] = 'DATA_CENTER_VIRTUAL_SWITCH_TTP'

        domains = list(self.conn.get_domains(name=domain.name))

        if len(domains) > 0:
            error = _("Domain with the given name exists")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        try:
            domain_in = api_models.Domain(**change)
        except Exception:
            LOG.exception("Error while posting Domain: %s" % change)
            error = _("Domain incorrect")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        domain_out = self.conn.create_domain(domain_in)

        #UCM Support Start
        #if cfg.CONF.api.ucm_support:
        #    body = domain_out.as_dict()
        #    ucm_record = utils.generate_ucm_data(self, body, [])
        #    if UCM_LOADED:
        #        try:
        #            ret_val = _ucm.add_record(ucm_record)
        #            if ret_val != 0:
        #                error = _("Unable to add Domain record to UCM")
        #                response.translatable_error = error
        #                raise wsme.exc.ClientSideError(unicode(error))
        #        except UCMException, msg:
        #            LOG.info(_("UCM Exception raised. %s\n"), msg)
        #            error = _("Unable to add Domain record to UCM")
        #            response.translatable_error = error
        #            raise wsme.exc.ClientSideError(unicode(error))
        #UCM Support End

        return DomainResp(**({'domain': Domain.from_db_model(domain_out)}))
コード例 #12
0
def report_deprecated_feature(logger, msg, *args, **kwargs):
    """Call this function when a deprecated feature is used.

    If the system is configured for fatal deprecations then the message
    is logged at the 'critical' level and :class:`DeprecatedConfig` will
    be raised.

    Otherwise, the message will be logged (once) at the 'warn' level.

    :raises: :class:`DeprecatedConfig` if the system is configured for
             fatal deprecations.
    """
    stdmsg = _("Deprecated: %s") % msg
    register_options()
    if CONF.fatal_deprecations:
        logger.critical(stdmsg, *args, **kwargs)
        raise DeprecatedConfig(msg=stdmsg)

    # Using a list because a tuple with dict can't be stored in a set.
    sent_args = _deprecated_messages_sent.setdefault(msg, list())

    if args in sent_args:
        # Already logged this message, so don't log it again.
        return

    sent_args.append(args)
    logger.warn(stdmsg, *args, **kwargs)
コード例 #13
0
def report_deprecated_feature(logger, msg, *args, **kwargs):
    """Call this function when a deprecated feature is used.

    If the system is configured for fatal deprecations then the message
    is logged at the 'critical' level and :class:`DeprecatedConfig` will
    be raised.

    Otherwise, the message will be logged (once) at the 'warn' level.

    :raises: :class:`DeprecatedConfig` if the system is configured for
             fatal deprecations.
    """
    stdmsg = _("Deprecated: %s") % msg
    register_options()
    if CONF.fatal_deprecations:
        logger.critical(stdmsg, *args, **kwargs)
        raise DeprecatedConfig(msg=stdmsg)

    # Using a list because a tuple with dict can't be stored in a set.
    sent_args = _deprecated_messages_sent.setdefault(msg, list())

    if args in sent_args:
        # Already logged this message, so don't log it again.
        return

    sent_args.append(args)
    logger.warning(stdmsg, *args, **kwargs)
コード例 #14
0
ファイル: types.py プロジェクト: iawells/gluon
 def validate(self, value):
     for t in self.types:
         try:
             return wtypes.validate_value(t, value)
         except (exception.InvalidUUID, ValueError):
             pass
     else:
         raise ValueError(_("Expected '%(type)s', got '%(value)s'") % {"type": self.types, "value": type(value)})
コード例 #15
0
ファイル: vmachines.py プロジェクト: Open-SFC/cns
    def post(self, virtualmachine):
        """
        This function implements create record functionality of the RESTful request.
        It converts the requested body in JSON format to dictionary in string representation and verifies whether
        required ATTRIBUTES are present in the POST request body and adds the record to DB and UCM if all the
        UCM_ATTRIBUTES are present.

        :return: Dictionary of the added record.
        """

        change = virtualmachine.as_dict(api_models.VirtualMachine)

        virtualmachines = list(self.conn.get_virtualmachines(vm_id=virtualmachine.id))

        if len(virtualmachines) > 0:
            error = _("Virtual Machine with the given id exists")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        try:
            vm_in = api_models.VirtualMachine(**change)
        except Exception:
            LOG.exception("Error while posting Virtual Machine: %s" % change)
            error = _("Virtual Machine incorrect")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        vm_out = self.conn.create_virtualmachine(vm_in)

        # UCM Configuration Start
        if cfg.CONF.api.ucm_support:
            body = vm_out.as_dict()
            ucm_record = utils.generate_ucm_data(self, body, [])
            if UCM_LOADED:
                try:
                    ret_val = _ucm.add_record(ucm_record)
                    if ret_val != 0:
                        error = _("Unable to add virtual machine record to UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))
                except UCMException, msg:
                    LOG.info(_("UCM Exception raised. %s\n"), msg)
                    error = _("Unable to add virtual machine record to UCM")
                    response.translatable_error = error
                    raise wsme.exc.ClientSideError(unicode(error))
コード例 #16
0
ファイル: vmachines.py プロジェクト: Open-SFC/cns
    def get_one(self, vm_id):
        """Return this virtual machine."""

        virtualmachines = list(self.conn.get_virtualmachines(vm_id=vm_id))

        if len(virtualmachines) < 1:
            raise EntityNotFound(_('Virtual Machine'), vm_id)

        return VirtualMachineResp(**({'virtualmachine': VirtualMachine.from_db_model(virtualmachines[0])}))
コード例 #17
0
ファイル: vnetworks.py プロジェクト: Open-SFC/cns
    def get_one(self, nw_id):
        """Return this virtual network."""

        virtualnetworks = list(self.conn.get_virtualnetworks(nw_id=nw_id))

        if len(virtualnetworks) < 1:
            raise EntityNotFound(_('Virtual Network'), nw_id)

        return VirtualNetworkResp(**({'virtualnetwork': VirtualNetwork.from_db_model(virtualnetworks[0])}))
コード例 #18
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(self, value):
     for t in self.types:
         try:
             return wtypes.validate_value(t, value)
         except ValueError:
             pass
     else:
         raise ValueError(_("Expected '%(type)s', got '%(value)s'")
                          % {'type': self.types, 'value': type(value)})
コード例 #19
0
class GluonException(Exception):
    """Base Gluon Exception

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.

    """
    message = _("An unknown exception occurred.")
    code = 500

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass

        if message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception as e:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception('Exception in string format operation')
            for name, value in kwargs.items():
                LOG.error("%(name)s: %(value)s" % {
                    'name': name,
                    'value': value
                })
            try:
                if CONF.fatal_exception_format_errors:
                    raise e
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise e

        super(GluonException, self).__init__(self.message)

    def __str__(self):
        if six.PY3:
            return self.message
        return self.message.encode('utf-8')

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)
コード例 #20
0
ファイル: datapath.py プロジェクト: Open-SFC/cns
    def get_one(self, datapath_id):
        """Return this datapath."""

        datapaths = list(self.conn.get_datapaths(datapath_id=datapath_id))

        if len(datapaths) < 1:
            raise EntityNotFound(_('Datapath'), datapath_id)

        return DatapathResp(**({'datapath': Datapath.from_db_model(datapaths[0])}))
コード例 #21
0
ファイル: vnetworks.py プロジェクト: Open-SFC/cns
    def get_one(self, nw_id, sub_id):
        """Return this virtual network."""

        subnets = list(self.conn.get_subnets(nw_id=nw_id, sub_id=sub_id))

        if len(subnets) < 1:
            raise EntityNotFound(_('Subnet'), sub_id)
        for sub in subnets:
            sub.pools = self.pools_from_db_model(sub.pools, final=True)

        return SubnetResp(**({'subnet': Subnet.from_db_model(subnets[0])}))
コード例 #22
0
ファイル: domain.py プロジェクト: Open-SFC/cns
    def get_one(self, domain_id):
        """Return this domain."""

        domains = list(self.conn.get_domains(domain_id=domain_id))

        if len(domains) < 1:
            domains = list(self.conn.get_domains(name=domain_id))
            if len(domains) < 1:
                raise EntityNotFound(_('Domain'), domain_id)

        return DomainResp(**({'domain': Domain.from_db_model(domains[0])}))
コード例 #23
0
ファイル: services.py プロジェクト: Open-SFC/sfc
    def get_one(self, service_id):
        """Return this Network Service."""
        services = list(self.conn.get_services(service_id=service_id))

        if len(services) < 1:
            services = list(self.conn.get_services(name=service_id))
            if len(services) < 1:
                raise EntityNotFound(_('Service'), service_id)

        return ServiceResp(**(
            {'service': Service.from_db_model(services[0])}))
コード例 #24
0
ファイル: switch.py プロジェクト: Open-SFC/cns
    def get_one(self, switch_id):
        """Return this Switch."""

        switches = list(self.conn.get_switches(switch_id=switch_id))

        if len(switches) < 1:
            switches = list(self.conn.get_switches(name=switch_id))
            if len(switches) < 1:
                raise EntityNotFound(_('Switch'), switch_id)

        return SwitchResp(**({'switch': Switch.from_db_model(switches[0])}))
コード例 #25
0
ファイル: log.py プロジェクト: fvukelic/flocx-market
class LogConfigError(Exception):

    message = _('Error loading logging config %(log_config)s: %(err_msg)s')

    def __init__(self, log_config, err_msg):
        self.log_config = log_config
        self.err_msg = err_msg

    def __str__(self):
        return self.message % dict(log_config=self.log_config,
                                   err_msg=self.err_msg)
コード例 #26
0
 def validate(self, value):
     for t in self.types:
         try:
             return wtypes.validate_value(t, value)
         except ValueError:
             pass
     else:
         raise ValueError(
             _("Expected '%(type)s', got '%(value)s'") % {
                 'type': self.types,
                 'value': type(value)
             })
コード例 #27
0
ファイル: vnetworks.py プロジェクト: Open-SFC/cns
    def delete(self, nw_id):
        """Delete this Virtual Network."""
        # ensure virtual network exists before deleting

        virtualnetworks = list(self.conn.get_virtualnetworks(nw_id=nw_id))

        if len(virtualnetworks) < 1:
            raise EntityNotFound(_('Virtual Network'), nw_id)

        #UCM Configuration Start
        record = {'name': {'type': constants.DATA_TYPES['string'], 'value': str(virtualnetworks[0].name)},
                  'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
        try:
            ret_val = _ucm.delete_record(record)
            LOG.debug(_("return value = %s"), str(ret_val))
            if ret_val != 0:
                error = _("Unable to delete Virtual Network record from UCM")
                response.translatable_error = error
                raise wsme.exc.ClientSideError(unicode(error))
        except UCMException, msg:
            LOG.info(_("UCM Exception raised. %s"), msg)
            error = _("Unable to delete Virtual Network record from UCM")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))
コード例 #28
0
ファイル: datapath.py プロジェクト: Open-SFC/cns
    def delete(self, datapath_id):
        """Delete this datapath."""
        # ensure datapath exists before deleting

        datapaths = list(self.conn.get_datapaths(datapath_id=datapath_id))

        if len(datapaths) < 1:
            raise EntityNotFound(_('Datapath'), datapath_id)

        #UCM Configuration Start
        record = {'datapathid': {'type': constants.DATA_TYPES['uint64'], 'value': str(datapath_id)},
                  'dmpath': constants.PATH_PREFIX + '.' + self.dmpath}
        try:
            ret_val = _ucm.delete_record(record)
            LOG.debug(_("return value = %s"), str(ret_val))
            if ret_val != 0:
                error = _("Unable to delete datapath record from UCM")
                response.translatable_error = error
                raise wsme.exc.ClientSideError(unicode(error))
        except UCMException, msg:
            LOG.info(_("UCM Exception raised. %s"), msg)
            error = _("Unable to delete datapath record from UCM")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))
コード例 #29
0
ファイル: api.py プロジェクト: Open-SFC/nscs
    def __init__(self):
        engine = get_engine()

        modconf = configparser.ConfigParser()
        confbase = os.path.dirname(cfg.CONF.config_file[0])
        res_modules = list()
        for cnf in os.listdir(confbase + "/modules"):
            if ".conf" in cnf:
                modconf.read(str(confbase + "/modules/" + cnf))
                mod = modconf.get("DEFAULT", "resource_module")
                res_modules.append(str(mod.split(":")[1]))

        for res in res_modules:
            try:
                __import__(res + ".db", fromlist=["*"])
            except ImportError:
                LOG.info(_("Invalid Resource. No DB schema found."))

        Base.metadata.create_all(engine)
コード例 #30
0
ファイル: log.py プロジェクト: XiaoDongZhi/oslo.log
def _find_facility_from_conf(conf):
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       conf.syslog_log_facility,
                       None)

    if facility is None and conf.syslog_log_facility in facility_names:
        facility = facility_names.get(conf.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
                  'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
                  'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',
                  'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3',
                  'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7']
        valid_facilities.extend(consts)
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return facility
コード例 #31
0
def _find_facility_from_conf(conf):
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       conf.syslog_log_facility,
                       None)

    if facility is None and conf.syslog_log_facility in facility_names:
        facility = facility_names.get(conf.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
                  'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
                  'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',
                  'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3',
                  'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7']
        valid_facilities.extend(consts)
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return facility
コード例 #32
0
ファイル: impl_sqlalchemy.py プロジェクト: Open-SFC/nscs
    def __init__(self, engine):
        url = cfg.CONF.database.connection
        if url == 'sqlite://':
            cfg.CONF.database.connection = \
                os.environ.get('NSCSAS_TEST_SQL_URL', url)

        modconf = configparser.ConfigParser()
        confbase = os.path.dirname(cfg.CONF.config_file[0])
        res_modules = list()
        for cnf in os.listdir(confbase + '/modules'):
            if '.conf' in cnf:
                modconf.read(str(confbase + '/modules/' + cnf))
                mod = modconf.get("DEFAULT","resource_module")
                res_modules.append(str(mod.split(':')[1]))

        for res in res_modules:
            try:
                __import__(res + '.db', fromlist=['*'])
            except ImportError:
                LOG.info(_("Invalid Resource. No DB schema found."))

        Base.metadata.create_all(engine)
コード例 #33
0
ファイル: log.py プロジェクト: khandranagarajan/oslo.log
def _find_facility(facility):
    # NOTE(jd): Check the validity of facilities at run time as they differ
    # depending on the OS and Python version being used.
    valid_facilities = [f for f in
                        ["LOG_KERN", "LOG_USER", "LOG_MAIL",
                         "LOG_DAEMON", "LOG_AUTH", "LOG_SYSLOG",
                         "LOG_LPR", "LOG_NEWS", "LOG_UUCP",
                         "LOG_CRON", "LOG_AUTHPRIV", "LOG_FTP",
                         "LOG_LOCAL0", "LOG_LOCAL1", "LOG_LOCAL2",
                         "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5",
                         "LOG_LOCAL6", "LOG_LOCAL7"]
                        if getattr(syslog, f, None)]

    facility = facility.upper()

    if not facility.startswith("LOG_"):
        facility = "LOG_" + facility

    if facility not in valid_facilities:
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return getattr(syslog, facility)
コード例 #34
0
ファイル: log.py プロジェクト: fvukelic/flocx-market
def _find_facility(facility):
    # NOTE(jd): Check the validity of facilities at run time as they differ
    # depending on the OS and Python version being used.
    valid_facilities = [f for f in
                        ["LOG_KERN", "LOG_USER", "LOG_MAIL",
                         "LOG_DAEMON", "LOG_AUTH", "LOG_SYSLOG",
                         "LOG_LPR", "LOG_NEWS", "LOG_UUCP",
                         "LOG_CRON", "LOG_AUTHPRIV", "LOG_FTP",
                         "LOG_LOCAL0", "LOG_LOCAL1", "LOG_LOCAL2",
                         "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5",
                         "LOG_LOCAL6", "LOG_LOCAL7"]
                        if getattr(syslog, f, None)]

    facility = facility.upper()

    if not facility.startswith("LOG_"):
        facility = "LOG_" + facility

    if facility not in valid_facilities:
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return getattr(syslog, facility)
コード例 #35
0
ファイル: log.py プロジェクト: varunarya10/oslo.log
def _find_facility_from_conf(conf):
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler, conf.syslog_log_facility, None)

    if facility is None and conf.syslog_log_facility in facility_names:
        facility = facility_names.get(conf.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = [
            "LOG_AUTH",
            "LOG_AUTHPRIV",
            "LOG_CRON",
            "LOG_DAEMON",
            "LOG_FTP",
            "LOG_KERN",
            "LOG_LPR",
            "LOG_MAIL",
            "LOG_NEWS",
            "LOG_AUTH",
            "LOG_SYSLOG",
            "LOG_USER",
            "LOG_UUCP",
            "LOG_LOCAL0",
            "LOG_LOCAL1",
            "LOG_LOCAL2",
            "LOG_LOCAL3",
            "LOG_LOCAL4",
            "LOG_LOCAL5",
            "LOG_LOCAL6",
            "LOG_LOCAL7",
        ]
        valid_facilities.extend(consts)
        raise TypeError(_("syslog facility must be one of: %s") % ", ".join("'%s'" % fac for fac in valid_facilities))

    return facility
コード例 #36
0
class EndpointNotFound(GluonClientException):
    message = _("Could not find Service or Region in Service Catalog.")
コード例 #37
0
class DeprecatedConfig(Exception):
    message = _("Fatal call to deprecated config: %(msg)s")

    def __init__(self, msg):
        super(Exception, self).__init__(self.message % dict(msg=msg))
コード例 #38
0
class EndpointTypeNotFound(GluonClientException):
    message = _("Could not find endpoint type %(type_)s in Service Catalog.")
コード例 #39
0

LOG = logging.getLogger(__name__)
CONF = cfg.CONF
_DEPRECATED_EXCEPTIONS = set()


deprecated_opts = [
    cfg.BoolOpt('fatal_deprecations',
                default=False,
                help='Enables or disables fatal status of deprecations.'),
]


_deprecated_msg_with_alternative = _(
    '%(what)s is deprecated as of %(as_of)s in favor of '
    '%(in_favor_of)s and may be removed in %(remove_in)s.')

_deprecated_msg_no_alternative = _(
    '%(what)s is deprecated as of %(as_of)s and may be '
    'removed in %(remove_in)s. It will not be superseded.')

_deprecated_msg_with_alternative_no_removal = _(
    '%(what)s is deprecated as of %(as_of)s in favor of %(in_favor_of)s.')

_deprecated_msg_with_no_alternative_no_removal = _(
    '%(what)s is deprecated as of %(as_of)s. It will not be superseded.')


_RELEASES = {
    # NOTE(morganfainberg): Bexar is used for unit test purposes, it is
コード例 #40
0
 def validate(value):
     if isinstance(value, six.string_types) and netaddr.valid_mac(value):
         return value
     raise ValueError(_("Expected MAC String, got '%s'") % value)
コード例 #41
0
class AlreadyExists(Conflict):
    message = _("Object of %(cls)s with %(key)s \"%(value)s\" already exists.")
コード例 #42
0
ファイル: log.py プロジェクト: fvukelic/flocx-market
def _setup_logging_from_conf(conf, project, version):
    log_root = getLogger(None).logger

    # Remove all handlers
    for handler in list(log_root.handlers):
        log_root.removeHandler(handler)

    logpath = _get_log_file_path(conf)
    if logpath:
        # On Windows, in-use files cannot be moved or deleted.
        if conf.watch_log_file and platform.system() == 'Linux':
            from oslo_log import watchers
            file_handler = watchers.FastWatchedFileHandler
            filelog = file_handler(logpath)
        elif conf.log_rotation_type.lower() == "interval":
            file_handler = logging.handlers.TimedRotatingFileHandler
            when = conf.log_rotate_interval_type.lower()
            interval_type = LOG_ROTATE_INTERVAL_MAPPING[when]
            # When weekday is configured, "when" has to be a value between
            # 'w0'-'w6' (w0 for Monday, w1 for Tuesday, and so on)'
            if interval_type == 'w':
                interval_type = interval_type + str(conf.log_rotate_interval)
            filelog = file_handler(logpath,
                                   when=interval_type,
                                   interval=conf.log_rotate_interval,
                                   backupCount=conf.max_logfile_count)
        elif conf.log_rotation_type.lower() == "size":
            file_handler = logging.handlers.RotatingFileHandler
            maxBytes = conf.max_logfile_size_mb * units.Mi
            filelog = file_handler(logpath,
                                   maxBytes=maxBytes,
                                   backupCount=conf.max_logfile_count)
        else:
            file_handler = logging.handlers.WatchedFileHandler
            filelog = file_handler(logpath)

        log_root.addHandler(filelog)

    if conf.use_stderr:
        streamlog = handlers.ColorHandler()
        log_root.addHandler(streamlog)

    if conf.use_journal:
        journal = handlers.OSJournalHandler()
        log_root.addHandler(journal)

    if conf.use_eventlog:
        if platform.system() == 'Windows':
            eventlog = logging.handlers.NTEventLogHandler(project)
            log_root.addHandler(eventlog)
        else:
            raise RuntimeError(_("Windows Event Log is not available on this "
                                 "platform."))

    # if None of the above are True, then fall back to standard out
    if not logpath and not conf.use_stderr and not conf.use_journal:
        # pass sys.stdout as a positional argument
        # python2.6 calls the argument strm, in 2.7 it's stream
        streamlog = handlers.ColorHandler(sys.stdout)
        log_root.addHandler(streamlog)

    if conf.publish_errors:
        handler = importutils.import_object(
            "oslo_messaging.notify.log_handler.PublishErrorsHandler",
            logging.ERROR)
        log_root.addHandler(handler)

    if conf.use_syslog:
        global syslog
        if syslog is None:
            raise RuntimeError("syslog is not available on this platform")
        facility = _find_facility(conf.syslog_log_facility)
        syslog_handler = handlers.OSSysLogHandler(facility=facility)
        log_root.addHandler(syslog_handler)

    datefmt = conf.log_date_format
    if not conf.use_json:
        for handler in log_root.handlers:
            handler.setFormatter(formatters.ContextFormatter(project=project,
                                                             version=version,
                                                             datefmt=datefmt,
                                                             config=conf))
    else:
        for handler in log_root.handlers:
            handler.setFormatter(formatters.JSONFormatter(datefmt=datefmt))
    _refresh_root_level(conf.debug)

    for pair in conf.default_log_levels:
        mod, _sep, level_name = pair.partition('=')
        logger = logging.getLogger(mod)
        numeric_level = None
        try:
            # NOTE(harlowja): integer's are valid level names, and for some
            # libraries they have a lower level than DEBUG that is typically
            # defined at level 5, so to make that accessible, try to convert
            # this to a integer, and if not keep the original...
            numeric_level = int(level_name)
        except ValueError:  # nosec
            pass
        if numeric_level is not None:
            logger.setLevel(numeric_level)
        else:
            logger.setLevel(level_name)

    if conf.rate_limit_burst >= 1 and conf.rate_limit_interval >= 1:
        from oslo_log import rate_limit
        rate_limit.install_filter(conf.rate_limit_burst,
                                  conf.rate_limit_interval,
                                  conf.rate_limit_except)
コード例 #43
0
class InvalidConfigurationOption(GluonClientException):
    """An error due to an invalid configuration option value."""

    message = _("An invalid value for configuration option %(opt_name): "
                "%(opt_value)")
コード例 #44
0
class MalformedResponseBody(GluonClientException):
    message = _("Malformed response body: %(reason)s")
コード例 #45
0
class SslCertificateValidationError(GluonClientException):
    message = _("SSL certificate validation has failed: %(reason)s")
コード例 #46
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(self, value):
     if isinstance(value, six.string_types) and re.match(self.regex, value):
         return value
     raise ValueError(_("Expected Email String, got '%s'") % value)
コード例 #47
0
class InvalidContentType(GluonClientException):
    message = _("Invalid content type %(content_type)s.")
コード例 #48
0
ファイル: types.py プロジェクト: openstack/gluon
 def validate(value):
     if isinstance(value, six.string_types) and netaddr.valid_mac(value):
         return value
     raise ValueError(_("Expected MAC String, got '%s'") % value)
コード例 #49
0
class BackendDoesNotExsist(GluonException):
    code = 409
    message = _("Backend with name %(name)s does not exsist.")
コード例 #50
0
class PolicyCheckError(GluonClientException):
    """An error due to a policy check failure."""

    message = _("Failed to check policy %(policy)s because %(reason)s.")
コード例 #51
0
ファイル: switch.py プロジェクト: Open-SFC/cns
from oslo_log import log as logging
from oslo_log._i18n import _
from . import model as api_models
from . import db as cns_db

LOG = logging.getLogger(__name__)

#UCM Support Start
UCM_LOADED = False
if cfg.CONF.api.ucm_support:
    try:
        import _ucm
        from _ucm import UCMException
        UCM_LOADED = True
    except ImportError:
        LOG.info(_("Unable to Load UCM"))
#UCM Support End


class Switch(_Base):
    """
    Representation of Switch Structure
    """
    id = BoundedStr(minlen=36, maxlen=36)
    "The UUID of the switch"

    name = BoundedStr(maxlen=16)
    "The name for the switch"

    fqdn = BoundedStr(maxlen=96)
    "Switch FQDN"
コード例 #52
0
class PolicyInitError(GluonClientException):
    """An error due to policy initialization failure."""

    message = _("Failed to initialize policy %(policy)s because %(reason)s.")
コード例 #53
0
ファイル: services.py プロジェクト: Open-SFC/sfc
    def post(self, service):
        """
        This function implements create record functionality of the RESTful request.
        It converts the requested body in JSON format to dictionary in string representation and verifies whether
        required ATTRIBUTES are present in the POST request body and adds the record to DB and UCM if all the
        UCM_ATTRIBUTES are present.

        :return: Dictionary of the added record.
        """

        change = service.as_dict(api_models.Service)

        services = list(self.conn.get_services(service_id=service.id))

        if len(services) > 0:
            error = _("Network Service with the given id exists")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        if change['form_factor_type'].lower() == 'physical':
            change['form_factor_type'] = 'Physical'
        elif change['form_factor_type'].lower() == 'virtual':
            change['form_factor_type'] = 'Virtual'

        change['type'] = change['type'].capitalize()
        if change['load_share_algorithm'].lower() == 'round_robin':
            change['load_share_algorithm'] = 'Round_Robin'
        elif change['load_share_algorithm'].lower() == 'hash_based':
            change['load_share_algorithm'] = 'Hash_Based'
        elif change['load_share_algorithm'].lower() == 'least_connections':
            change['load_share_algorithm'] = 'Least_Connections'

        if change['load_indication_type'].lower() == 'connection_based':
            change['load_indication_type'] = 'Connection_Based'
        elif change['load_indication_type'].lower() == 'traffic_based':
            change['load_indication_type'] = 'Traffic_Based'

        try:
            service_in = api_models.Service(**change)
        except Exception:
            LOG.exception("Error while posting Network Service: %s" % change)
            error = _("Network service incorrect")
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        service_out = self.conn.create_service(service_in)

        # UCM Configuration Start
        if cfg.CONF.api.ucm_support:
            body = service_out.as_dict()
            ucm_record = utils.generate_ucm_data(self, body, [])
            if UCM_LOADED:
                try:
                    ret_val = ucm.add_record(ucm_record)
                    if ret_val != 0:
                        error = _("Unable to add chain record to UCM")
                        response.translatable_error = error
                        raise wsme.exc.ClientSideError(unicode(error))
                except ucm.UCMException, msg:
                    LOG.info(_("UCM Exception raised. %s\n"), msg)
                    error = _("Unable to add chain record to UCM")
                    response.translatable_error = error
                    raise wsme.exc.ClientSideError(unicode(error))
コード例 #54
0
class NotFound(GluonException):
    code = 404
    message = _("Object of %(cls)s with Primay Key %(key)s not found.")
コード例 #55
0
ファイル: versionutils.py プロジェクト: tc1989tc/oslo.log
class deprecated(object):
    """A decorator to mark callables as deprecated.

    This decorator logs a deprecation message when the callable it decorates is
    used. The message will include the release where the callable was
    deprecated, the release where it may be removed and possibly an optional
    replacement. It also logs a message when a deprecated exception is being
    caught in a try-except block, but not when subclasses of that exception
    are being caught.

    Examples:

    1. Specifying the required deprecated release

    >>> @deprecated(as_of=deprecated.ICEHOUSE)
    ... def a(): pass

    2. Specifying a replacement:

    >>> @deprecated(as_of=deprecated.ICEHOUSE, in_favor_of='f()')
    ... def b(): pass

    3. Specifying the release where the functionality may be removed:

    >>> @deprecated(as_of=deprecated.ICEHOUSE, remove_in=+1)
    ... def c(): pass

    4. Specifying the deprecated functionality will not be removed:

    >>> @deprecated(as_of=deprecated.ICEHOUSE, remove_in=None)
    ... def d(): pass

    5. Specifying a replacement, deprecated functionality will not be removed:

    >>> @deprecated(as_of=deprecated.ICEHOUSE, in_favor_of='f()',
    ...             remove_in=None)
    ... def e(): pass

    .. warning::

       The hook used to detect when a deprecated exception is being
       *caught* does not work under Python 3. Deprecated exceptions
       are still logged if they are thrown.

    """

    # NOTE(morganfainberg): Bexar is used for unit test purposes, it is
    # expected we maintain a gap between Bexar and Folsom in this list.
    BEXAR = 'B'
    FOLSOM = 'F'
    GRIZZLY = 'G'
    HAVANA = 'H'
    ICEHOUSE = 'I'
    JUNO = 'J'
    KILO = 'K'
    LIBERTY = 'L'
    MITAKA = 'M'
    NEWTON = 'N'
    OCATA = 'O'

    _RELEASES = {
        # NOTE(morganfainberg): Bexar is used for unit test purposes, it is
        # expected we maintain a gap between Bexar and Folsom in this list.
        'B': 'Bexar',
        'F': 'Folsom',
        'G': 'Grizzly',
        'H': 'Havana',
        'I': 'Icehouse',
        'J': 'Juno',
        'K': 'Kilo',
        'L': 'Liberty',
        'M': 'Mitaka',
        'N': 'Newton',
        'O': 'Ocata',
    }

    _deprecated_msg_with_alternative = _(
        '%(what)s is deprecated as of %(as_of)s in favor of '
        '%(in_favor_of)s and may be removed in %(remove_in)s.')

    _deprecated_msg_no_alternative = _(
        '%(what)s is deprecated as of %(as_of)s and may be '
        'removed in %(remove_in)s. It will not be superseded.')

    _deprecated_msg_with_alternative_no_removal = _(
        '%(what)s is deprecated as of %(as_of)s in favor of %(in_favor_of)s.')

    _deprecated_msg_with_no_alternative_no_removal = _(
        '%(what)s is deprecated as of %(as_of)s. It will not be superseded.')

    def __init__(self, as_of, in_favor_of=None, remove_in=2, what=None):
        """Initialize decorator

        :param as_of: the release deprecating the callable. Constants
            are define in this class for convenience.
        :param in_favor_of: the replacement for the callable (optional)
        :param remove_in: an integer specifying how many releases to wait
            before removing (default: 2)
        :param what: name of the thing being deprecated (default: the
            callable's name)

        """
        self.as_of = as_of
        self.in_favor_of = in_favor_of
        self.remove_in = remove_in
        self.what = what

    def __call__(self, func_or_cls):
        if not self.what:
            self.what = func_or_cls.__name__ + '()'
        msg, details = self._build_message()

        if inspect.isfunction(func_or_cls):

            @six.wraps(func_or_cls)
            def wrapped(*args, **kwargs):
                report_deprecated_feature(LOG, msg, details)
                return func_or_cls(*args, **kwargs)

            return wrapped
        elif inspect.isclass(func_or_cls):
            orig_init = func_or_cls.__init__

            # TODO(tsufiev): change `functools` module to `six` as
            # soon as six 1.7.4 (with fix for passing `assigned`
            # argument to underlying `functools.wraps`) is released
            # and added to the oslo-incubator requrements
            @functools.wraps(orig_init, assigned=('__name__', '__doc__'))
            def new_init(self, *args, **kwargs):
                if self.__class__ in _DEPRECATED_EXCEPTIONS:
                    report_deprecated_feature(LOG, msg, details)
                orig_init(self, *args, **kwargs)

            func_or_cls.__init__ = new_init
            _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            if issubclass(func_or_cls, Exception):
                # NOTE(dhellmann): The subclasscheck is called,
                # sometimes, to test whether a class matches the type
                # being caught in an exception. This lets us warn
                # folks that they are trying to catch an exception
                # that has been deprecated. However, under Python 3
                # the test for whether one class is a subclass of
                # another has been optimized so that the abstract
                # check is only invoked in some cases. (See
                # PyObject_IsSubclass in cpython/Objects/abstract.c
                # for the short-cut.)
                class ExceptionMeta(type):
                    def __subclasscheck__(self, subclass):
                        if self in _DEPRECATED_EXCEPTIONS:
                            report_deprecated_feature(LOG, msg, details)
                        return super(ExceptionMeta,
                                     self).__subclasscheck__(subclass)

                func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
                _DEPRECATED_EXCEPTIONS.add(func_or_cls)

            return func_or_cls
        else:
            raise TypeError('deprecated can be used only with functions or '
                            'classes')

    def _get_safe_to_remove_release(self, release):
        # TODO(dstanek): this method will have to be reimplemented once
        #    when we get to the X release because once we get to the Y
        #    release, what is Y+2?
        remove_in = self.remove_in
        if remove_in is None:
            remove_in = 0
        new_release = chr(ord(release) + remove_in)
        if new_release in self._RELEASES:
            return self._RELEASES[new_release]
        else:
            return new_release

    def _build_message(self):
        details = dict(what=self.what,
                       as_of=self._RELEASES[self.as_of],
                       remove_in=self._get_safe_to_remove_release(self.as_of))

        if self.in_favor_of:
            details['in_favor_of'] = self.in_favor_of
            if self.remove_in is not None and self.remove_in > 0:
                msg = self._deprecated_msg_with_alternative
            else:
                # There are no plans to remove this function, but it is
                # now deprecated.
                msg = self._deprecated_msg_with_alternative_no_removal
        else:
            if self.remove_in is not None and self.remove_in > 0:
                msg = self._deprecated_msg_no_alternative
            else:
                # There are no plans to remove this function, but it is
                # now deprecated.
                msg = self._deprecated_msg_with_no_alternative_no_removal
        return msg, details
コード例 #56
0
class ConnectionFailed(GluonClientException):
    message = _("Connection to Gluon failed: %(reason)s")
コード例 #57
0
 def validate(self, value):
     if isinstance(value, six.string_types) and re.match(self.regex, value):
         return value
     raise ValueError(_("Expected Email String, got '%s'") % value)
コード例 #58
0
class AmbiguousEndpoints(GluonClientException):
    message = _("Found more than one matching endpoint in Service Catalog: "
                "%(matching_endpoints)")
コード例 #59
0
class Conflict(GluonException):
    message = _('Conflict.')
    code = 409
コード例 #60
0
class InvalidFileFormat(GluonClientException):
    """An error due to a invalid API specification file."""
    message = _("Invalid file format")