-
Notifications
You must be signed in to change notification settings - Fork 0
/
workers.py
339 lines (274 loc) · 9.59 KB
/
workers.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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# Copyright 2024 Josua Krause
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Example showcasing producer and consumers with a dynamic amount of workers
and local vs. remote setup."""
import argparse
import random
import threading
import time
from typing import cast, Literal, NoReturn
import redipy
from redipy import ExecFunction, RedisClientAPI
from redipy.script import FnContext, RedisHash, RedisSortedSet, RedisVar, ToNum
def get_worker_id(client: RedisClientAPI, heartbeat_key: str) -> str:
"""
Assigns a unique worker id.
Args:
client (RedisClientAPI): The redis client.
heartbeat_key (str): The heartbeat key base.
Returns:
str: The unique worker id.
"""
worker_num = 0
while True:
worker_id = f"w{worker_num:08x}"
if not client.set_value(
f"{heartbeat_key}:{worker_id}", "init", mode="if_missing"):
worker_num += 1
continue
print(f"register worker {worker_id}")
return worker_id
def worker_heartbeat(
worker_id: str,
client: RedisClientAPI,
heartbeat_key: str) -> NoReturn:
"""
Signals that the current worker is still active.
Args:
worker_id (str): The worker id.
client (RedisClientAPI): The redis client.
heartbeat_key (str): The heartbeat key base.
"""
while True:
client.set_value(
f"{heartbeat_key}:{worker_id}", "alive", expire_in=2.0)
time.sleep(1.0)
def detect_stale_workers(
client: RedisClientAPI,
queue_key: str,
busy_key: str,
heartbeat_key: str) -> NoReturn:
"""
Goes through the list of active tasks and checks whether the associated
workers are still alive. If not, the task is added back to the task queue
with a higher priority.
Args:
client (RedisClientAPI): The redis client.
queue_key (str): The task queue key.
busy_key (str): The busy hash key.
heartbeat_key (str): The heartbeat key base.
"""
def _task_check() -> ExecFunction:
ctx = FnContext()
queue = RedisSortedSet(ctx.add_key("queue"))
busy = RedisHash(ctx.add_key("busy"))
heartbeat = RedisVar(ctx.add_key("heartbeat"))
task = ctx.add_arg("task")
res = ctx.add_local(None)
b_then, _ = ctx.if_(heartbeat.exists().eq_(0))
b_then.add(queue.add(2.0, task))
b_then.add(busy.hdel(task))
b_then.add(res.assign(queue.card()))
ctx.set_return_value(res)
return client.register_script(ctx)
task_check = _task_check()
while True:
for task_id, worker_id in client.hgetall(busy_key).items():
cur = cast(int | None, task_check(
keys={
"queue": queue_key,
"busy": busy_key,
"heartbeat": f"{heartbeat_key}:{worker_id}",
},
args={
"task": task_id,
}))
if cur is not None:
print(f"readd task {task_id} (total tasks {cur})")
time.sleep(1.0)
def enqueue_task(
client: RedisClientAPI,
queue_key: str,
info_key: str,
priority: float,
task_id: str,
task_payload: float) -> None:
"""
Adds a new task to the task queue.
Args:
client (RedisClientAPI): The redis client.
queue_key (str): The task queue key.
info_key (str): The task info hash key.
priority (float): The priority of the task.
task_id (str): The task id.
task_payload (float): The task payload.
"""
with client.pipeline() as pipe:
pipe.hset(info_key, {task_id: f"{task_payload}"})
pipe.zadd(queue_key, {task_id: priority})
pipe.zcard(queue_key)
_, _, count = pipe.execute()
print(f"add task {task_id} (payload {task_payload}; total tasks {count})")
def execute_task(
worker_id: str,
task_id: str,
task_payload: float) -> None:
"""
Executes a task.
Args:
worker_id (str): The worker id.
task_id (str): The task id.
task_payload (float): The task payload.
"""
print(f"[{worker_id}] start task {task_id} ({task_payload})")
if task_payload > 0.0:
time.sleep(task_payload)
print(f"[{worker_id}] finished task {task_id}")
def consume_task_loop(
worker_id: str,
client: RedisClientAPI,
queue_key: str,
info_key: str,
busy_key: str) -> NoReturn:
"""
Consumes and executes tasks in a loop.
Args:
worker_id (str): The worker id.
client (RedisClientAPI): The redis client.
queue_key (str): The task queue key.
info_key (str): The task info hash key.
busy_key (str): The busy hash key.
"""
def _pick_task() -> ExecFunction:
ctx = FnContext()
queue = RedisSortedSet(ctx.add_key("queue"))
info = RedisHash(ctx.add_key("info"))
busy = RedisHash(ctx.add_key("busy"))
worker = ctx.add_arg("worker")
res = ctx.add_local([])
loop, _, task = ctx.for_(queue.pop_max())
loop.add(res.set_at(res.len_(), task[0]))
loop.add(res.set_at(res.len_(), ToNum(info.hget(task[0]))))
loop.add(busy.hset({task[0]: worker}))
ctx.set_return_value(res)
return client.register_script(ctx)
pick_task = _pick_task()
while True:
task = cast(list, pick_task(
keys={
"queue": queue_key,
"info": info_key,
"busy": busy_key,
},
args={
"worker": worker_id,
}))
if not task:
time.sleep(1.0)
continue
task_id, task_payload = task
execute_task(worker_id, task_id, task_payload)
with client.pipeline() as pipe:
pipe.hdel(info_key, task_id)
pipe.hdel(busy_key, task_id)
def produce_task_loop(
client: RedisClientAPI, queue_key: str, info_key: str) -> NoReturn:
"""
Produces new tasks in a loop.
Args:
client (RedisClientAPI): The redis client.
queue_key (str): The task queue key.
info_key (str): The task info hash key.
"""
task_num = 0
while True:
priority = random.choice([0, 0.25, 0.5, 0.75, 1.0])
task_id = f"t{task_num:08x}"
task_payload = random.choice([0, 0.25, 0.5, 0.75, 1.0])
enqueue_task(
client, queue_key, info_key, priority, task_id, task_payload)
time.sleep(0.25)
task_num += 1
def parse_args() -> tuple[Literal["single", "producer", "worker"], bool]:
"""
Parses the command line arguments.
Returns:
str: The mode.
"""
parser = argparse.ArgumentParser(description="Worker Example")
parser.add_argument(
"mode",
choices=["single", "producer", "worker"],
help=(
"Which mode to run. Single is fully self contained. "
"Producer and worker run in separate processes together."
))
parser.add_argument(
"--verbose",
action="store_true",
help="If set all generated lua scripts are printed to stdout.")
args = parser.parse_args()
return args.mode, args.verbose
def run() -> None:
"""Runs the app."""
mode, lua_verbose = parse_args()
queue_key = "task_queue"
info_key = "task_info"
busy_key = "busy_tasks"
heartbeat_key = "heartbeat"
def do_cleanup(client: RedisClientAPI) -> NoReturn:
detect_stale_workers(client, queue_key, busy_key, heartbeat_key)
def do_produce(client: RedisClientAPI) -> NoReturn:
produce_task_loop(client, queue_key, info_key)
def do_heartbeat(worker_id: str, client: RedisClientAPI) -> NoReturn:
worker_heartbeat(worker_id, client, heartbeat_key)
def do_consume(worker_id: str, client: RedisClientAPI) -> NoReturn:
consume_task_loop(worker_id, client, queue_key, info_key, busy_key)
def print_lua(code: list[str]) -> None:
for line in code:
print(line)
if mode == "single":
client = redipy.Redis()
for wid in range(3):
threading.Thread(
target=do_consume,
args=(f"w{wid:08x}", client),
daemon=True).start()
do_produce(client)
else:
client = redipy.Redis(
cfg={
"host": "localhost",
"port": 6379,
"passwd": "",
"prefix": "",
},
lua_code_hook=print_lua if lua_verbose else None)
if mode == "producer":
threading.Thread(
target=do_cleanup,
args=(client,),
daemon=True).start()
do_produce(client)
elif mode == "worker":
worker_id = get_worker_id(client, heartbeat_key)
threading.Thread(
target=do_heartbeat,
args=(worker_id, client),
daemon=True).start()
do_consume(worker_id, client)
else:
raise ValueError(f"invalid mode: {mode}")
if __name__ == "__main__":
run()