Coverage for /Users/buh/.pyenv/versions/3.12.2/envs/pii/lib/python3.12/site-packages/es_pii_tool/base.py: 71%
113 statements
« prev ^ index » next coverage.py v7.5.0, created at 2025-01-29 19:29 -0700
« prev ^ index » next coverage.py v7.5.0, created at 2025-01-29 19:29 -0700
1"""Main app definition"""
3# pylint: disable=broad-exception-caught,R0913
4import typing as t
5import logging
6from es_pii_tool.exceptions import FatalError, MissingIndex
7from es_pii_tool.job import Job
8from es_pii_tool.redacters.index import RedactIndex
9from es_pii_tool.trackables import Task
10from es_pii_tool.helpers.elastic_api import get_hits
11from es_pii_tool.helpers.utils import end_it, get_redactions
13if t.TYPE_CHECKING:
14 from elasticsearch8 import Elasticsearch
16logger = logging.getLogger(__name__)
19class PiiTool:
20 """Elasticsearch PII Tool"""
22 def __init__(
23 self,
24 client: 'Elasticsearch',
25 tracking_index: str,
26 redaction_file: str = '',
27 redaction_dict: t.Union[t.Dict, None] = None,
28 dry_run: bool = False,
29 ):
30 if redaction_dict is None:
31 redaction_dict = {}
32 logger.debug('Redactions file: %s', redaction_file)
33 self.counter = 0
34 self.client = client
35 self.redactions = get_redactions(redaction_file, redaction_dict)
36 self.tracking_index = tracking_index
37 self.dry_run = dry_run
39 def verify_doc_count(self, job: Job) -> bool:
40 """Verify that expected_docs and the hits from the query have the same value
42 :param job: The job object for the present redaction run
44 :type job: :py:class:`~.app.tracking.Job`
46 :rtype: None
47 :returns: No return value
48 """
49 try:
50 task = Task(job, task_id=f'PRE---{job.name}---DOC-COUNT-VERIFICATION')
51 except Exception as err:
52 logger.critical('Unable to create task: %s', err)
53 raise FatalError('Unable to create task', err) from err
54 success = False
55 errors = False
56 if task.finished():
57 return True # We're done already
58 # Log task start
59 task.begin()
60 hits = 0
61 try:
62 hits = get_hits(self.client, job.config['pattern'], job.config['query'])
63 except Exception as err:
64 logger.critical('Unable to count query result hits: %s', err)
65 raise err
66 msg = f'{hits} hit(s)'
67 logger.debug(msg)
68 task.add_log(msg)
69 logger.info("Checking expected document count...")
70 zeromsg = (
71 f"For index pattern {job.config['pattern']}, with query "
72 f"{job.config['query']} 'expected_docs' is {job.config['expected_docs']} "
73 f"but query results is {hits} matches."
74 )
75 if job.config['expected_docs'] == hits:
76 msg = (
77 f'Query result hits: {hits} matches expected_docs: '
78 f'{job.config["expected_docs"]}'
79 )
80 logger.debug(msg)
81 task.add_log(msg)
82 success = True
83 if hits == 0:
84 logger.critical(zeromsg)
85 logger.info('Continuing to next configuration block (if any)')
86 success = False
87 else:
88 logger.critical(zeromsg)
89 logger.info('Continuing to next configuration block (if any)')
90 if not success:
91 errors = True
92 task.add_log(zeromsg)
93 task.end(success, errors=errors)
94 return success
96 def iterate_indices(self, job: Job) -> bool:
97 """Iterate over every index in job.indices"""
98 all_succeeded = True
99 for idx in job.indices:
100 try:
101 task = Task(job, index=idx, id_suffix='PARENT-TASK')
102 # First check to see if idx has been touched as part of a previous run
103 if task.finished():
104 continue # This index has already been verified
105 task.begin()
106 except Exception as err:
107 logger.critical('Unable to create task: %s', err)
108 raise FatalError('Unable to create task', err) from err
109 task_success = False
110 try:
111 msg = f'Iterating per index: Index {idx} of {job.indices}'
112 logger.debug(msg)
113 task.add_log(msg)
114 redact = RedactIndex(idx, job, self.counter)
115 redact.run()
116 task_success = redact.success
117 self.counter = redact.counter
118 logger.debug('RESULT: %s', task_success)
119 except MissingIndex as err:
120 logger.critical(err)
121 raise FatalError(f'Index {err.missing} not found.', err) from err
122 except FatalError as err:
123 logger.critical('Fatal upstream error encountered: %s', err.message)
124 raise FatalError('We suffered a fatal upstream error', err) from err
125 end_it(task, task_success)
126 if not task.completed:
127 all_succeeded = False
128 job.add_log(f'Unable to complete task {task.task_id}')
129 return all_succeeded
131 def iterate_configuration(self) -> None:
132 """Iterate over every configuration block in self.redactions"""
133 logger.debug('Full redactions object from config: %s', self.redactions)
134 for config_block in self.redactions['redactions']: # type: ignore
135 job_success = True
136 # Reset counter to zero for each full iteration
137 self.counter = 0
138 if self.dry_run:
139 logger.info("DRY-RUN MODE ENABLED. No data will be changed.")
141 # There's really only 1 root-level key for each configuration block,
142 # and that's job_id
143 job_name = list(config_block.keys())[0]
144 args = (self.client, self.tracking_index, job_name, config_block[job_name])
145 job = Job(*args, dry_run=self.dry_run)
146 if job.finished():
147 continue
148 job.begin()
149 if not self.verify_doc_count(job):
150 # This configuration block can't go further because of the mismatch
151 job_success = False
152 end_it(job, job_success)
153 continue
155 job_success = self.iterate_indices(job)
156 # At this point, self.counter should be equal to total, indicating that we
157 # matched expected_docs. We should therefore register that the job was
158 # successful, if we have reached this point with no other errors having
159 # interrupted the process.
161 end_it(job, job_success)
163 def run(self) -> None:
164 """Do the thing"""
165 logger.info('PII scrub initiated')
166 self.iterate_configuration()