def test_exception(self):
        io = StringIO()
        with pytest.raises(SystemExit) as exc_info:
            backend.exception_occured(io)

        assert exc_info.value.code != 0
        assert io.getvalue() > ""
Exemple #2
0
def replog(ucr, var, old_value, value=None):
    """
	This function writes a new entry to replication logfile if
	this feature has been enabled.
	"""
    if ucr.is_true('ucr/replog/enabled', False):
        if value is not None:
            method = 'set'
            varvalue = "%s=%s" % (var, escape_value(value))
        else:
            method = 'unset'
            varvalue = "'%s'" % var

        scope_arg = {
            ConfigRegistry.LDAP: '--ldap-policy ',
            ConfigRegistry.FORCED: '--force ',
            ConfigRegistry.SCHEDULE: '--schedule ',
        }.get(ucr.scope, '')

        if old_value is None:
            old_value = "[Previously undefined]"

        log = '%s: %s %s%s old:%s\n' % (time.strftime("%Y-%m-%d %H:%M:%S"),
                                        method, scope_arg, varvalue, old_value)
        try:
            if not os.path.isfile(REPLOG_FILE):
                os.close(os.open(REPLOG_FILE, os.O_CREAT, 0o640))
            logfile = open(REPLOG_FILE, "a+")
            logfile.write(log)
            logfile.close()
        except EnvironmentError as ex:
            print >> sys.stderr, ("E: exception occurred while writing to " +
                                  "replication log: %s" % (ex, ))
            exception_occured()
Exemple #3
0
def replog(method, scope, ucr, var, old_value, value=None):
	"""
	This function writes a new entry to replication logfile if
	this feature has been enabled.
	"""
	if ucr.is_true('ucr/replog/enabled', False):
		if method == 'set':
			varvalue = "%s=%s" % (var, escape_value(value))
		else:
			varvalue = "'%s'" % var

		scope_arg = ''
		if scope == ConfigRegistry.LDAP:
			scope_arg = '--ldap-policy '
		elif scope == ConfigRegistry.FORCED:
			scope_arg = '--force '
		elif scope == ConfigRegistry.SCHEDULE:
			scope_arg = '--schedule '

		if old_value is None:
			old_value = "[Previously undefined]"

		log = '%s: %s %s%s old:%s\n' % (time.strftime("%Y-%m-%d %H:%M:%S"),
				method, scope_arg, varvalue, old_value)
		try:
			if not os.path.isfile(REPLOG_FILE):
				os.close(os.open(REPLOG_FILE, os.O_CREAT, 0640))
			logfile = open(REPLOG_FILE, "a+")
			logfile.write(log)
			logfile.close()
		except EnvironmentError, ex:
			print >> sys.stderr, ("E: exception occurred while writing to " +
				"replication log: %s" % (ex,))
			exception_occured()
def replog(ucr, var, old_value, value=None):
    # type: (ConfigRegistry, str, Optional[str], Optional[str]) -> None
    """
	This function writes a new entry to replication logfile if
	this feature has been enabled.

	:param ucr: UCR instance.
	:param var: UCR variable name.
	:param old_value: Old UCR variable value.
	:param value: New UCR variable value. `None` is now unset.
	"""
    if ucr.is_true('ucr/replog/enabled', False):
        if value is not None:
            method = 'set'
            varvalue = "%s=%s" % (var, escape_value(value))
        else:
            method = 'unset'
            varvalue = "'%s'" % var

        scope_arg = {
            ConfigRegistry.LDAP: '--ldap-policy ',
            ConfigRegistry.FORCED: '--force ',
            ConfigRegistry.SCHEDULE: '--schedule ',
        }.get(ucr.scope, '')

        if old_value is None:
            old_value = "[Previously undefined]"

        log = u'%s: %s %s%s old:%s\n' % (time.strftime("%Y-%m-%d %H:%M:%S"),
                                         method, scope_arg, varvalue,
                                         old_value)
        try:
            if not os.path.isfile(REPLOG_FILE):
                os.close(os.open(REPLOG_FILE, os.O_CREAT, 0o640))

            with open(REPLOG_FILE, "a+", encoding='utf-8') as logfile:
                logfile.write(log)
        except EnvironmentError as ex:
            print(
                "E: exception occurred while writing to replication log: %s" %
                (ex, ),
                file=sys.stderr)
            exception_occured()
Exemple #5
0
def main(args):
	# type: (List[str]) -> None
	"""Run config registry."""
	try:
		# close your eyes ...
		if not args:
			args.append('--help')
		# search for options in command line arguments
		while args and args[0].startswith('-'):
			arg = args.pop(0)
			# is action option?
			for key, opt in OPT_ACTIONS.items():
				if arg[2:] == key or arg in opt[2]:
					opt[1] = True
					break
			else:
				# not an action option; is a filter option?
				try:
					OPT_FILTERS[arg[2:]][2] = True
				except LookupError:
					print('E: unknown option %s' % (arg,), file=sys.stderr)
					sys.exit(1)

		# is action already defined by global option?
		for name, (func, state, _aliases) in OPT_ACTIONS.items():
			if state:
				func(args)

		# find action
		try:
			action = args.pop(0)
		except IndexError:
			print('E: missing action, see --help', file=sys.stderr)
			sys.exit(1)
		# COMPAT: the 'shell' command is now an option and equivalent to
		# --shell search
		if action == 'shell':
			action = 'search'
			# activate shell option
			OPT_FILTERS['shell'][2] = True
			# switch to old, brief output
			OPT_COMMANDS['search']['brief'][1] = True

			tmp = []
			if not args:
				tmp.append('')
			else:
				for arg in args:
					if not arg.startswith('--'):
						tmp.append('^%s$' % arg)
					else:
						tmp.append(arg)
			args = tmp

		# set 'sort' option by default for dump and search
		if action in ['dump', 'search', 'info']:
			OPT_FILTERS['sort'][2] = True

		# set brief option when generating shell output
		if OPT_FILTERS['shell'][2]:
			OPT_COMMANDS['search']['brief'][1] = True

		# if a filter option is set: verify that a valid command is given
		for name, (_prio, func, state, actions) in OPT_FILTERS.items():
			if state:
				if action not in actions:
					print('E: invalid option --%s for command %s' % (name, action), file=sys.stderr)
					sys.exit(1)

		# check command options
		cmd_opts = OPT_COMMANDS.get(action, {})
		while args and args[0].startswith('--'):
			arg = args.pop(0)
			if action in ('set', 'unset') and arg == '--forced':
				arg = '--force'
			try:
				cmd_opt_tuple = cmd_opts[arg[2:]]
			except LookupError:
				print('E: invalid option %s for command %s' % (arg, action), file=sys.stderr)
				sys.exit(1)
			else:
				if cmd_opt_tuple[0] == BOOL:
					cmd_opt_tuple[1] = True
				else:  # STRING
					try:
						cmd_opt_tuple[1] = args.pop(0)
					except IndexError:
						msg = 'E: option %s for command %s expects an argument'
						print(msg % (arg, action), file=sys.stderr)
						sys.exit(1)

		# Drop type
		cmd_opts = dict(((key, value) for key, (typ, value) in cmd_opts.items()))

		# action!
		try:
			handler_func, min_args = HANDLERS[action]
		except LookupError:
			print('E: unknown action "%s", see --help' % (action,), file=sys.stderr)
			sys.exit(1)
		else:
			# enough arguments?
			if len(args) < min_args:
				missing_parameter(action)

			# if any filter option is set
			result = handler_func(args, cmd_opts)
			if result is None:
				return

			results = result
			# let the filter options do their job
			for (_prio, filter_func, state, _actions) in sorted(OPT_FILTERS.values()):
				if not state:
					continue
				results = filter_func(args, results)

			for line in results:
				print(line)

	except (EnvironmentError, TypeError):
		if OPT_ACTIONS['debug'][1]:
			raise
		exception_occured()
Exemple #6
0
def main(args):
	"""Run config registry."""
	try:
		# close your eyes ...
		if not args:
			args.append('--help')
		# search for options in command line arguments
		while args and args[0].startswith('-'):
			arg = args.pop(0)
			# is action option?
			for key, opt in OPT_ACTIONS.items():
				if arg[2:] == key or arg in opt[2]:
					opt[1] = True
					break
			else:
				# not an action option; is a filter option?
				try:
					OPT_FILTERS[arg[2:]][2] = True
				except LookupError:
					print >> sys.stderr, 'E: unknown option %s' % (arg,)
					sys.exit(1)

		# is action already defined by global option?
		for name, (func, state, _aliases) in OPT_ACTIONS.items():
			if state:
				func(args)

		# find action
		try:
			action = args.pop(0)
		except IndexError:
			print >> sys.stderr, 'E: missing action, see --help'
			sys.exit(1)
		# COMPAT: the 'shell' command is now an option and equivalent to
		# --shell search
		if action == 'shell':
			action = 'search'
			# activate shell option
			OPT_FILTERS['shell'][2] = True
			# switch to old, brief output
			OPT_COMMANDS['search']['brief'][1] = True

			tmp = []
			if not args:
				tmp.append('')
			else:
				for arg in args:
					if not arg.startswith('--'):
						tmp.append('^%s$' % arg)
					else:
						tmp.append(arg)
			args = tmp

		# set 'sort' option by default for dump and search
		if action in ['dump', 'search', 'info']:
			OPT_FILTERS['sort'][2] = True

		# set brief option when generating shell output
		if OPT_FILTERS['shell'][2]:
			OPT_COMMANDS['search']['brief'][1] = True

		# if a filter option is set: verify that a valid command is given
		post_filter = False
		for name, (_prio, func, state, actions) in OPT_FILTERS.items():
			if state:
				if not action in actions:
					print >> sys.stderr, \
							'E: invalid option --%s for command %s' % \
							(name, action)
					sys.exit(1)
				else:
					post_filter = True

		# check command options
		cmd_opts = OPT_COMMANDS.get(action, {})
		while args and args[0].startswith('--'):
			arg = args.pop(0)
			if action in ('set', 'unset') and arg == '--forced':
				arg = '--force'
			try:
				cmd_opt_tuple = cmd_opts[arg[2:]]
			except LookupError:
				print >> sys.stderr, \
					'E: invalid option %s for command %s' % (arg, action)
				sys.exit(1)
			else:
				if cmd_opt_tuple[0] == BOOL:
					cmd_opt_tuple[1] = True
				else:  # STRING
					try:
						cmd_opt_tuple[1] = args.pop(0)
					except IndexError:
						msg = 'E: option %s for command %s expects an argument'
						print >> sys.stderr, msg % (arg, action)
						sys.exit(1)

		# Drop type
		cmd_opts = dict(((key, value) for key, (typ, value) in
			cmd_opts.items()))

		# action!
		try:
			handler_func, min_args = HANDLERS[action]
		except LookupError:
			print >> sys.stderr, 'E: unknown action "%s", see --help' % (action,)
			sys.exit(1)
		else:
			# enough arguments?
			if len(args) < min_args:
				missing_parameter(action)
			# if any filter option is set
			if post_filter:
				old_stdout = sys.stdout
				sys.stdout = capture = Output()
			handler_func(args, cmd_opts)
			# let the filter options do their job
			if post_filter:
				sys.stdout = old_stdout
				text = capture.text
				for _prio, (name, filter_func, state, actions) in \
						sorted(OPT_FILTERS.items(), key=lambda (k, v): v[0]):
					if state:
						text = filter_func(args, text)
				for line in text:
					print line

	except (EnvironmentError, TypeError):
		if OPT_ACTIONS['debug'][1]:
			raise
		exception_occured()