-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
queues.py
427 lines (359 loc) · 15.6 KB
/
queues.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import multiprocessing
import pickle
import queue # needed as import instead from/import for mocking in tests
import time
import warnings
from abc import ABC, abstractmethod
from enum import Enum
from pathlib import Path
from typing import Any, Optional
from lightning_app.core.constants import (
HTTP_QUEUE_REFRESH_INTERVAL,
HTTP_QUEUE_TOKEN,
HTTP_QUEUE_URL,
LIGHTNING_DIR,
QUEUE_DEBUG_ENABLED,
REDIS_HOST,
REDIS_PASSWORD,
REDIS_PORT,
REDIS_QUEUES_READ_DEFAULT_TIMEOUT,
STATE_UPDATE_TIMEOUT,
WARNING_QUEUE_SIZE,
)
from lightning_app.utilities.app_helpers import Logger
from lightning_app.utilities.imports import _is_redis_available, requires
from lightning_app.utilities.network import HTTPClient
if _is_redis_available():
import redis
logger = Logger(__name__)
READINESS_QUEUE_CONSTANT = "READINESS_QUEUE"
ERROR_QUEUE_CONSTANT = "ERROR_QUEUE"
DELTA_QUEUE_CONSTANT = "DELTA_QUEUE"
HAS_SERVER_STARTED_CONSTANT = "HAS_SERVER_STARTED_QUEUE"
CALLER_QUEUE_CONSTANT = "CALLER_QUEUE"
API_STATE_PUBLISH_QUEUE_CONSTANT = "API_STATE_PUBLISH_QUEUE"
API_DELTA_QUEUE_CONSTANT = "API_DELTA_QUEUE"
API_REFRESH_QUEUE_CONSTANT = "API_REFRESH_QUEUE"
ORCHESTRATOR_REQUEST_CONSTANT = "ORCHESTRATOR_REQUEST"
ORCHESTRATOR_RESPONSE_CONSTANT = "ORCHESTRATOR_RESPONSE"
ORCHESTRATOR_COPY_REQUEST_CONSTANT = "ORCHESTRATOR_COPY_REQUEST"
ORCHESTRATOR_COPY_RESPONSE_CONSTANT = "ORCHESTRATOR_COPY_RESPONSE"
WORK_QUEUE_CONSTANT = "WORK_QUEUE"
API_RESPONSE_QUEUE_CONSTANT = "API_RESPONSE_QUEUE"
FLOW_TO_WORKS_DELTA_QUEUE_CONSTANT = "FLOW_TO_WORKS_DELTA_QUEUE"
class QueuingSystem(Enum):
MULTIPROCESS = "multiprocess"
REDIS = "redis"
HTTP = "http"
def get_queue(self, queue_name: str) -> "BaseQueue":
if self == QueuingSystem.MULTIPROCESS:
return MultiProcessQueue(queue_name, default_timeout=STATE_UPDATE_TIMEOUT)
elif self == QueuingSystem.REDIS:
return RedisQueue(queue_name, default_timeout=REDIS_QUEUES_READ_DEFAULT_TIMEOUT)
else:
return HTTPQueue(queue_name, default_timeout=STATE_UPDATE_TIMEOUT)
def get_api_response_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{API_RESPONSE_QUEUE_CONSTANT}" if queue_id else API_RESPONSE_QUEUE_CONSTANT
return self.get_queue(queue_name)
def get_readiness_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{READINESS_QUEUE_CONSTANT}" if queue_id else READINESS_QUEUE_CONSTANT
return self.get_queue(queue_name)
def get_delta_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{DELTA_QUEUE_CONSTANT}" if queue_id else DELTA_QUEUE_CONSTANT
return self.get_queue(queue_name)
def get_error_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{ERROR_QUEUE_CONSTANT}" if queue_id else ERROR_QUEUE_CONSTANT
return self.get_queue(queue_name)
def get_has_server_started_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{HAS_SERVER_STARTED_CONSTANT}" if queue_id else HAS_SERVER_STARTED_CONSTANT
return self.get_queue(queue_name)
def get_caller_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{CALLER_QUEUE_CONSTANT}_{work_name}" if queue_id else f"{CALLER_QUEUE_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_api_state_publish_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{API_STATE_PUBLISH_QUEUE_CONSTANT}" if queue_id else API_STATE_PUBLISH_QUEUE_CONSTANT
return self.get_queue(queue_name)
# TODO: This is hack, so we can remove this queue entirely when fully optimized.
def get_api_delta_queue(self, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = f"{queue_id}_{DELTA_QUEUE_CONSTANT}" if queue_id else DELTA_QUEUE_CONSTANT
return self.get_queue(queue_name)
def get_orchestrator_request_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{ORCHESTRATOR_REQUEST_CONSTANT}_{work_name}"
if queue_id
else f"{ORCHESTRATOR_REQUEST_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_orchestrator_response_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{ORCHESTRATOR_RESPONSE_CONSTANT}_{work_name}"
if queue_id
else f"{ORCHESTRATOR_RESPONSE_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_orchestrator_copy_request_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{ORCHESTRATOR_COPY_REQUEST_CONSTANT}_{work_name}"
if queue_id
else f"{ORCHESTRATOR_COPY_REQUEST_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_orchestrator_copy_response_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{ORCHESTRATOR_COPY_RESPONSE_CONSTANT}_{work_name}"
if queue_id
else f"{ORCHESTRATOR_COPY_RESPONSE_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_work_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{WORK_QUEUE_CONSTANT}_{work_name}" if queue_id else f"{WORK_QUEUE_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
def get_flow_to_work_delta_queue(self, work_name: str, queue_id: Optional[str] = None) -> "BaseQueue":
queue_name = (
f"{queue_id}_{FLOW_TO_WORKS_DELTA_QUEUE_CONSTANT}_{work_name}"
if queue_id
else f"{FLOW_TO_WORKS_DELTA_QUEUE_CONSTANT}_{work_name}"
)
return self.get_queue(queue_name)
class BaseQueue(ABC):
"""Base Queue class that has a similar API to the Queue class in python."""
@abstractmethod
def __init__(self, name: str, default_timeout: float):
self.name = name
self.default_timeout = default_timeout
@abstractmethod
def put(self, item):
pass
@abstractmethod
def get(self, timeout: int = None):
"""Returns the left most element of the queue.
Parameters
----------
timeout:
Read timeout in seconds, in case of input timeout is 0, the `self.default_timeout` is used.
A timeout of None can be used to block indefinitely.
"""
pass
@property
def is_running(self) -> bool:
"""Returns True if the queue is running, False otherwise.
Child classes should override this property and implement custom logic as required
"""
return True
class MultiProcessQueue(BaseQueue):
def __init__(self, name: str, default_timeout: float):
self.name = name
self.default_timeout = default_timeout
context = multiprocessing.get_context("spawn")
self.queue = context.Queue()
def put(self, item):
self.queue.put(item)
def get(self, timeout: int = None):
if timeout == 0:
timeout = self.default_timeout
return self.queue.get(timeout=timeout, block=(timeout is None))
class RedisQueue(BaseQueue):
@requires("redis")
def __init__(
self,
name: str,
default_timeout: float,
host: str = None,
port: int = None,
password: str = None,
):
"""
Parameters
----------
name:
The name of the list to use
default_timeout:
Default timeout for redis read
host:
The hostname of the redis server
port:
The port of the redis server
password:
Redis password
"""
if name is None:
raise ValueError("You must specify a name for the queue")
self.host = host or REDIS_HOST
self.port = port or REDIS_PORT
self.password = password or REDIS_PASSWORD
self.name = name
self.default_timeout = default_timeout
self.redis = redis.Redis(host=self.host, port=self.port, password=self.password)
def put(self, item: Any) -> None:
from lightning_app import LightningWork
is_work = isinstance(item, LightningWork)
# TODO: Be careful to handle with a lock if another thread needs
# to access the work backend one day.
# The backend isn't picklable
# Raises a TypeError: cannot pickle '_thread.RLock' object
if is_work:
backend = item._backend
item._backend = None
value = pickle.dumps(item)
queue_len = self.length()
if queue_len >= WARNING_QUEUE_SIZE:
warnings.warn(
f"The Redis Queue {self.name} length is larger than the "
f"recommended length of {WARNING_QUEUE_SIZE}. "
f"Found {queue_len}. This might cause your application to crash, "
"please investigate this."
)
try:
self.redis.rpush(self.name, value)
except redis.exceptions.ConnectionError:
raise ConnectionError(
"Your app failed because it couldn't connect to Redis. "
"Please try running your app again. "
"If the issue persists, please contact support@lightning.ai"
)
# The backend isn't pickable.
if is_work:
item._backend = backend
def get(self, timeout: int = None):
"""Returns the left most element of the redis queue.
Parameters
----------
timeout:
Read timeout in seconds, in case of input timeout is 0, the `self.default_timeout` is used.
A timeout of None can be used to block indefinitely.
"""
if timeout is None:
# this means it's blocking in redis
timeout = 0
elif timeout == 0:
timeout = self.default_timeout
try:
out = self.redis.blpop([self.name], timeout=timeout)
except redis.exceptions.ConnectionError:
raise ConnectionError(
"Your app failed because it couldn't connect to Redis. "
"Please try running your app again. "
"If the issue persists, please contact support@lightning.ai"
)
if out is None:
raise queue.Empty
return pickle.loads(out[1])
def clear(self) -> None:
"""Clear all elements in the queue."""
self.redis.delete(self.name)
def length(self) -> int:
"""Returns the number of elements in the queue."""
try:
return self.redis.llen(self.name)
except redis.exceptions.ConnectionError:
raise ConnectionError(
"Your app failed because it couldn't connect to Redis. "
"Please try running your app again. "
"If the issue persists, please contact support@lightning.ai"
)
@property
def is_running(self) -> bool:
"""Pinging the redis server to see if it is alive."""
try:
return self.redis.ping()
except redis.exceptions.ConnectionError:
return False
def to_dict(self):
return {
"type": "redis",
"name": self.name,
"default_timeout": self.default_timeout,
"host": self.host,
"port": self.port,
"password": self.password,
}
@classmethod
def from_dict(cls, state):
return cls(**state)
class HTTPQueue(BaseQueue):
def __init__(self, name: str, default_timeout: float):
"""
Parameters
----------
name:
The name of the Queue to use. In the current implementation, we expect the name to be of the format
`appID_queueName`. Based on this assumption, we try to fetch the app id and the queue name by splitting
the `name` argument.
default_timeout:
Default timeout for redis read
"""
if name is None:
raise ValueError("You must specify a name for the queue")
self.app_id, self._name_suffix = self._split_app_id_and_queue_name(name)
self.name = name # keeping the name for debugging
self.default_timeout = default_timeout
self.client = HTTPClient(base_url=HTTP_QUEUE_URL, auth_token=HTTP_QUEUE_TOKEN, log_callback=debug_log_callback)
def get(self, timeout: int = None) -> Any:
if not self.app_id:
raise ValueError(f"App ID couldn't be extracted from the queue name: {self.name}")
# it's a blocking call, we need to loop and call the backend to mimic this behavior
if timeout is None:
while True:
try:
return self._get()
except queue.Empty:
time.sleep(HTTP_QUEUE_REFRESH_INTERVAL)
# make one request and return the result
if timeout == 0:
return self._get()
# timeout is some value - loop until the timeout is reached
start_time = time.time()
while (time.time() - start_time) < timeout:
try:
return self._get()
except queue.Empty:
pass
def _get(self):
resp = self.client.post(f"v1/{self.app_id}/{self._name_suffix}", query_params={"action": "pop"})
if resp.status_code == 204:
raise queue.Empty
return pickle.loads(resp.content)
def put(self, item: Any) -> None:
if not self.app_id:
raise ValueError(f"The Lightning App ID couldn't be extracted from the queue name: {self.name}")
value = pickle.dumps(item)
queue_len = self.length()
if queue_len >= WARNING_QUEUE_SIZE:
warnings.warn(
f"The Queue {self._name_suffix} length is larger than the recommended length of {WARNING_QUEUE_SIZE}. "
f"Found {queue_len}. This might cause your application to crash, please investigate this."
)
resp = self.client.post(f"v1/{self.app_id}/{self._name_suffix}", data=value, query_params={"action": "push"})
if resp.status_code != 201:
raise RuntimeError(f"Failed to push to queue: {self._name_suffix}")
def length(self):
if not self.app_id:
raise ValueError(f"App ID couldn't be extracted from the queue name: {self.name}")
val = self.client.get(f"/v1/{self.app_id}/{self._name_suffix}/length")
return int(val.text)
@staticmethod
def _split_app_id_and_queue_name(queue_name):
"""This splits the app id and the queue name into two parts.
This can be brittle, as if the queue name creation logic changes, the response values from here wouldn't be
accurate. Remove this eventually and let the Queue class take app id and name of the queue as arguments
"""
if "_" not in queue_name:
return "", queue_name
app_id, queue_name = queue_name.split("_", 1)
return app_id, queue_name
def to_dict(self):
return {
"type": "http",
"name": self.name,
"default_timeout": self.default_timeout,
}
@classmethod
def from_dict(cls, state):
return cls(**state)
def debug_log_callback(message: str, *args: Any, **kwargs: Any) -> None:
if QUEUE_DEBUG_ENABLED or (Path(LIGHTNING_DIR) / "QUEUE_DEBUG_ENABLED").exists():
logger.info(message, *args, **kwargs)