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 | class SupervisorStrategy(Service, SupervisorStrategyT):
"""Base class for all supervisor strategies."""
# set this future to wakeup supervisor
_please_wakeup: Optional[asyncio.Future]
#: the services we manage
_services: List[ServiceT]
# rate limit state
_bucket: Bucket
# what index is service at?
# if we have 10 services for example, and one of the crash,
# we want to know the position of the service we are restarting.
# This is needed for Faust and the @app.agent(concurrency=n) feature.
_index: Dict[ServiceT, int]
def __init__(
self,
*services: ServiceT,
max_restarts: Seconds = 100.0,
over: Seconds = 1.0,
raises: Type[BaseException] = MaxRestartsExceeded,
replacement: Optional[
Callable[[ServiceT, int], Awaitable[ServiceT]]
] = None,
**kwargs: Any,
) -> None:
self.max_restarts = want_seconds(max_restarts)
self.over = want_seconds(over)
self.raises = raises
self._bucket = rate_limit(self.max_restarts, self.over, raises=raises)
self._services = list(services or [])
self.replacement = replacement
self._please_wakeup = None
self._index = {}
super().__init__(**kwargs)
def wakeup(self) -> None:
notify(self._please_wakeup)
def add(self, *services: ServiceT) -> None:
# XXX not thread-safe, but shouldn't have to be.
size = len(self._services)
for i, service in enumerate(services):
if size:
pos = size + i
else:
pos = i
self._index[service] = pos
assert service.supervisor is None
self._contribute_to_service(service)
self._services.extend(services)
def _contribute_to_service(self, service: ServiceT) -> None:
# A "poisonpill" is the default behavior for any service
# with no supervisor attribute set.
#
# Setting the service.supervisor attribute here means calling
# `await service.crash(exc)` won't traverse the tree, crash
# every parent of the service, until it hits Worker terminating
# the running program abruptly. See `CrashingSupervisor`.
service.supervisor = self
def discard(self, *services: ServiceT) -> None:
for service in services:
self._index.pop(service, None)
try:
self._services.remove(service)
except ValueError:
pass
def insert(self, index: int, service: ServiceT) -> None:
old_service, self._services[index] = self._services[index], service
service.supervisor = self
self._index.pop(old_service, None)
self._index[service] = index
def service_operational(self, service: ServiceT) -> bool:
return not service.crashed
async def run_until_complete(self) -> None:
await self.start()
await self.stop()
@Service.task
async def _supervisor(self) -> None:
services = self._services
while not self.should_stop:
# other coroutines may set this future to wake us up using
# notify(self._please_wakeup)
self._please_wakeup = asyncio.Future(loop=self.loop)
try:
# we'll also timeout after five seconds,
# just in case nobody wakes us up.
await asyncio.wait_for(self._please_wakeup, timeout=5.0)
except asyncio.TimeoutError:
pass
finally:
self._please_wakeup = None
if not self.should_stop:
to_start: List[ServiceT] = []
to_restart: List[ServiceT] = []
for service in services:
if service.started:
if not self.service_operational(service):
to_restart.append(service)
else:
to_start.append(service)
await self.start_services(to_start)
await self.restart_services(to_restart)
async def on_start(self) -> None:
await self.start_services(self._services)
async def on_stop(self) -> None:
for service in self._services:
if service.started:
try:
await service.stop()
except MemoryError:
raise
except Exception as exc:
self.log.exception(
"Unable to stop service %r: %r", service, exc
)
async def start_services(self, services: List[ServiceT]) -> None:
for service in services:
await self.start_service(service)
async def start_service(self, service: ServiceT) -> None:
await service.maybe_start()
async def restart_services(self, services: List[ServiceT]) -> None:
for service in services:
await self.restart_service(service)
async def stop_services(self, services: List[ServiceT]) -> None:
# Stop them all simultaneously.
await asyncio.gather(*[service.stop() for service in services])
async def restart_service(self, service: ServiceT) -> None:
self.log.info(
"Restarting dead %r! Last crash reason: %r",
service,
service.crash_reason,
exc_info=1,
)
try:
async with self._bucket:
if self.replacement:
index = self._index[service]
new_service = await self.replacement(service, index)
new_service.supervisor = self
self.insert(index, new_service)
else:
await service.restart()
except MaxRestartsExceeded as exc:
self.log.warning("Max restarts exceeded: %r", exc, exc_info=1)
raise SystemExit(1) from None
@property
def label(self) -> str:
return f"{type(self).__name__}: ({len(self._services)}@{id(self):#x})"
|