-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmayhem_1.py
190 lines (147 loc) · 5.18 KB
/
mayhem_1.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
#!/usr/bin/env python3.7
# Copyright (c) 2018-2019 Lynn Root
"""
The case of unhandled exception.
Notice! This requires:
- attrs==19.1.0
To run:
$ python part-3/mayhem_1.py
Follow along: https://roguelynn.com/words/asyncio-exception-handling/
"""
import asyncio
import logging
import random
import signal
import string
import uuid
import attr
# NB: Using f-strings with log messages may not be ideal since no matter
# what the log level is set at, f-strings will always be evaluated
# whereas the old form ("foo %s" % "bar") is lazily-evaluated.
# But I just love f-strings.
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s",
datefmt="%H:%M:%S",
)
@attr.s
class PubSubMessage:
instance_name = attr.ib()
message_id = attr.ib(repr=False)
hostname = attr.ib(repr=False, init=False)
restarted = attr.ib(repr=False, default=False)
saved = attr.ib(repr=False, default=False)
acked = attr.ib(repr=False, default=False)
extended_cnt = attr.ib(repr=False, default=0)
def __attrs_post_init__(self):
self.hostname = f"{self.instance_name}.example.net"
async def publish(queue):
"""Simulates an external publisher of messages.
Args:
queue (asyncio.Queue): Queue to publish messages to.
"""
choices = string.ascii_lowercase + string.digits
while True:
msg_id = str(uuid.uuid4())
host_id = "".join(random.choices(choices, k=4))
instance_name = f"cattle-{host_id}"
msg = PubSubMessage(message_id=msg_id, instance_name=instance_name)
# publish an item
asyncio.create_task(queue.put(msg))
logging.debug(f"Published message {msg}")
# simulate randomness of publishing messages
await asyncio.sleep(random.random())
async def restart_host(msg):
"""Restart a given host.
Args:
msg (PubSubMessage): consumed event message for a particular
host to be restarted.
"""
# unhelpful simulation of i/o work
await asyncio.sleep(random.random())
msg.restart = True
logging.info(f"Restarted {msg.hostname}")
async def save(msg):
"""Save message to a database.
Args:
msg (PubSubMessage): consumed event message to be saved.
"""
# unhelpful simulation of i/o work
await asyncio.sleep(random.random())
msg.save = True
logging.info(f"Saved {msg} into database")
async def cleanup(msg, event):
"""Cleanup tasks related to completing work on a message.
Args:
msg (PubSubMessage): consumed event message that is done being
processed.
"""
# this will block the rest of the coro until `event.set` is called
await event.wait()
# unhelpful simulation of i/o work
await asyncio.sleep(random.random())
msg.acked = True
logging.info(f"Done. Acked {msg}")
async def extend(msg, event):
"""Periodically extend the message acknowledgement deadline.
Args:
msg (PubSubMessage): consumed event message to extend.
event (asyncio.Event): event to watch for message extention or
cleaning up.
"""
while not event.is_set():
msg.extended_cnt += 1
logging.info(f"Extended deadline by 3 seconds for {msg}")
# want to sleep for less than the deadline amount
await asyncio.sleep(2)
async def handle_message(msg):
"""Kick off tasks for a given message.
Args:
msg (PubSubMessage): consumed message to process.
"""
event = asyncio.Event()
asyncio.create_task(extend(msg, event))
asyncio.create_task(cleanup(msg, event))
await asyncio.gather(save(msg), restart_host(msg))
event.set()
async def consume(queue):
"""Consumer client to simulate subscribing to a publisher.
Args:
queue (asyncio.Queue): Queue from which to consume messages.
"""
while True:
msg = await queue.get()
# totally realistic exception
if random.randrange(1, 5) == 3:
raise Exception(f"Could not consume {msg}")
logging.info(f"Consumed {msg}")
asyncio.create_task(handle_message(msg))
async def shutdown(signal, loop):
"""Cleanup tasks tied to the service's shutdown."""
logging.info(f"Received exit signal {signal.name}...")
logging.info("Closing database connections")
logging.info("Nacking outstanding messages")
tasks = [t for t in asyncio.all_tasks() if t is not
asyncio.current_task()]
[task.cancel() for task in tasks]
logging.info(f"Cancelling {len(tasks)} outstanding tasks")
await asyncio.gather(*tasks, return_exceptions=True)
logging.info(f"Flushing metrics")
loop.stop()
def main():
loop = asyncio.get_event_loop()
# May want to catch other signals too
signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
for s in signals:
loop.add_signal_handler(
s, lambda s=s: asyncio.create_task(shutdown(s, loop)))
queue = asyncio.Queue()
try:
loop.create_task(publish(queue))
loop.create_task(consume(queue))
loop.run_forever()
finally:
loop.close()
logging.info("Successfully shutdown the Mayhem service.")
if __name__ == "__main__":
main()