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