-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathworker.py
More file actions
260 lines (224 loc) · 9.68 KB
/
Copy pathworker.py
File metadata and controls
260 lines (224 loc) · 9.68 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
from pprint import pformat # noqa
from collections import defaultdict
import time
import threading
import functools
import copy
from typing import Dict, Callable
import sqlalchemy
import structlog
from servicelayer.taskqueue import Worker, Task
from servicelayer import settings as sls
from aleph import __version__
from aleph.core import kv, db, create_app
from aleph.settings import SETTINGS
from aleph.model import Collection
from aleph.queues import get_rate_limit
from aleph.logic.alerts import check_alerts
from aleph.logic.api_keys import send_api_key_expiration_notifications
from aleph.logic.collections import reingest_collection, reindex_collection
from aleph.logic.collections import compute_collections, refresh_collection
from aleph.logic.notifications import generate_digest, delete_old_notifications
from aleph.logic.roles import update_roles
from aleph.logic.export import delete_expired_exports, export_entities
from aleph.logic.processing import index_many
from aleph.logic.xref import xref_collection, export_matches
from aleph.logic.entities import update_entity, prune_entity
from aleph.logic.mapping import load_mapping, flush_mapping
INDEXING_TIMEOUT = (
SETTINGS.INDEXING_TIMEOUT
) # run all available indexing jobs in a batch after 10 seconds
log = structlog.get_logger(__name__)
app = create_app(config={"SERVER_NAME": SETTINGS.APP_UI_URL})
indexing_lock = threading.Lock()
def op_index(batch, worker: Worker):
sync = False
for collection_id in batch:
for task in batch[collection_id]:
if task.context.get("sync", False):
sync = True
break
item_count = sum(map(len, batch.values()))
log.debug(
f"Running batch indexing with {item_count}"
f" items from {len(batch.keys())} collections"
)
# we want skip_errors=True because we can't recover from ftm merge related errors
index_many(batch, sync=sync, skip_errors=True)
for collection_id, tasks in batch.items():
for task in tasks:
# acknowledge batched tasks
log.info(
f"Task [collection: {task.collection_id}]: "
f"op:{task.operation} task_id:{task.task_id} priority: {task.priority} (done)"
)
# avoid data race with the main thread by using a copy of the task
channel = task._channel
delattr(task, "_channel")
task = copy.deepcopy(task)
task.context["skip_ack"] = False
cb = functools.partial(worker.ack_message, task, channel)
channel.connection.add_callback_threadsafe(cb)
def op_reingest(collection, task):
reingest_collection(collection, job_id=task.job_id, **task.payload)
def op_reindex(collection, task):
sync = task.context.get("sync", False)
reindex_collection(collection, sync=sync, **task.payload)
def op_flush_mapping(collection, task):
sync = task.context.get("sync", False)
flush_mapping(collection, sync=sync, **task.payload)
# All stages that aleph should listen for. Does not include ingest,
# which is received and processed by the ingest-file service.
OPERATIONS: Dict[str, Callable] = {
SETTINGS.STAGE_INDEX: op_index,
SETTINGS.STAGE_XREF: lambda c, _: xref_collection(c),
SETTINGS.STAGE_REINGEST: op_reingest,
SETTINGS.STAGE_REINDEX: op_reindex,
SETTINGS.STAGE_LOAD_MAPPING: lambda c, t: load_mapping(c, **t.payload),
SETTINGS.STAGE_FLUSH_MAPPING: op_flush_mapping,
SETTINGS.STAGE_EXPORT_SEARCH: lambda _, t: export_entities(**t.payload),
SETTINGS.STAGE_EXPORT_XREF: lambda _, t: export_matches(**t.payload),
SETTINGS.STAGE_UPDATE_ENTITY: lambda c, t: update_entity(
c, job_id=t.job_id, **t.payload
),
SETTINGS.STAGE_PRUNE_ENTITY: lambda c, t: prune_entity(
c, job_id=t.job_id, **t.payload
),
}
class AlephWorker(Worker):
def __init__(
self,
queues,
conn=None,
num_threads=sls.WORKER_THREADS,
version=None,
prefetch_count_mapping=defaultdict(lambda: 1),
):
super().__init__(
queues,
conn=conn,
num_threads=num_threads,
version=version,
prefetch_count_mapping=prefetch_count_mapping,
)
self.often = get_rate_limit("often", unit=300, interval=1, limit=1)
self.daily = get_rate_limit("daily", unit=3600, interval=24, limit=1)
# special treatment for indexing jobs - indexing jobs need to be batched
# in batches of 100 (specified by INDEXING_BATCH_SIZE) or we wait for 10
# seconds (specified by INDEXING_TIMEOUT) before triggering an batched
# run of all available indexing tasks
self.indexing_batch_last_updated = 0.0
self.indexing_batches = defaultdict(list)
self.prefetch_count_mapping = prefetch_count_mapping
def on_signal(self, signal, _):
super().on_signal(signal, _)
def process(self, blocking=True):
if blocking:
with app.app_context():
self.process_blocking()
else:
self.process_nonblocking()
def periodic(self):
with app.app_context():
try:
db.session.remove()
if self.often.check():
self.often.update()
log.info("Self-check...")
compute_collections()
if self.daily.check():
self.daily.update()
log.info("Running daily tasks...")
update_roles()
check_alerts()
generate_digest()
send_api_key_expiration_notifications()
delete_expired_exports()
delete_old_notifications()
if SETTINGS.STAGE_INDEX in SETTINGS.ALEPH_STAGES:
self.run_indexing_batches()
except Exception:
log.exception("Error while executing periodic tasks")
def dispatch_task(self, task: Task) -> Task:
log.info(
f"Task [collection:{task.collection_id}]: "
f"op:{task.operation} task_id:{task.task_id} priority: {task.priority} (started)"
)
handler = OPERATIONS[task.operation]
collection = None
# We call commit here to prevent worker-created SQLa sessions
# from interfering with API-created, flask-sqlalchemy managed ones
try:
db.session.commit()
except sqlalchemy.exc.PendingRollbackError:
db.session.rollback()
with db.session.begin():
if task.collection_id is not None:
collection = Collection.by_id(task.collection_id, deleted=True)
# Task batching for index operation
if task.operation == SETTINGS.STAGE_INDEX:
with indexing_lock:
self.indexing_batches[task.collection_id].append(task)
self.indexing_batch_last_updated = time.time()
if (
sum(
[len(self.indexing_batches[id]) for id in self.indexing_batches]
)
>= SETTINGS.INDEXING_BATCH_SIZE
):
# batch size limit reached; execute the existing batch and reset
op_index(self.indexing_batches, worker=self)
self.indexing_batches = defaultdict(list)
self.indexing_batch_last_updated = 0.0
else:
log.info(
f"Task [collection: {task.collection_id}]: "
f"op:{task.operation} task_id:{task.task_id} priority: {task.priority} (batched)"
)
# skip acknowledgment for batched task; the batch processing function
# will acknowledge tasks after execution is complete
task.context["skip_ack"] = True
return task
handler(collection, task)
log.info(
f"Task [collection:{task.collection_id}]: "
f"op:{task.operation} task_id:{task.task_id} priority: {task.priority} (done)"
)
return task
def after_task(self, task):
if not SETTINGS.TESTING:
if task.collection_id and task.get_dataset(conn=kv).is_done():
refresh_collection(task.collection_id)
def run_indexing_batches(self):
"""Run remaining batched indexing tasks after waiting for a maximum of
INDEXING_TIMEOUT seconds"""
# is the lock needed?
with indexing_lock:
now = time.time()
since_last_update = int(now - self.indexing_batch_last_updated)
if since_last_update > INDEXING_TIMEOUT:
batched_item_count = sum(
[len(self.indexing_batches[id]) for id in self.indexing_batches]
)
if batched_item_count:
op_index(self.indexing_batches, worker=self)
self.indexing_batches = defaultdict(list)
self.indexing_batch_last_updated = 0.0
def get_worker(num_threads=1):
# The stages performed by AlephWorker correspond to
# RabbitMQ queues. Both use the same string as a name,
# By default, AlephWorker implements all stages
# (and reads from all queues) except "index" and "analyze".
aleph_worker_stages = list(SETTINGS.ALEPH_STAGES)
log.info(f"Worker active, stages: {aleph_worker_stages}")
qos_mapping = {}
for stage in aleph_worker_stages:
if stage not in qos_mapping:
qos_mapping[stage] = SETTINGS.QOS_MAPPING.get(stage, 1)
return AlephWorker(
queues=aleph_worker_stages,
conn=kv,
num_threads=num_threads or 1,
version=__version__,
prefetch_count_mapping=qos_mapping,
)