Beispiel #1
0
    def deprecated(self, msg, *args, **kwargs):
        """Call this method 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
        if CONF.fatal_deprecations:
            self.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 = self._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)
        self.warn(stdmsg, *args, **kwargs)
Beispiel #2
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
    CONF.register_opts(deprecated_opts)
    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)
Beispiel #3
0
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)
Beispiel #4
0
 def _extract_bytes(self, details):
     # Replace it with the byte amount
     real_size = self.SIZE_RE.search(details)
     if not real_size:
         raise ValueError(_('Invalid input value "%s".') % details)
     magnitude = real_size.group(1)
     unit_of_measure = real_size.group(2)
     bytes_info = real_size.group(3)
     if bytes_info:
         return int(real_size.group(4))
     elif not unit_of_measure:
         return int(magnitude)
     return strutils.string_to_bytes('%s%sB' % (magnitude, unit_of_measure),
                                     return_int=True)
Beispiel #5
0
 def _extract_bytes(self, details):
     # Replace it with the byte amount
     real_size = self.SIZE_RE.search(details)
     if not real_size:
         raise ValueError(_('Invalid input value "%s".') % details)
     magnitude = real_size.group(1)
     unit_of_measure = real_size.group(2)
     bytes_info = real_size.group(3)
     if bytes_info:
         return int(real_size.group(4))
     elif not unit_of_measure:
         return int(magnitude)
     return strutils.string_to_bytes('%s%sB' % (magnitude, unit_of_measure),
                                     return_int=True)
Beispiel #6
0
 def _extract_details(self, root_cmd, root_details, lines_after):
     real_details = root_details
     if root_cmd == 'backing_file':
         # Replace it with the real backing file
         backing_match = self.BACKING_FILE_RE.match(root_details)
         if backing_match:
             real_details = backing_match.group(2).strip()
     elif root_cmd in ['virtual_size', 'cluster_size', 'disk_size']:
         # Replace it with the byte amount (if we can convert it)
         if root_details == 'None':
             real_details = 0
         else:
             real_details = self._extract_bytes(root_details)
     elif root_cmd == 'file_format':
         real_details = real_details.strip().lower()
     elif root_cmd == 'snapshot_list':
         # Next line should be a header, starting with 'ID'
         if not lines_after or not lines_after.pop(0).startswith("ID"):
             msg = _("Snapshot list encountered but no header found!")
             raise ValueError(msg)
         real_details = []
         # This is the sprintf pattern we will try to match
         # "%-10s%-20s%7s%20s%15s"
         # ID TAG VM SIZE DATE VM CLOCK (current header)
         while lines_after:
             line = lines_after[0]
             line_pieces = line.split()
             if len(line_pieces) != 6:
                 break
             # Check against this pattern in the final position
             # "%02d:%02d:%02d.%03d"
             date_pieces = line_pieces[5].split(":")
             if len(date_pieces) != 3:
                 break
             lines_after.pop(0)
             real_details.append({
                 'id':
                 line_pieces[0],
                 'tag':
                 line_pieces[1],
                 'vm_size':
                 line_pieces[2],
                 'date':
                 line_pieces[3],
                 'vm_clock':
                 line_pieces[4] + " " + line_pieces[5],
             })
     return real_details
Beispiel #7
0
    def set_rules(self, rules, overwrite=True, use_conf=False):
        """Create a new Rules object based on the provided dict of rules.

        :param rules: New rules to use. It should be an instance of dict.
        :param overwrite: Whether to overwrite current rules or update them
                          with the new rules.
        :param use_conf: Whether to reload rules from cache or config file.
        """

        if not isinstance(rules, dict):
            raise TypeError(_("Rules must be an instance of dict or Rules, "
                            "got %s instead") % type(rules))
        self.use_conf = use_conf
        if overwrite:
            self.rules = Rules(rules, self.default_rule)
        else:
            self.rules.update(rules)
Beispiel #8
0
    def set_rules(self, rules, overwrite=True, use_conf=False):
        """Create a new Rules object based on the provided dict of rules.

        :param rules: New rules to use. It should be an instance of dict.
        :param overwrite: Whether to overwrite current rules or update them
                          with the new rules.
        :param use_conf: Whether to reload rules from cache or config file.
        """

        if not isinstance(rules, dict):
            raise TypeError(
                _("Rules must be an instance of dict or Rules, "
                  "got %s instead") % type(rules))
        self.use_conf = use_conf
        if overwrite:
            self.rules = Rules(rules, self.default_rule)
        else:
            self.rules.update(rules)
Beispiel #9
0
 def _extract_details(self, root_cmd, root_details, lines_after):
     real_details = root_details
     if root_cmd == 'backing_file':
         # Replace it with the real backing file
         backing_match = self.BACKING_FILE_RE.match(root_details)
         if backing_match:
             real_details = backing_match.group(2).strip()
     elif root_cmd in ['virtual_size', 'cluster_size', 'disk_size']:
         # Replace it with the byte amount (if we can convert it)
         if root_details == 'None':
             real_details = 0
         else:
             real_details = self._extract_bytes(root_details)
     elif root_cmd == 'file_format':
         real_details = real_details.strip().lower()
     elif root_cmd == 'snapshot_list':
         # Next line should be a header, starting with 'ID'
         if not lines_after or not lines_after.pop(0).startswith("ID"):
             msg = _("Snapshot list encountered but no header found!")
             raise ValueError(msg)
         real_details = []
         # This is the sprintf pattern we will try to match
         # "%-10s%-20s%7s%20s%15s"
         # ID TAG VM SIZE DATE VM CLOCK (current header)
         while lines_after:
             line = lines_after[0]
             line_pieces = line.split()
             if len(line_pieces) != 6:
                 break
             # Check against this pattern in the final position
             # "%02d:%02d:%02d.%03d"
             date_pieces = line_pieces[5].split(":")
             if len(date_pieces) != 3:
                 break
             lines_after.pop(0)
             real_details.append({
                 'id': line_pieces[0],
                 'tag': line_pieces[1],
                 'vm_size': line_pieces[2],
                 'date': line_pieces[3],
                 'vm_clock': line_pieces[4] + " " + line_pieces[5],
             })
     return real_details
Beispiel #10
0
def _find_facility_from_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
Beispiel #11
0
class InvalidPeriodicTaskArg(Exception):
    message = _("Unexpected argument for periodic task creation: %(arg)s.")
Beispiel #12
0
 def __init__(self, rule):
     msg = _("Policy doesn't allow %s to be performed.") % rule
     super(PolicyNotAuthorized, self).__init__(msg)
Beispiel #13
0
import re

from oslo.config import cfg
from oslo_serialization import jsonutils
import six
import six.moves.urllib.parse as urlparse
import six.moves.urllib.request as urlrequest

from ironic.openstack.common import fileutils
from ironic.openstack.common._i18n import _, _LE, _LI
from ironic.openstack.common import log as logging

policy_opts = [
    cfg.StrOpt('policy_file',
               default='policy.json',
               help=_('The JSON file that defines policies.')),
    cfg.StrOpt('policy_default_rule',
               default='default',
               help=_('Default rule. Enforced when a requested rule is not '
                      'found.')),
    cfg.MultiStrOpt('policy_dirs',
                    default=['policy.d'],
                    help=_('Directories where policy configuration files are '
                           'stored. They can be relative to any directory '
                           'in the search path defined by the config_dir '
                           'option, or absolute paths. The file defined by '
                           'policy_file must exist for these directories to '
                           'be searched.')),
]

CONF = cfg.CONF
Beispiel #14
0
 def __init__(self, rule):
     msg = _("Policy doesn't allow %s to be performed.") % rule
     super(PolicyNotAuthorized, self).__init__(msg)
Beispiel #15
0
from oslo.config import cfg
from oslo_serialization import jsonutils
import six
import six.moves.urllib.parse as urlparse
import six.moves.urllib.request as urlrequest

from ironic.openstack.common import fileutils
from ironic.openstack.common._i18n import _, _LE, _LI
from ironic.openstack.common import log as logging


policy_opts = [
    cfg.StrOpt('policy_file',
               default='policy.json',
               help=_('The JSON file that defines policies.')),
    cfg.StrOpt('policy_default_rule',
               default='default',
               help=_('Default rule. Enforced when a requested rule is not '
                      'found.')),
    cfg.MultiStrOpt('policy_dirs',
                    default=['policy.d'],
                    help=_('Directories where policy configuration files are '
                           'stored. They can be relative to any directory '
                           'in the search path defined by the config_dir '
                           'option, or absolute paths. The file defined by '
                           'policy_file must exist for these directories to '
                           'be searched.')),
]

CONF = cfg.CONF
Beispiel #16
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))