Debian Codegraph @

ansible_collections/community/general/plugins/lookup/lmdb_kv.py

raw
1 # Copyright (c) 2017-2018, Jan-Piet Mens <jpmens(at)gmail.com>
2 # Copyright (c) 2018 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: lmdb_kv
9 author:
10 - Jan-Piet Mens (@jpmens)
11 version_added: '0.2.0'
12 short_description: Fetch data from LMDB
13 description:
14 - This lookup returns a list of results from an LMDB DB corresponding to a list of items given to it.
15 requirements:
16 - lmdb (Python library U(https://lmdb.readthedocs.io/en/latest/))
17 options:
18 _terms:
19 description: List of keys to query.
20 type: list
21 elements: str
22 db:
23 description: Path to LMDB database.
24 type: str
25 default: 'ansible.mdb'
26 vars:
27 - name: lmdb_kv_db
28 """
29
30 EXAMPLES = r"""
31 - name: query LMDB for a list of country codes
32 ansible.builtin.debug:
33 msg: "{{ query('community.general.lmdb_kv', 'nl', 'be', 'lu', db='jp.mdb') }}"
34
35 - name: use list of values in a loop by key wildcard
36 ansible.builtin.debug:
37 msg: "Hello from {{ item.0 }} a.k.a. {{ item.1 }}"
38 vars:
39 lmdb_kv_db: jp.mdb
40 with_community.general.lmdb_kv:
41 - "n*"
42
43 - name: get an item by key
44 ansible.builtin.assert:
45 that:
46 - item == 'Belgium'
47 vars:
48 lmdb_kv_db: jp.mdb
49 with_community.general.lmdb_kv:
50 - be
51 """
52
53 RETURN = r"""
54 _raw:
55 description: Value(s) stored in LMDB.
56 type: list
57 elements: raw
58 """
59
60
61 from ansible.errors import AnsibleError
62 from ansible.module_utils.common.text.converters import to_native, to_text
63 from ansible.plugins.lookup import LookupBase
64
65 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
66
67 HAVE_LMDB = True
68 try:
69 import lmdb
70 except ImportError:
71 HAVE_LMDB = False
72
73
74 class LookupModule(LookupBase):
75 def run(self, terms, variables=None, **kwargs):
76 """
77 terms contain any number of keys to be retrieved.
78 If terms is None, all keys from the database are returned
79 with their values, and if term ends in an asterisk, we
80 start searching there
81
82 The LMDB database defaults to 'ansible.mdb' if Ansible's
83 variable 'lmdb_kv_db' is not set:
84
85 vars:
86 lmdb_kv_db: "jp.mdb"
87 """
88 if HAVE_LMDB is False:
89 raise AnsibleError("Can't LOOKUP(lmdb_kv): this module requires lmdb to be installed")
90
91 self.set_options(var_options=variables, direct=kwargs)
92 check_for_wrong_terms(self, direct=kwargs)
93
94 db = self.get_option("db")
95
96 try:
97 env = lmdb.open(str(db), readonly=True)
98 except Exception as e:
99 raise AnsibleError(f"LMDB cannot open database {db}: {e}") from e
100
101 ret = []
102 if len(terms) == 0:
103 with env.begin() as txn:
104 cursor = txn.cursor()
105 cursor.first()
106 for key, value in cursor:
107 ret.append((to_text(key), to_native(value)))
108
109 else:
110 for term in terms:
111 with env.begin() as txn:
112 if term.endswith("*"):
113 cursor = txn.cursor()
114 prefix = term[:-1] # strip asterisk
115 cursor.set_range(to_text(term).encode())
116 while cursor.key().startswith(to_text(prefix).encode()):
117 for key, value in cursor:
118 ret.append((to_text(key), to_native(value)))
119 cursor.next()
120 else:
121 value = txn.get(to_text(term).encode())
122 if value is not None:
123 ret.append(to_native(value))
124
125 return ret