-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathhost_reaper.py
executable file
·164 lines (128 loc) · 5.7 KB
/
host_reaper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/python
import sys
from functools import partial
from prometheus_client import CollectorRegistry
from prometheus_client import push_to_gateway
from sqlalchemy import and_
from sqlalchemy import create_engine
from sqlalchemy import or_
from sqlalchemy.orm import sessionmaker
from api.cache import init_cache
from app import create_app
from app.auth.identity import create_mock_identity_with_org_id
from app.config import Config
from app.environment import RuntimeEnvironment
from app.logging import get_logger
from app.logging import threadctx
from app.models import Host
from app.models import Staleness
from app.queue.event_producer import EventProducer
from app.queue.metrics import event_producer_failure
from app.queue.metrics import event_producer_success
from app.queue.metrics import event_serialization_time
from lib.handlers import ShutdownHandler
from lib.handlers import register_shutdown
from lib.host_delete import delete_hosts
from lib.host_repository import find_hosts_by_staleness_reaper
from lib.host_repository import find_hosts_sys_default_staleness
from lib.metrics import delete_host_count
from lib.metrics import delete_host_processing_time
from lib.metrics import host_reaper_fail_count
__all__ = ("main", "run")
PROMETHEUS_JOB = "inventory-reaper"
LOGGER_NAME = "host_reaper"
COLLECTED_METRICS = (
delete_host_count,
delete_host_processing_time,
host_reaper_fail_count,
event_producer_failure,
event_producer_success,
event_serialization_time,
)
RUNTIME_ENVIRONMENT = RuntimeEnvironment.JOB
def _init_config():
config = Config(RUNTIME_ENVIRONMENT)
config.log_configuration()
return config
def _init_db(config):
engine = create_engine(config.db_uri)
return sessionmaker(bind=engine)
def _prometheus_job(namespace):
return f"{PROMETHEUS_JOB}-{namespace}" if namespace else PROMETHEUS_JOB
def _excepthook(logger, type, value, traceback):
logger.exception("Host reaper failed", exc_info=value)
def filter_culled_hosts_using_custom_staleness(logger, session):
staleness_objects = session.query(Staleness).all()
org_ids = []
query_filters = []
for staleness_obj in staleness_objects:
# Validate which host types for a given org_id never get deleted
logger.debug(f"Looking for hosts from org_id {staleness_obj.org_id} that use custom staleness")
org_ids.append(staleness_obj.org_id)
identity = create_mock_identity_with_org_id(staleness_obj.org_id)
query_filters.append(
and_(
(Host.org_id == staleness_obj.org_id),
find_hosts_by_staleness_reaper(["culled"], identity),
)
)
return query_filters, org_ids
def filter_culled_hosts_using_sys_default_staleness(logger, org_ids):
# Use the hosts_ids_list to exclude hosts that were found with custom staleness
logger.debug("Looking for hosts that use system default staleness")
return and_(~Host.org_id.in_(org_ids), find_hosts_sys_default_staleness(["culled"]))
def find_hosts_to_delete(logger, session):
# Find all host ids that are using custom staleness
query_filters, org_ids = filter_culled_hosts_using_custom_staleness(logger, session)
# Find all host ids that are not using custom staleness,
# excluding the hosts for the org_ids that use custom staleness
query_filters.append(filter_culled_hosts_using_sys_default_staleness(logger, org_ids))
return query_filters
@host_reaper_fail_count.count_exceptions()
def run(config, logger, session, event_producer, notification_event_producer, shutdown_handler, application):
with application.app.app_context():
filter_hosts_to_delete = find_hosts_to_delete(logger, session)
query = session.query(Host).filter(or_(False, *filter_hosts_to_delete))
hosts_processed = config.host_delete_chunk_size
deletions_remaining = query.count()
while hosts_processed == config.host_delete_chunk_size:
logger.info(f"Reaper starting batch; {deletions_remaining} remaining.")
try:
events = delete_hosts(
query,
event_producer,
notification_event_producer,
config.host_delete_chunk_size,
shutdown_handler.shut_down,
control_rule="REAPER",
)
hosts_processed = len(list(events))
except InterruptedError:
events = []
hosts_processed = 0
deletions_remaining -= hosts_processed
def main(logger):
config = _init_config()
application = create_app(RUNTIME_ENVIRONMENT)
init_cache(config, application)
registry = CollectorRegistry()
for metric in COLLECTED_METRICS:
registry.register(metric)
job = _prometheus_job(config.kubernetes_namespace)
prometheus_shutdown = partial(push_to_gateway, config.prometheus_pushgateway, job, registry)
register_shutdown(prometheus_shutdown, "Pushing metrics")
Session = _init_db(config)
session = Session()
register_shutdown(session.get_bind().dispose, "Closing database")
event_producer = EventProducer(config, config.event_topic)
register_shutdown(event_producer.close, "Closing producer")
notification_event_producer = EventProducer(config, config.notification_topic)
register_shutdown(notification_event_producer.close, "Closing notification producer")
shutdown_handler = ShutdownHandler()
shutdown_handler.register()
run(config, logger, session, event_producer, notification_event_producer, shutdown_handler, application)
if __name__ == "__main__":
logger = get_logger(LOGGER_NAME)
sys.excepthook = partial(_excepthook, logger)
threadctx.request_id = None
main(logger)