示例#1
0
def elektraMount(mountpoint, filename, resolver, plugins, recommends):
    with kdb.KDB() as db:
        ks = kdb.KeySet(0)
        mountpoints = "system/elektra/mountpoints"
        rc = 0
        try:
            rc = db.get(ks, mountpoints)
        except kdb.KDBException as e:
            raise ElektraReadException("KDB.get failed: {}".format(e))
        if rc == -1:
            raise ElektraMountException(
                "Failed to fetch elektra facts: failed to read system/elektra/mountpoints."
            )
        searchKey = mountpoints + '/' + mountpoint.replace('/', '\/')
        try:
            key = ks[searchKey]
            return (0, True)
        except KeyError:
            command = []
            command.append("kdb")
            command.append("mount")
            if recommends:
                command.append("--with-recommends")
            command.append("-R")
            command.append(resolver)
            command.append(filename)
            command.append(mountpoint)
            for item in plugins:
                for cname, cvalue in item.items():
                    command.append(str(cname))  # plugin
                    if isinstance(cvalue, dict):  # iterate plugin meta
                        for scname, scvalue in cvalue.items():
                            command.append(str(scname) + "=" + str(scvalue))
            return execute(command)
示例#2
0
 def set_key(self, key):
     if not key.HasField('name'):
         return False
     name = str(key.name)
     value = None
     if key.type == PARAM_STRING:
         if not key.HasField('paramstring'):
             return False
         value = str(key.paramstring)
     elif key.type == PARAM_BINARY:
         if not key.HasField('parambinary'):
             return False
         value = str(key.parambinary)
     elif key.type == PARAM_INTEGER:
         if not key.HasField('paramint'):
             return False
         value = str(key.paramint)
     elif key.type == PARAM_DOUBLE:
         if not key.HasField('paramdouble'):
             return False
         value = str(key.paramdouble)
     elif key.type == PARAM_DOUBLE:
         if not key.HasField('paramlist'):
             return False
         return False  # TODO: implement
     for s in self.subscriptions:
         if name.startswith(s):
             with kdb.KDB() as db:
                 ks = kdb.KeySet()
                 db.get(ks, s)
                 ks[name].string = value
                 db.set(ks, s)
             return True
     return False
示例#3
0
 def tearDownClass(cls):
     # cleanup
     with kdb.KDB() as db:
         ks = kdb.KeySet(100)
         db.get(ks, TEST_NS)
         ks.cut(kdb.Key(TEST_NS))
         db.set(ks, TEST_NS)
def complete_long_options():
	global start_of_current_input, mount_point, last_command
	completion_options = []
	k = kdb.KDB()
	ks = kdb.KeySet()
	k.get(ks, mount_point)
	word = start_of_current_input.strip()
	while word.startswith('-'):
		word = word[1:]
	for key in ks:
		if last_command and last_command != str(key):
			continue
		long_opt = key.getMeta(name='opt/long')
		opt = key.getMeta(name='opt')
		if long_opt:
			if long_opt.value.startswith(word):
				completion_options.append('--' + long_opt.value)
		elif opt and opt.value.startswith('#'):
			try:
				len_opts = int((opt.value)[1:])
			except ValueError:
				continue
			for i in range(len_opts+1):
				long_opt = None
				long_opt = key.getMeta(name='opt/#{}/long'.format(i))
				if long_opt and long_opt.value.startswith(word):
					completion_options.append('--' + long_opt.value)
	k.close()
	return completion_options
示例#5
0
    def test_get(self):
        with kdb.KDB() as db:
            ks = kdb.KeySet()
            db.get(ks, "system/elektra")

            key = ks["system/elektra/version/constants/KDB_VERSION"]
            self.assertEqual(key.value, kdb.VERSION)
示例#6
0
 def full_update(self, basekey):
     with kdb.KDB() as db:
         ks = kdb.KeySet()
         db.get(ks, basekey)
         for k in ks:
             key = self.tx.key.add()
             self.convert_key(key, k)
     self.add_pparams()
     self.send_param_msg(basekey, MT_PARAM_FULL_UPDATE)
示例#7
0
    def test_get(self):
        with kdb.KDB() as db:
            ks = kdb.KeySet()
            db.get(ks, "system/elektra")

            import os
            if os.getenv("CHECK_VERSION") is None:
                key = ks["system/elektra/version/constants/KDB_VERSION"]
                self.assertEqual(key.value, kdb.VERSION)
示例#8
0
    def test_set(self):
        with kdb.KDB() as db:
            ks = kdb.KeySet(100)
            db.get(ks, TEST_NS)

            try:
                key = ks[TEST_NS + "/mykey"]
            except KeyError:
                key = kdb.Key(TEST_NS + "/mykey")
                ks.append(key)
            key.value = "new_value"

            db.set(ks, TEST_NS)

        with kdb.KDB() as db:
            ks = kdb.KeySet(100)
            db.get(ks, TEST_NS)
            self.assertEqual(ks[TEST_NS + "/mykey"].value, "new_value")
示例#9
0
 def test_ensure(self):
     with kdb.KDB() as db:
         ks = kdb.KeySet()
         k = kdb.Key("system:/elektra/ensure/plugins/global/gopts",
                     kdb.KEY_VALUE, "mounted")
         parent = kdb.Key("system:/elektra")
         rc = db.ensure(ks, parent)
         self.assertEqual(rc, 0)
         db.get(ks, parent)
示例#10
0
def setupSpec():
    with kdb.KDB() as db:
        ks = kdb.KeySet(10)
        db.get(ks, spec_base_key)
        if len(ks.cut(kdb.Key(spec_base_key))) > 0:
            print("ERROR: Couldn't setup spec, keys exist!", file=sys.stderr)
            exit(1)

        ks.extend(spec)
        db.set(ks, spec_base_key)
示例#11
0
 def incremental_update(self, key, basekey='', delete=False):
     if not delete:
         with kdb.KDB() as db:
             ks = kdb.KeySet()
             db.get(ks, basekey)
             k = ks[key]
             paramKey = self.tx.key.add()
             self.convert_key(paramKey, k)
     else:
         paramKey = self.tx.key.add()
         paramKey.name = key
         paramKey.deleted = True
     self.send_param_msg(basekey, MT_PARAM_INCREMENTAL_UPDATE)
示例#12
0
def elektraSet(mountpoint, keyset, keeporder):
    with kdb.KDB() as db:
        ks = kdb.KeySet(0)
        rc = 0
        try:
            rc = db.get(ks, mountpoint)
        except kdb.KDBException as e:
            raise ElektraReadException("KDB.get failed: {}".format(e))
        if rc == -1:
            raise ElektraReadException(
                "Failed to read keyset below {}".format(mountpoint))
        flattenedKeyset = flatten_json(keyset)
        i = 0
        for name, value in flattenedKeyset.items():
            key = None
            kname = None
            try:
                key = ks[mountpoint + "/" + name]
                if keeporder and key.hasMeta("order"):
                    i = int((key.getMeta("order").value)) + 1
                if keeporder:
                    key.setMeta("order", str(i))
                    i += 1
            except KeyError:
                key = kdb.Key(mountpoint + "/" + name)
                if keeporder:
                    key.setMeta("order", str(i))
                    i += 1
                ks.append(key)
            if isinstance(value, dict):
                for sname, svalue in value.items():
                    if sname == 'value':
                        key.value = svalue
                    elif sname == 'meta':
                        for mname, mvalue in svalue.items():
                            key.setMeta(mname, str(mvalue))
            else:
                key.value = value
        try:
            rc = db.set(ks, mountpoint)
        except kdb.KDBException as e:
            raise ElektraWriteException("KDB.set failed: {}".format(e))
        if rc == -1:
            raise ElektraWriteException(
                "Failed to write keyset to {}".format(mountpoint))
        return rc
def complete_commands(start_of_input):
	global mount_point, root
	with kdb.KDB() as k:
		ks = kdb.KeySet()
		k.get(ks, mount_point)
		len_path_mount_point = len(mount_point.split('/'))
		completion_commands = []
		for key in ks:
			path = str(key).split('/')
			if len(path) <= len_path_mount_point:
				continue
			if start_of_input is None:
				completion_commands.append(path[-1])
			elif path[-1].startswith(start_of_input):
				completion_commands.append(path[-1])
		k.close()
		return completion_commands
def complete_program_args():
	# TODO only add as many arguments as needed
	global start_of_current_input, mount_point
	completion_arguments = []
	word = start_of_current_input.strip()
	while word.startswith('-'):
		word = word[1:]
	k = kdb.KDB()
	ks = kdb.KeySet()
	k.get(ks, mount_point)
	for key in ks:
		args = key.getMeta(name='args')
		if not args:
			continue
		if args.value == 'remaining':
			shell_command = key.getMeta(name='completion/shell')
			if shell_command:
				completion_arguments.extend(execute_shell_command(shell_command.value))
	k.close()
	return completion_arguments
def complete_opt_args():
	# TODO only add as many arguments as needed
	global start_of_current_input, mount_point, last_option, last_option_meta
	completion_arguments = []
	word = start_of_current_input.strip()
	while word.startswith('-'):
		word = word[1:]
	k = kdb.KDB()
	ks = kdb.KeySet()
	if last_option is None or last_option_meta is None:
		return completion_options
	k.get(ks, mount_point)
	for key in ks:
		if str(key) != last_option:
			continue
		opt_arg = key.getMeta(name=last_option_meta)
		opt_arg_complete = key.getMeta(name=last_option_meta + '/completion/shell')
		if opt_arg and opt_arg.value != 'none' and opt_arg_complete:
			 completion_arguments.extend(execute_shell_command(opt_arg_complete.value))
	k.close()
	return completion_arguments
示例#16
0
def _get_kdb_instance():
    config = kdb.KeySet(0)
    contract = kdb.KeySet(0)
    custom_envp = [ "%s=%s" % (k, v) for (k, v) in os.environ.items() ]
    kdb.goptsContract (contract, sys.argv, custom_envp, parent_key, config)
    db = kdb.KDB(contract)

    #monkey patch db.get as
        #- proc:/ keys are only available through a cascading lookup (See manpage elektra-namespaces: "Keys in the namespace proc ... are ignored by kdbGet ... ")
        #- we don't want spec: keys to appear in the cascading namespace 
    orig_get = db.get
    def patched_get(ks, orig_root):
        justified_root = re.sub("^proc:/", "/", str(orig_root))
        status = orig_get(ks, justified_root)
        if kdb.Key(orig_root).isCascading():
            for key_to_remove in ks.filter(lambda key: key.isSpec()):
                ks.remove(key_to_remove)
        return status

    db.get = patched_get
    return db
示例#17
0
def elektraUmount(mountpoint):
    with kdb.KDB() as db:
        ks = kdb.KeySet(0)
        mountpoints = "system/elektra/mountpoints"
        rc = 0
        try:
            rc = db.get(ks, mountpoints)
        except kdb.KDBException as e:
            raise ElektraReadException("KDB.get failed: {}".format(e))
        if rc != 1:
            raise ElektraUmountException(
                "Failed to fetch elektra facts: failed to read system/elektra/mountpoints."
            )
        key = kdb.Key()
        key.name = mountpoints + '/' + mountpoint.replace('/', '\/')
        ks.cut(key)
        try:
            rc = db.set(ks, mountpoints)
        except kdb.KDBException as e:
            raise ElektraWriteException("KDB.set failed: {}".format(e))
        if rc != 1:
            raise ElektraUmountException("Failed to umount " + key.name)
示例#18
0
def main():
    module = AnsibleModule(argument_spec=dict(mountpoint=dict(
        default='system'), ))
    mountpoint = module.params.get('mountpoint')
    json_output = {}
    with kdb.KDB() as db:
        ks = kdb.KeySet(0)
        rc = db.get(ks, mountpoint)
        if rc != 1:
            module.fail_json(msg="No configuration mounted under %s" %
                             mountpoint)
        for k in ks:
            kname = str(k)[len(mountpoint) + 1:]
            miter = k.getMeta()
            if miter != None:
                json_output[kname] = {}
                json_output[kname]['value'] = k.value
                for m in miter:
                    json_output[kname][str(m)] = m.value
            else:
                json_output[kname] = k.value

    module.exit_json(**json_output)
示例#19
0
    def test_gopts(self):
        try:
            setupSpec()

            custom_argv = ["test", "get", "-v", "user:/"]
            custom_envp = []

            config = kdb.KeySet(0)
            contract = kdb.KeySet(0)
            kdb.goptsContract(contract, custom_argv, custom_envp,
                              kdb.Key(base_key), config)

            with kdb.KDB(contract) as db:
                ks = kdb.KeySet(0)
                db.get(ks, base_key)

                self.assertTrue((base_key in ks))
                self.assertEqual(ks[base_key].value, "getter")
                self.assertEqual(ks[base_key + "/getter/keyname"].value,
                                 "user:/")
                self.assertTrue((base_key + "/getter/verbose" in ks))
                self.assertEqual(ks[base_key + "/getter/verbose"].value, "1")
        finally:
            removeSpec()
示例#20
0
        ks.cut(kdb.Key(spec_base_key))
        db.set(ks, spec_base_key)


def array_index(index):
    return "_" * (len(str(index)) - 1) + str(index)


setupSpec()

contract = kdb.KeySet(0)
config = kdb.KeySet(0)

kdb.goptsContract(contract, sys.argv, os.environ, base_key, config)

with kdb.KDB(contract) as db:
    ks = kdb.KeySet(0)
    db.get(ks, spec_base_key)

    if "proc:/elektra/gopts/help" in ks and ks[
            "proc:/elektra/gopts/help"].value == "1":
        print(ks["proc:/elektra/gopts/help/message"].value)
        removeSpec()
        exit(0)

    print("A real implementation would now")

    if base_key + "/printversion" in ks and ks[base_key +
                                               "/printversion"].value == "1":
        print("print version information\n")
        removeSpec()
def get_command_line_arguments():
	global mount_point, root, typed, start_of_current_input, last_command, last_option, last_option_meta, command_or_option, opt_arg
	wipe()
	try:
		opts, args = getopt.getopt(sys.argv[1:],'s:m:')
	except getopt.GetoptError:
		print('getting command line options failed')
		sys.exit(2)
	for opt, arg in opts:
		if opt == '-s':
			s = arg.strip()
			if s:
				start_of_current_input = s
		if opt == '-m':
			m = arg.strip()
			if m:
				mount_point = m
				root = mount_point.split('/')[-1]
	if mount_point is None:
		print('no mount point, pass mount point with -m')
		sys.exit(2)
	k = kdb.KDB()
	ks = kdb.KeySet()
	k.get(ks, mount_point) 
	for i in ks:
		if str(i) == mount_point:
			get_complete = i.getMeta(name='complete')
			if get_complete and get_complete.value == 'command':
				command_or_option = True
	if len(args) > 0:
		typed = args[0].split()
		if command_or_option:
			for i in reversed(typed):
				for j in ks:
					if str(j).split('/')[-1] == i:
						last_command = str(j)
						break
					if last_command is not None:
						break
		for i in reversed(typed):
			if not i.startswith('-'):
				continue
			word = i.strip()
			while word.startswith('-'):
				word = word[1:]
			for j in ks:
				opt = j.getMeta(name='opt')
				long_opt = j.getMeta(name='opt/long')
				if long_opt and long_opt.value == word:
					last_option = str(j)
					last_option_meta = 'opt/long'
				elif opt and not opt.value.startswith('#'):
					if opt and opt.value == word:
						last_option = str(j)
						last_option_meta = 'opt'
				elif opt and opt.value.startswith('#'):
					try:
						len_opts = int((opt.value)[1:])
					except ValueError:
						continue
					for l in range(len_opts+1):
						opt_loop = None
						opt_loop = j.getMeta(name='opt/#{}'.format(l))
						long_opt_loop = None
						long_opt_loop = j.getMeta(name='opt/#{}/long'.format(l))
						if opt_loop and opt_loop.value == word:
							last_option = str(j)
							last_option_meta = 'opt/#{}'.format(l)
						if long_opt_loop and long_opt_loop.value == word:
							last_option = str(j)
							last_option_meta = 'opt/#{}/long'.format(l)
				if last_option is not None and last_option_meta is not None:
					opt_arg_meta = j.getMeta(name=last_option_meta+'/arg')
					if opt_arg_meta:
						opt_arg = opt_arg_meta.value
					break

	k.close()
	if root is None:
		print('getting root failed')
		sys.exit(2)
示例#22
0
 def test_ctor(self):
     self.assertIsInstance(kdb.KDB(), kdb.KDB)
     error = kdb.Key()
     self.assertIsInstance(kdb.KDB(error), kdb.KDB)
示例#23
0
import kdb

# open database
with kdb.KDB() as db:
	ks = kdb.KeySet(100)
	# get keys
	db.get(ks, "user:/MyApp")

	# check if key exists
	try:
		key = ks["user:/MyApp/mykey"]
	except KeyError:
		# create a new key + append to keyset
		key = kdb.Key("user:/MyApp/mykey")
		ks.append(key)

	# change keys value
	key.value = "new_value"

	# store new keyset
	db.set(ks, "user:/MyApp")

# database close is implicit
示例#24
0
def removeSpec():
    with kdb.KDB() as db:
        ks = kdb.KeySet(10)
        db.get(ks, spec_base_key)
        ks.cut(kdb.Key(spec_base_key))
        db.set(ks, spec_base_key)
示例#25
0
def _get_kdb_instance():
    config = kdb.KeySet(0)
    contract = kdb.KeySet(0)
    custom_envp = ["%s=%s" % (k, v) for (k, v) in os.environ.items()]
    kdb.goptsContract(contract, sys.argv, custom_envp, kdb.Key(), config)
    return kdb.KDB(contract)