Ejemplo n.º 1
0
def _validate_key(key: bytes):
    assure_type(key, bytes)

    if not (0 < len(key) <= 255):
        raise InvalidKey('Max key length is 255 bytes')

    for character in key:
        if character not in _VALID_FILENAME_CHARACTERS:
            raise InvalidKey()
Ejemplo n.º 2
0
    def __post_init__(self):
        if self.Nodes:
            raise UnsupportedCase()

        assure_type(self.NodeNames, List[NodeName])
        assure_type(self.FailedNodes, Dict[NodeName, FailureMessage])
        assure_type(self.Error, str)
Ejemplo n.º 3
0
 def __post_init__(self):
     assure_type(self.name, str)
     assure_type(self.task_id, TaskId)
     assure_type(self.cgroup_path, str)
     assure_type(self.subcgroups_paths, List[str])
     assure_type(self.labels, Dict[str, str])
     assure_type(self.resources, Dict[str, Union[float, int, str]])
Ejemplo n.º 4
0
def _validate_value(value: bytes):
    assure_type(value, bytes)
Ejemplo n.º 5
0
Archivo: main.py Proyecto: Damenus/owca
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-c',
                        '--config',
                        help="Configuration",
                        default=None,
                        required=True)
    parser.add_argument(
        '-l',
        '--log-level',
        help='Log level for modules (by default for wca) in [module:]level form,'
        'where level can be one of: CRITICAL,ERROR,WARNING,INFO,DEBUG,TRACE'
        'Example -l debug -l example:debug. Defaults to wca:INFO.'
        'Can be overridden at runtime with config.yaml "loggers" section.',
        default=[],
        action='append',
        dest='levels',
    )
    parser.add_argument('-r',
                        '--register',
                        action='append',
                        dest='components',
                        help="Register additional components in config",
                        default=[])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version=platforms.get_wca_version(),
                        help="Show version")
    parser.add_argument('-0',
                        '--root',
                        help="Allow WCA process to be run using root account",
                        dest='is_root_allowed',
                        action='store_true')

    args = parser.parse_args()

    # Do not allow to run WCA with root privileges unless user indicates that it is intended.
    uid = os.geteuid()
    if uid == 0 and not args.is_root_allowed:
        log.fatal(
            "Do not run WCA with root privileges. Consult documentation "
            "to understand what capabilities are required. If root account "
            "has to be used then set --root/-0 argument to override.")
        exit(2)

    # Initialize logging subsystem from command line options.
    log_levels = logger.parse_loggers_from_list(args.levels)
    log_levels_copy_with_default = dict(**log_levels)
    log_levels_copy_with_default.setdefault(logger.DEFAULT_MODULE, 'info')
    logger.configure_loggers_from_dict(log_levels_copy_with_default)

    log.warning(
        'This software is pre-production and should not be deployed to production servers.'
    )
    log.debug('started PID=%r', os.getpid())
    log.info('Version wca: %s', platforms.get_wca_version())

    # Register internal & external components.
    components.register_components(extra_components=args.components)

    valid_config_file(args.config)

    # Initialize all necessary objects.
    try:
        configuration = config.load_config(args.config)
    except config.ConfigLoadError as e:
        log.error('Error: Cannot load config file! : %s', e)
        if log.getEffectiveLevel() <= logging.DEBUG:
            log.exception('Detailed exception:')
        exit(1)

    for key in configuration:
        if key != 'loggers' and key != 'runner':
            log.error('Error: Unknown fields in configuration '
                      'file! Possible are: \'loggers\', '
                      '\'runner\'')
            exit(1)

    assure_type(configuration, dict)
    assert 'runner' in configuration, 'Improper config - missing runner instance!'

    # Configure loggers using configuration file.
    if 'loggers' in configuration:
        log_levels_config = configuration['loggers']
        if not isinstance(log_levels, dict):
            log.error(
                'Loggers configuration error: log levels are mapping from logger name to'
                'log level!')
            exit(1)
        # Merge config from cmd line and config file.
        # Overwrite config file values with values provided from command line.
        log_levels = dict(log_levels_config, **log_levels)
        logger.configure_loggers_from_dict(log_levels)

    # Dump loggers configurations  to debug issues with loggers.
    if os.environ.get('WCA_DUMP_LOGGERS') == 'True':
        print(
            '------------------------------------ Logging tree ---------------------'
        )
        import logging_tree
        logging_tree.printout()
        print(
            '------------------------------------ Logging tree END------------------'
        )

    # Extract main loop component.
    runner = configuration['runner']
    assure_type(runner, Runner)

    # Prepare and run the "main loop".
    exit_code = runner.run()
    exit(exit_code)
Ejemplo n.º 6
0
def test_valid_assure_type(value, expected_type):
    assure_type(value, expected_type)
Ejemplo n.º 7
0
def test_assure_type_invalid_weak(value, expected_type,
                                  expected_exception_msg):
    with pytest.raises(WeakValidationError, match=expected_exception_msg):
        assure_type(value, expected_type)
Ejemplo n.º 8
0
def _validate_allocate_return_vals(
        tasks: TasksAllocations, anomalies: List[Anomaly], metrics: List[Metric]):
    assure_type(tasks, TasksAllocations)
    assure_type(anomalies, List[Anomaly])
    assure_type(metrics, List[Metric])
Ejemplo n.º 9
0
    def __post_init__(self):
        if self.Nodes:
            raise UnsupportedCase()

        assure_type(self.Pod, dict)
        assure_type(self.NodeNames, List[str])
Ejemplo n.º 10
0
 def __post_init__(self):
     assure_type(self.Host, str)
     assure_type(self.Score, int)
Ejemplo n.º 11
0
 def validate(self, anomalies: List[Anomaly]):
     assure_type(anomalies, List[Anomaly])
Ejemplo n.º 12
0
 def __post_init__(self):
     assure_type(self.name, str)
     assure_type(self.task_id, TaskId)
     assure_type(self.cgroup_path, str)
     assure_type(self.subcgroups_paths, List[str])
     assure_type(self.labels, Dict[str, str])
     assure_type(self.resources, TaskResources)
     assure_type(self.executor_pid, int)
     assure_type(self.container_id, str)
     assure_type(self.executor_id, str)
     assure_type(self.agent_id, str)