def test_create_audit_entry(monkeypatch): monkeypatch.setenv('LEAPP_CURRENT_ACTOR', _ACTOR_NAME) monkeypatch.setenv('LEAPP_CURRENT_PHASE', _PHASE_NAME) monkeypatch.setenv('LEAPP_EXECUTION_ID', _CONTEXT_NAME) monkeypatch.setenv('LEAPP_HOSTNAME', _HOSTNAME) _id = str(uuid.uuid4()) event = 'process-start' create_audit_entry(event, {'id': _id, 'parameters': 'ls'}) assert get_audit_entry(event, _CONTEXT_NAME)
def get(self, scope, fallback=None): """ Dict compatible interface to get a sub dictionary by dialog scope. :param scope: Scope of the data to retrieve. :param fallback: Fallback value to return if not found. :return: A shallow copy of data stored in _storage by scope key """ # NOTE(ivasilev) self.storage.get() will return a DictProxy. To avoid TypeError during later # JSON serialization a copy() should be invoked to get a shallow copy of data answer = self._storage.get(scope, fallback).copy() create_audit_entry('dialog-answer', {'scope': scope, 'fallback': fallback, 'answer': answer}) return answer
def get(self, scope, fallback=None): """ Dict compatible interface to get a sub dictionary by dialog scope. :param scope: Scope of the data to retrieve. :param fallback: Fallback value to return if not found. :return: """ answer = self._storage.get(scope, fallback) create_audit_entry('dialog-answer', { 'scope': scope, 'fallback': fallback, 'answer': answer }) return answer
def _do_run(stdin, logger, messaging, definition, config_model, skip_dialogs, args, kwargs): if stdin is not None: try: sys.stdin = os.fdopen(stdin) except OSError: pass with warnings.catch_warnings(record=True) as recording: warnings.simplefilter(action="always", category=_LeappDeprecationWarning) definition.load() with definition.injected_context(): target_actor = [ actor for actor in get_actors() if actor.name == definition.name ][0] actor_instance = target_actor(logger=logger, messaging=messaging, config_model=config_model, skip_dialogs=skip_dialogs) actor_instance.run(*args, **kwargs) try: # By this time this is no longer set, so we have to get it back os.environ['LEAPP_CURRENT_ACTOR'] = actor_instance.name for rec in recording: if issubclass(rec.category, _LeappDeprecationWarning): entry = { 'message': str(rec.message), 'filename': rec.filename, 'line': linecache.getline(rec.filename, rec.lineno) if rec.line is None else rec.line, 'lineno': rec.lineno, 'since': rec.category.since, 'reason': rec.category.msg } create_audit_entry('deprecation', entry) finally: # Remove it again os.environ.pop('LEAPP_CURRENT_ACTOR')
def run(args, split=False): """ Run a command and return its result as a dict. The execution of the program and it's results are captured by the audit. :param args: Command to execute :type args: list or tuple :param split: Split the output on newlines :type split: bool :return: {'stdout' : stdout, 'stderr': stderr, 'signal': signal, 'exit_code': exit_code, 'pid': pid} :rtype: dict """ _id = str(uuid.uuid4()) result = None try: create_audit_entry('process-start', {'id': _id, 'parameters': args}) result = _call(args, callback_raw=_logging_handler) if result['exit_code'] != 0: raise CalledProcessError( message="A Leapp Command Error occurred. ", command=args, result=result) else: if split: result.update({'stdout': result['stdout'].splitlines()}) finally: create_audit_entry('process-end', _id) create_audit_entry('process-result', { 'id': _id, 'parameters': args, 'result': result }) return result
def run(args, split=False, callback_raw=_console_logging_handler, callback_linebuffered=_logfile_logging_handler, env=None, checked=True): """ Run a command and return its result as a dict. The execution of the program and it's results are captured by the audit. :param args: Command to execute :type args: list or tuple :param split: Split the output on newlines :type split: bool :param callback_raw: Optional custom callback executed on raw data to print in console :type callback_raw: (fd: int, buffer: bytes) -> None :param env: Environment variables to use for execution of the command :type env: dict :param checked: Raise an exception on a non-zero exit code, default True :type checked: bool :return: {'stdout' : stdout, 'stderr': stderr, 'signal': signal, 'exit_code': exit_code, 'pid': pid} :rtype: dict """ api.current_logger().debug('External command is started: [%s]', ' '.join(args)) _id = str(uuid.uuid4()) result = None try: create_audit_entry('process-start', { 'id': _id, 'parameters': args, 'env': env }) result = _call(args, callback_raw=callback_raw, callback_linebuffered=callback_linebuffered, env=env) if checked and result['exit_code'] != 0: raise CalledProcessError( message="A Leapp Command Error occurred. ", command=args, result=result) if split: result.update({'stdout': result['stdout'].splitlines()}) finally: create_audit_entry('process-end', _id) create_audit_entry('process-result', { 'id': _id, 'parameters': args, 'result': result, 'env': env }) api.current_logger().debug('External command is finished: [%s]', ' '.join(args)) return result
def run(args, split=False, callback_raw=_console_logging_handler, callback_linebuffered=_logfile_logging_handler, env=None, checked=True, stdin=None): """ Run a command and return its result as a dict. The execution of the program and it's results are captured by the audit. :param args: Command to execute :type args: list or tuple :param split: Split the output on newlines :type split: bool :param callback_raw: Optional custom callback executed on raw data to print in console :type callback_raw: (fd: int, buffer: bytes) -> None :param env: Environment variables to use for execution of the command :type env: dict :param checked: Raise an exception on a non-zero exit code, default True :type checked: bool :param stdin: String or a file descriptor that will be written to stdin of the child process :type stdin: int, str :return: {'stdout' : stdout, 'stderr': stderr, 'signal': signal, 'exit_code': exit_code, 'pid': pid} :rtype: dict """ if not args: message = 'Command to call is missing.' api.current_logger().error(message) raise ValueError(message) api.current_logger().debug('External command has started: {0}'.format( str(args))) _id = str(uuid.uuid4()) result = None try: create_audit_entry('process-start', { 'id': _id, 'parameters': args, 'env': env }) result = _call(args, callback_raw=callback_raw, callback_linebuffered=callback_linebuffered, stdin=stdin, env=env) if checked and result['exit_code'] != 0: message = 'Command {0} failed with exit code {1}.'.format( str(args), result.get('exit_code')) api.current_logger().debug(message) raise CalledProcessError(message=message, command=args, result=result) if split: result.update({'stdout': result['stdout'].splitlines()}) finally: create_audit_entry('process-result', { 'id': _id, 'parameters': args, 'result': result, 'env': env }) api.current_logger().debug('External command has finished: {0}'.format( str(args))) return result