예제 #1
0
    def _ReadPythonModuleConfiguration(self, config_parser):
        """Reads the Python module configuration.

    Args:
      config_parser (ConfigParser): configuration file parser.

    Raises:
      ConfigurationError: if the Python module year of creation cannot
          be converted to a base 10 integer value.
    """
        self.python_module_authors = self._GetOptionalConfigValue(
            config_parser,
            'python_module',
            'authors',
            default_value=self.project_authors)
        self.python_module_name = 'py{0:s}'.format(self.library_name_suffix)
        self.python_module_year_of_creation = self._GetOptionalConfigValue(
            config_parser, 'python_module', 'year_of_creation')

        if not self.python_module_year_of_creation:
            self.python_module_year_of_creation = self.project_year_of_creation
        else:
            try:
                self.python_module_year_of_creation = int(
                    self.python_module_year_of_creation, 10)
            except ValueError:
                raise errors.ConfigurationError(
                    'Invalid Python module year of creation: {0!s}'.format(
                        self.python_module_year_of_creation))
예제 #2
0
  def _ReadProjectConfiguration(self, config_parser):
    """Reads the project configuration.

    Args:
      config_parser (ConfigParser): configuration file parser.

    Raises:
      ConfigurationError: if the project year of creation cannot
          be converted to a base 10 integer value.
    """
    self.project_name = self._GetConfigValue(
        config_parser, 'project', 'name')

    self.project_data_format = self._GetOptionalConfigValue(
        config_parser, 'project', 'data_format', default_value='')

    project_description = ''
    if self.project_data_format:
      project_description = (
          '{0:s} is a library to access the {1:s} format.'.format(
              self.project_name, self.project_data_format))
    self.project_description = self._GetOptionalConfigValue(
        config_parser, 'project', 'description',
        default_value=project_description)

    project_authors = ['Joachim Metz <*****@*****.**>']
    self.project_authors = self._GetOptionalConfigValue(
        config_parser, 'project', 'authors', default_value=project_authors)

    self.project_documentation_url = self._GetOptionalConfigValue(
        config_parser, 'project', 'documentation_url')

    project_downloads_url = 'https://github.com/libyal/{0:s}/releases'.format(
        self.project_name)
    self.project_downloads_url = self._GetOptionalConfigValue(
        config_parser, 'project', 'downloads_url',
        default_value=project_downloads_url)

    project_git_url = 'https://github.com/libyal/{0:s}.git'.format(
        self.project_name)
    self.project_git_url = self._GetOptionalConfigValue(
        config_parser, 'project', 'git_url', default_value=project_git_url)

    self.project_status = self._GetConfigValue(
        config_parser, 'project', 'status')
    self.project_year_of_creation = self._GetConfigValue(
        config_parser, 'project', 'year_of_creation')

    try:
      self.project_year_of_creation = int(self.project_year_of_creation, 10)
    except ValueError:
      raise errors.ConfigurationError(
          'Invalid project year of creation: {0!s}'.format(
              self.project_year_of_creation))

    features = self._GetOptionalConfigValue(
        config_parser, u'project', u'features', default_value=[])

    self.supports_debug_output = 'debug_output' in features
예제 #3
0
파일: webservice.py 프로젝트: qa1/Pontiac
 def __init__(self, *args, **kwargs):
     self.queue = kwargs.pop('queue')
     self.number_requests = 0
     try:
         self.schema = json.loads(
             open(settings.SCHEMA['NOTIFICATION']).read())
     except (KeyError, IOError, ValueError):
         raise errors.ConfigurationError('invalid json schema document')
     resource.Resource.__init__(self, *args, **kwargs)
예제 #4
0
 def __init__(self,
              minConnections=3,
              maxConnections=5,
              reconnect=True,
              keepAliveQuery=storagecontroller.KEEPALIVE_QUERY,
              keepAliveInterval=storagecontroller.KEEPALIVE_INTERVAL):
     self.minConnections = minConnections
     self.maxConnections = maxConnections
     self.reconnect = reconnect
     self.keepAliveQuery = keepAliveQuery
     self.keepAliveInterval = keepAliveInterval
     # validate config
     if self.minConnections < 1:
         raise errors.ConfigurationError('minConnections must be >= 1')
     if self.maxConnections > 100:
         raise errors.ConfigurationError('maxConnections must be <= 100')
     if self.keepAliveInterval < storagecontroller.MIN_KEEPALIVE_INTERVAL:
         raise errors.ConfigurationError(
             'maxConnections is specified in seconds. '
             'It must be >= %s' % storagecontroller.MIN_KEEPALIVE_INTERVAL)
예제 #5
0
 def __getitem__(self, key):
     if key in self.overrides:
         val = self.overrides[key]
     elif key in self.obsconfigs:
         val = self.obsconfigs[key]
     elif key in self.defaults:
         val = self.defaults[key]
     else:
         raise errors.ConfigurationError("The configuration '%s' "
                                         "cannot be found!" % key)
     return val
예제 #6
0
파일: creds.py 프로젝트: kusoof/wprof
 def __init__(self, pwd_path):
     try:
         content = open(pwd_path, 'r').read()
     except IOError:
         raise errors.ConfigurationError(
             '%s is missing. Please read workdir/README.' %
             os.path.basename(pwd_path))
     lines = [l.strip() for l in content.splitlines()]
     lines = [l for l in lines if l and not l.startswith('#')]
     self.creds = {}
     for l in lines:
         items = l.split(':', 1)
         self.creds[items[0].strip()] = items[1].strip()
예제 #7
0
 def __getitem__(self, key):
     if key in self.overrides:
         #utils.print_debug("Config '%s' found in Overrides" % key, 'config', stepsback=3)
         val = self.overrides[key]
     elif key in self.obsconfigs:
         #utils.print_debug("Config '%s' found in Observation configs" % key, 'config', stepsback=3)
         val = self.obsconfigs[key]
     elif key in self.defaults:
         #utils.print_debug("Config '%s' found in Default" % key, 'config', stepsback=3)
         val = self.defaults[key]
     else:
         raise errors.ConfigurationError("The configuration '%s' "
                                         "cannot be found!" % key)
     return val
예제 #8
0
파일: notifier.py 프로젝트: qa1/Pontiac
    def connect_apns(self):
        for pem_file in [settings.APNS['cert'], settings.APNS['key']]:
            if not validate_pem_file(pem_file):
                raise errors.ConfigurationError(
                    'APNS PEM file is not valid: {}'.format(pem_file))

        params = {
            'cert': settings.APNS['cert'],
            'key': settings.APNS['key'],
            'release': settings.APNS['dist'],
        }
        if 'proxy' in settings.APNS and settings.APNS['proxy']:
            params.update({'proxy': settings.APNS['proxy']})
        logger.debug('connecting to apns service')
        self.apns_obj = apns_service.APNS(**params)
예제 #9
0
    def __init__(self,
                 name=None,
                 readServers=None,
                 writeServers=None,
                 user=None,
                 password=None,
                 port=3306,
                 sharePool=False,
                 ConnectionPool=None):
        self._readPool = None
        self._writePool = None
        self.name = name
        self.port = port
        self.sharePool = sharePool
        self.readServers = readServers
        self.writeServers = writeServers
        self.user = user
        self.password = password
        if ConnectionPool is not None:
            self.ConnectionPool = ConnectionPoolConfig(**ConnectionPool)
        else:
            self.ConnectionPool = ConnectionPoolConfig()

        # validate config
        if self.name is None:
            raise errors.ConfigurationError('DB.name is None or missing')
        if self.readServers is None or not self.readServers:
            raise errors.ConfigurationError(
                'DB.readServers is None or empty list or missing')
        if self.writeServers is None or not self.writeServers:
            raise errors.ConfigurationError(
                'DB.writeServers is None or empty list or missing')
        if self.user is None:
            raise errors.ConfigurationError('DB.user is None or missing')
        if self.password is None:
            raise errors.ConfigurationError('DB.password is None or missing')
예제 #10
0
    def __init__(self, project_file_path, project_save_path=None):
        vs.setDefaultBackendDevice(0)
        self.calibration_string = None
        self.resolution = SETTINGS.resolution

        self.delay_adjusts = {}
        #listing the audio sources will update the delays
        self.list_audio_sources()

        self.project_file_path = project_file_path
        self.project_save_path = project_save_path if project_save_path else project_file_path
        self.reset(False)

        self.audio_pipe = None

        if SETTINGS.enable_ev_compensation and SETTINGS.enable_metadata_processing:
            raise errors.ConfigurationError(
                'Conflict: both exposure algorithm and metadata processing are enabled'
            )
예제 #11
0
    def _ReadInfoToolConfiguration(self, config_parser):
        """Reads the info tool configuration.

    Args:
      config_parser (ConfigParser): configuration file parser.

    Raises:
      ConfigurationError: if the info tool source type is not supported.
    """
        self.info_tool_source_description = self._GetOptionalConfigValue(
            config_parser, 'info_tool', 'source_description')

        self.info_tool_source_type = self._GetOptionalConfigValue(
            config_parser, 'info_tool', 'source_type')

        if (self.info_tool_source_type and self.info_tool_source_type
                not in ('file', 'image', 'volume')):
            raise errors.ConfigurationError(
                'unsupported info tool source type: {0:s}'.format(
                    self.info_tool_source_type))
예제 #12
0
    def _ReadMountToolConfiguration(self, config_parser):
        """Reads the mount tool configuration.

    Args:
      config_parser (ConfigParser): configuration file parser.

    Raises:
      ConfigurationError: if the mount tool source type is not supported.
    """
        features = self._GetOptionalConfigValue(config_parser,
                                                'mount_tool',
                                                'features',
                                                default_value=[])

        if features:
            self.mount_tool_has_keys_option = 'keys' in features
            self.mount_tool_has_password_option = 'password' in features

        self.mount_tool_additional_arguments = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'additional_arguments')
        self.mount_tool_mounted_description = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'mounted_description')
        self.mount_tool_source = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source')
        self.mount_tool_source_description = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_description')

        # If the long source description is not set it will default to
        # source description.
        self.mount_tool_source_description_long = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_description_long')

        self.mount_tool_source_type = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_type')

        if (self.mount_tool_source_type and self.mount_tool_source_type
                not in ('file', 'image', 'volume')):
            raise errors.ConfigurationError(
                'unsupported mount tool source type: {0:s}'.format(
                    self.mount_tool_source_type))
예제 #13
0
파일: notifier.py 프로젝트: qa1/Pontiac
    def notify(self, *args, **kwargs):
        msg = kwargs.pop('msg')
        expiry_time = msg.pop('expiry_time', None)
        if expiry_time:
            try:
                expiry = datetime.datetime.strptime(expiry_time,
                                                    '%Y-%m-%d %H:%M:%S')
            except ValueError:
                raise errors.DataValidationError(
                    'expiry time is not in a valid format')
            if expiry < datetime.datetime.now():
                logger.info('notification message is expired. dropped.')
                return

        srv_type = msg.pop('type', '')
        if srv_type.lower() == 'fcm':
            self.handle_fcm(*args, **msg)
        elif srv_type.lower() == 'apns':
            self.handle_apns(*args, **msg)
        else:
            raise errors.ConfigurationError(
                'invalid notification service type: {}'.format(srv_type))
예제 #14
0
# -*- coding: utf-8 -*-

from item import Item  # So that wikidata.Item can be used.

from configReader import Config
from api import API

import errors

config = Config('config.py')
if not config["api"]:
    raise errors.ConfigurationError(
        "An API url needs to be defined in config.py")

api = API(config)
예제 #15
0
 def _resolve_database(self, database_name=None):
     db = database_name or self.default_database
     if db is None:
         raise pbx_errors.ConfigurationError('Missing default database')
     return db
예제 #16
0
    def __init__(self, serverConfig, dbConfig, userData, profileData,
                 matchData, profileLogic):
        self.serverConfig = serverConfig
        self.dbConfig = dbConfig
        self.userData = userData
        self.profileData = profileData
        self.matchData = matchData
        self.profileLogic = profileLogic

        self.cipherKey = ('27501fd04e6b82c831024dac5c6305221974deb9388a2190'
                          '1d576cbbe2f377ef23d75486010f37819afe6c321a0146d2'
                          '1544ec365bf7289a')

        self.serverIP_lan = None
        self.serverIP_wan = None
        self.startDatetime = datetime.now()
        reactor.callLater(0, self.setIP)

        # initialize interface to listen on
        self.interface = self.serverConfig.get('ListenOn', '')

        # initialize MaxUsers, set to default if missing from config
        self.serverConfig.MaxUsers = self.serverConfig.get('MaxUsers', 1000)

        self.lobbies = []
        for i, item in enumerate(serverConfig.Lobbies):
            try:
                name = item['name']
            except TypeError:
                name = str(item)
            except KeyError:
                raise errors.ConfigurationError(
                    'Structured lobby definitions must '
                    'include "name" attribute')
            try:
                lobbyType = item['type']
            except TypeError:
                lobbyType = 'open'
            except KeyError:
                lobbyType = 'open'
            try:
                showMatches = item['showMatches']
            except TypeError:
                showMatches = True
            except KeyError:
                showMatches = True
            try:
                checkRosterHash = bool(int(item['checkRosterHash']))
            except:
                checkRosterHash = True

            aLobby = lobby.Lobby(name, 100)
            aLobby.showMatches = showMatches
            aLobby.checkRosterHash = checkRosterHash
            aLobby.typeStr = str(lobbyType)
            if lobbyType == 'noStats':
                aLobby.typeCode = 0x20
            elif lobbyType == 'open':
                aLobby.typeCode = 0x5f
            elif isinstance(lobbyType, list):
                # restricted lobby
                divMap = {'A': 0, '3B': 1, '3A': 2, '2': 3, '1': 4}
                typeCode = 0
                for divName in lobbyType:
                    try:
                        typeCode += 2**divMap[divName]
                    except KeyError:
                        raise errors.ConfigurationError(
                            'Invalid lobby type definition. '
                            'Unrecognized division: "%s" ' % divName)
                aLobby.typeCode = typeCode
            else:
                aLobby.typeCode = 0x5f  # default: open
            self.lobbies.append(aLobby)

        # auto-IP detector site
        try:
            self.ipDetectUri = self.serverConfig.IpDetectUri
        except AttributeError:
            self.ipDetectUri = 'http://mapote.com/cgi-bin/ip.py'

        # rating/points calculator
        self.ratingMath = rating.RatingMath(0.44, 0.56)

        # initialize online-list
        self.onlineUsers = dict()

        # initialize latest-info dict
        self._latestUserInfo = dict()

        # read banned-list, if available
        bannedYaml = self.serverConfig.BannedList
        if not bannedYaml.startswith('/'):
            fsroot = os.environ.get('FSROOT', '.')
            bannedYaml = fsroot + '/' + bannedYaml
        if os.path.exists(bannedYaml):
            self.bannedList = YamlConfig(bannedYaml)
        else:
            self.bannedList = YamlConfig(None, newYamlFile=bannedYaml)
            log.msg('NOTICE: banned-list file absent.')
        try:
            self.bannedList.Banned
        except AttributeError:
            self.bannedList.Banned = []

        # make banned-list structure for quick checks
        self.makeFastBannedList()

        # set up periodical rank-compute
        reactor.callLater(5, self.computeRanks)

        # set up periodical date updates
        now = datetime.now()
        today = datetime(now.year, now.month, now.day)
        td = today + timedelta(days=1) - now
        reactor.callLater(0, self.systemDayChange)
예제 #17
0
def _read_lines(filepath, what):
  try:
    return open(filepath).readlines()
  except IOError:
    raise errors.ConfigurationError('Put the %s in %s' % (what, filepath))
예제 #18
0
    def _ReadMountToolConfiguration(self, config_parser):
        """Reads the mount tool configuration.

    Args:
      config_parser (ConfigParser): configuration file parser.

    Raises:
      ConfigurationError: if the mount tool features or source type is not
          supported.
    """
        self._mount_tool_features = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'features', default_value=[])

        if ('offset' in self._mount_tool_features
                and 'parent' in self._mount_tool_features):
            raise errors.ConfigurationError(
                'unsupported mount tool features - offset and parent cannot be '
                'combined.')

        self.mount_tool_additional_arguments = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'additional_arguments')

        self.mount_tool_base_type = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'base_type')

        self.mount_tool_file_entry_access_time_type = (
            self._GetOptionalConfigValue(config_parser, 'mount_tool',
                                         'file_entry_access_time_type'))

        if (self.mount_tool_file_entry_access_time_type
                and self.mount_tool_file_entry_access_time_type
                not in ('filetime', 'hfs_time', 'nano_posix_time')):
            raise errors.ConfigurationError(
                'unsupported mount tool file entry access time type: {0:s}'.
                format(self.mount_tool_file_entry_access_time_type))

        self.mount_tool_file_entry_access_time_value = (
            self._GetOptionalConfigValue(config_parser,
                                         'mount_tool',
                                         'file_entry_access_time_value',
                                         default_value='access_time'))

        self.mount_tool_file_entry_creation_time_type = (
            self._GetOptionalConfigValue(config_parser, 'mount_tool',
                                         'file_entry_creation_time_type'))

        if (self.mount_tool_file_entry_creation_time_type
                and self.mount_tool_file_entry_creation_time_type
                not in ('filetime', 'hfs_time', 'nano_posix_time')):
            raise errors.ConfigurationError(
                'unsupported mount tool file entry creation time type: {0:s}'.
                format(self.mount_tool_file_entry_creation_time_type))

        self.mount_tool_file_entry_creation_time_value = (
            self._GetOptionalConfigValue(config_parser,
                                         'mount_tool',
                                         'file_entry_creation_time_value',
                                         default_value='creation_time'))

        self.mount_tool_file_entry_inode_change_time_type = (
            self._GetOptionalConfigValue(config_parser, 'mount_tool',
                                         'file_entry_inode_change_time_type'))

        if (self.mount_tool_file_entry_inode_change_time_type
                and self.mount_tool_file_entry_inode_change_time_type
                not in ('filetime', 'hfs_time', 'nano_posix_time')):
            raise errors.ConfigurationError(
                ('unsupported mount tool file entry inode change time type: '
                 '{0:s}').format(
                     self.mount_tool_file_entry_inode_change_time_type))

        self.mount_tool_file_entry_inode_change_time_value = (
            self._GetOptionalConfigValue(config_parser,
                                         'mount_tool',
                                         'file_entry_inode_change_time_value',
                                         default_value='inode_change_time'))

        self.mount_tool_file_entry_modification_time_type = (
            self._GetOptionalConfigValue(config_parser, 'mount_tool',
                                         'file_entry_modification_time_type'))

        if (self.mount_tool_file_entry_modification_time_type
                and self.mount_tool_file_entry_modification_time_type
                not in ('filetime', 'hfs_time', 'nano_posix_time')):
            raise errors.ConfigurationError(
                ('unsupported mount tool file entry modification time type: '
                 '{0:s}').format(
                     self.mount_tool_file_entry_modification_time_type))

        self.mount_tool_file_entry_modification_time_value = (
            self._GetOptionalConfigValue(config_parser,
                                         'mount_tool',
                                         'file_entry_modification_time_value',
                                         default_value='modification_time'))

        self.mount_tool_file_entry_type = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'file_entry_type')

        self.mount_tool_file_entry_type_size_value = self._GetOptionalConfigValue(
            config_parser,
            'mount_tool',
            'file_entry_type_size_value',
            default_value='size')

        self.mount_tool_file_system_type = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'file_system_type')

        self.mount_tool_mounted_description = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'mounted_description')

        self.mount_tool_path_prefix = self._GetOptionalConfigValue(
            config_parser,
            'mount_tool',
            'path_prefix',
            default_value=self.library_name_suffix)

        self.mount_tool_source = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source')
        self.mount_tool_source_description = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_description')

        # If the long source description is not set it will default to
        # source description.
        self.mount_tool_source_description_long = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_description_long')

        self.mount_tool_source_type = self._GetOptionalConfigValue(
            config_parser, 'mount_tool', 'source_type')

        if self.mount_tool_source_type and self.mount_tool_source_type not in (
                'container', 'file', 'image', 'volume'):
            raise errors.ConfigurationError(
                'unsupported mount tool source type: {0:s}'.format(
                    self.mount_tool_source_type))