Coverage for /Users/buh/.pyenv/versions/3.12.9/envs/es-testbed/lib/python3.12/site-packages/es_testbed/_base.py: 100%
163 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-04-16 12:29 -0600
« prev ^ index » next coverage.py v7.6.12, created at 2025-04-16 12:29 -0600
1"""Base TestBed Class"""
3import typing as t
4import logging
5from importlib import import_module
6from datetime import datetime, timezone
7from shutil import rmtree
8from .debug import debug, begin_end
9from .defaults import NAMEMAPPER
10from .es_api import delete, get
11from .exceptions import ResultNotExpected
12from .utils import prettystr, process_preset
13from ._plan import PlanBuilder
14from .mgrs import (
15 ComponentMgr,
16 DataStreamMgr,
17 IlmMgr,
18 IndexMgr,
19 SnapshotMgr,
20 TemplateMgr,
21)
23if t.TYPE_CHECKING:
24 from elasticsearch8 import Elasticsearch
26logger = logging.getLogger('es_testbed.TestBed')
28# pylint: disable=R0902,R0913,R0917
30# Preset Import
31# This imports the preset directory which must include the following files:
32# - A plan YAML file.
33# - A buildlist YAML file.
34# - A functions.py file (the actual python code), which must contain a
35# function named doc_generator(). This function must accept all kwargs from
36# the buildlist's options
37# - A definitions.py file, which is a Python variable file that helps find
38# the path to the module, etc., as well as import the plan, the buildlist,
39# the mappings and settings, etc. This must at least include a get_plan()
40# function that returns a dictionary of a plan.
41# - A mappings.json file (contains the index mappings your docs need)
42# - A settings.json file (contains the index settings)
43#
44# Any other files can be included to help your doc_generator function, e.g.
45# Faker definitions and classes, etc. Once the preset module is imported,
46# relative imports should work.
49class TestBed:
50 """TestBed Class"""
52 __test__ = False # Without this, this appears to be test class because of the name
54 def __init__(
55 self,
56 client: t.Optional['Elasticsearch'] = None,
57 builtin: t.Optional[str] = None,
58 path: t.Optional[str] = None,
59 ref: t.Optional[str] = None,
60 url: t.Optional[str] = None,
61 scenario: t.Optional[str] = None,
62 ):
63 debug.lv2('Initializing TestBed object...')
64 #: The plan settings
65 self.settings = None
67 modpath, tmpdir = process_preset(builtin, path, ref, url)
68 if modpath is None:
69 msg = 'Must define a preset'
70 logger.critical(msg)
71 raise ValueError(msg)
73 try:
74 debug.lv4('TRY: Attempting to import preset module')
75 debug.lv5(f'preset module: {modpath}')
76 preset = import_module(f'{modpath}.definitions')
77 self.settings = preset.get_plan(scenario)
78 except ImportError as err:
79 logger.critical('Preset settings incomplete or incorrect')
80 raise err
81 debug.lv5(f'Preset module imported: {modpath}')
83 self.settings['modpath'] = modpath
84 if scenario:
85 debug.lv5(f'Using scenario: {scenario}')
86 self.settings['scenario'] = scenario
87 if tmpdir:
88 debug.lv5(f'Using tmpdir: {tmpdir}')
89 self.settings['tmpdir'] = tmpdir
91 #: The Elasticsearch client object
92 self.client = client
93 #: The test plan
94 self.plan = None
96 # Set up for tracking
97 #: The ILM entity manager
98 self.ilmmgr = None
99 #: The Component Template entity manager
100 self.componentmgr = None
101 #: The (index) Template entity manager
102 self.templatemgr = None
103 #: The Snapshot entity manager
104 self.snapshotmgr = None
105 #: The Index entity manager
106 self.indexmgr = None
107 #: The data_stream entity manager
108 self.data_streammgr = None
110 @begin_end()
111 def _erase(self, kind: str, lst: t.Sequence[str]) -> None:
112 overall_success = True
113 if not lst:
114 debug.lv3(f'{kind}: nothing to delete.')
115 return True
116 if kind == 'ilm': # ILM policies can't be batch deleted
117 ilm = [self._while(kind, x) for x in lst]
118 overall_success = False not in ilm # No False values == True
119 else:
120 overall_success = self._while(kind, ','.join(lst))
121 debug.lv5(f'Return value = {overall_success}')
122 return overall_success
124 @begin_end()
125 def _erase_all(
126 self,
127 ) -> t.Generator[str, t.Sequence[str], None]:
128 """Method to delete everything matching our pattern(s)"""
129 items = ['index', 'data_stream', 'snapshot', 'template', 'component', 'ilm']
130 for i in items:
131 if i == 'snapshot' and self.plan.repository is None:
132 debug.lv4('No repository, no snapshots.')
133 continue
134 pattern = f'*{self.plan.prefix}-{NAMEMAPPER[i]}-{self.plan.uniq}*'
135 entities = get(self.client, i, pattern, repository=self.plan.repository)
136 yield (i, entities)
138 @begin_end()
139 def _while(self, kind: str, item: str) -> bool:
140 count = 1
141 success = False
142 exc = None
143 while count < 4 and not success:
144 try:
145 debug.lv4(f'TRY: Deleting {kind} "{item}"')
146 success = delete(
147 self.client, kind, item, repository=self.plan.repository
148 )
149 break
150 except ResultNotExpected as err:
151 debug.lv1(f'Tried deleting "{item}" {count} time(s)')
152 exc = err
153 count += 1
154 if not success:
155 logger.warning(
156 f'Failed to delete "{item}" after {count - 1} tries. '
157 f'Final error: {exc}'
158 )
159 return success
161 @begin_end()
162 def get_ilm_polling(self) -> None:
163 """
164 Get current ILM polling settings and store them in self.plan.polling_interval
165 """
166 debug.lv3('Storing current ILM polling settings, if any...')
167 try:
168 debug.lv4('TRY: Getting cluster settings')
169 res = dict(self.client.cluster.get_settings())
170 debug.lv5(f'Cluster settings: {prettystr(res)}')
171 except Exception as err:
172 logger.critical('Unable to get persistent cluster settings')
173 logger.critical('This could be permissions, or something larger.')
174 logger.critical(f'Exception: {prettystr(err)}')
175 logger.critical('Exiting.')
176 raise err
177 try:
178 debug.lv4('TRY: Getting ILM Polling Interval from settings')
179 retval = res['persistent']['indices']['lifecycle']['poll_interval']
180 except KeyError:
181 debug.lv3('No setting for indices.lifecycle.poll_interval. Must be default')
182 retval = None # Must be an actual value to go into a DotMap
183 if retval == '1s':
184 msg = (
185 'ILM polling already set at 1s. A previous run most likely did not '
186 'tear down properly. Resetting to null after this run'
187 )
188 logger.warning(msg)
189 retval = None # Must be an actual value to go into a DotMap
190 self.plan.ilm_polling_interval = retval
191 debug.lv3(f'Stored ILM Polling Interval: {retval}')
193 @begin_end()
194 def ilm_polling(self, interval: t.Union[str, None] = None) -> t.Dict:
195 """Return persistent cluster settings to speed up ILM polling during testing"""
196 retval = {'indices.lifecycle.poll_interval': interval}
197 debug.lv5(f'Return value = {retval}')
198 return retval
200 @begin_end()
201 def setup(self) -> None:
202 """Setup the instance"""
203 start = datetime.now(timezone.utc)
204 # If we build self.plan here, then we can modify settings before setup()
205 self.plan = PlanBuilder(settings=self.settings).plan
206 self.get_ilm_polling()
207 debug.lv5(f'Setting: {self.ilm_polling(interval="1s")}')
208 self.client.cluster.put_settings(persistent=self.ilm_polling(interval='1s'))
209 self.setup_entitymgrs()
210 end = datetime.now(timezone.utc)
211 debug.lv1(f'Testbed setup elapsed time: {(end - start).total_seconds()}')
213 @begin_end()
214 def setup_entitymgrs(self) -> None:
215 """
216 Setup each EntityMgr child class
217 """
218 kw = {'client': self.client, 'plan': self.plan}
220 self.ilmmgr = IlmMgr(**kw)
221 self.ilmmgr.setup()
222 self.componentmgr = ComponentMgr(**kw)
223 self.componentmgr.setup()
224 self.templatemgr = TemplateMgr(**kw)
225 self.templatemgr.setup()
226 self.snapshotmgr = SnapshotMgr(**kw)
227 self.snapshotmgr.setup()
228 if self.plan.type == 'indices':
229 self.indexmgr = IndexMgr(**kw, snapmgr=self.snapshotmgr)
230 self.indexmgr.setup()
231 if self.plan.type == 'data_stream':
232 self.data_streammgr = DataStreamMgr(**kw, snapmgr=self.snapshotmgr)
233 self.data_streammgr.setup()
235 @begin_end()
236 def teardown(self) -> None:
237 """Tear down anything we created"""
238 start = datetime.now(timezone.utc)
239 successful = True
240 if self.plan.tmpdir:
241 debug.lv3(f'Removing tmpdir: {self.plan.tmpdir}')
242 rmtree(self.plan.tmpdir) # Remove the tmpdir stored here
243 for kind, list_of_kind in self._erase_all():
244 if not self._erase(kind, list_of_kind):
245 successful = False
246 persist = self.ilm_polling(interval=self.plan.ilm_polling_interval)
247 debug.lv3(
248 f'Restoring ILM polling to previous value: '
249 f'{self.plan.ilm_polling_interval}'
250 )
251 self.client.cluster.put_settings(persistent=persist)
252 end = datetime.now(timezone.utc)
253 debug.lv1(f'Testbed teardown elapsed time: {(end - start).total_seconds()}')
254 if successful:
255 logger.info('Cleanup successful')
256 else:
257 logger.error('Cleanup was unsuccessful/incomplete')
258 self.plan.cleanup = successful