/
db_base.py
1579 lines (1360 loc) · 54.5 KB
/
db_base.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import base64
import json
import os
import uuid
from collections import defaultdict
from itertools import chain, islice
import sqlalchemy as sa
from async_timeout import timeout
from cryptography.fernet import Fernet, MultiFernet
from traitlets import Bool, Float, Integer, List, Unicode, default, validate
from .. import models
from ..proxy import Proxy
from ..tls import new_keypair
from ..utils import Flag, FrozenAttrDict, TaskPool, normalize_address, timestamp
from ..workqueue import Backoff, WorkQueue, WorkQueueClosed
from .base import Backend
__all__ = ("DBBackendBase", "Cluster", "Worker")
def _normalize_encrypt_key(key):
if isinstance(key, str):
key = key.encode("ascii")
if len(key) == 44:
try:
key = base64.urlsafe_b64decode(key)
except ValueError:
pass
if len(key) == 32:
return base64.urlsafe_b64encode(key)
raise ValueError(
"All keys in `db_encrypt_keys`/`DASK_GATEWAY_ENCRYPT_KEYS` must be 32 "
"bytes, base64-encoded"
)
def _is_in_memory_db(url):
return url in ("sqlite://", "sqlite:///:memory:")
class _IntEnum(sa.TypeDecorator):
impl = sa.Integer
def __init__(self, enumclass, *args, **kwargs):
super().__init__(*args, **kwargs)
self._enumclass = enumclass
def process_bind_param(self, value, dialect):
return value.value
def process_result_value(self, value, dialect):
return self._enumclass(value)
class _JSON(sa.TypeDecorator):
"Represents an immutable structure as a json-encoded string."
impl = sa.LargeBinary
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value).encode("utf-8")
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
class JobStatus(models.IntEnum):
CREATED = 1
SUBMITTED = 2
RUNNING = 3
CLOSING = 4
STOPPED = 5
FAILED = 6
class Cluster:
"""Information on a cluster.
Not all attributes on this object are publically accessible. When writing a
backend, you may access the following attributes:
Attributes
----------
name : str
The cluster name.
username : str
The user associated with this cluster.
token : str
The API token associated with this cluster. Used to authenticate the
cluster with the gateway.
config : FrozenAttrDict
The serialized ``ClusterConfig`` associated with this cluster.
state : dict
Any cluster state, as yielded from ``do_start_cluster``.
scheduler_address : str
The scheduler address. The empty string if the cluster is not running.
dashboard_address : str
The dashboard address. The empty string if the cluster is not running,
or no dashboard is running on the cluster.
api_address : str
The cluster's api address. The empty string if the cluster is not running.
tls_cert : bytes
The TLS cert credentials associated with the cluster.
tls_key : bytes
The TLS key credentials associated with the cluster.
"""
def __init__(
self,
id=None,
name=None,
username=None,
token=None,
options=None,
config=None,
status=None,
target=None,
count=0,
state=None,
scheduler_address="",
dashboard_address="",
api_address="",
tls_cert=b"",
tls_key=b"",
start_time=None,
stop_time=None,
):
self.id = id
self.name = name
self.username = username
self.token = token
self.options = options
self.config = config
self.status = status
self.target = target
self.count = count
self.state = state
self.scheduler_address = scheduler_address
self.dashboard_address = dashboard_address
self.api_address = api_address
self.tls_cert = tls_cert
self.tls_key = tls_key
self.start_time = start_time
self.stop_time = stop_time
if self.status == JobStatus.RUNNING:
self.last_heartbeat = timestamp()
else:
self.last_heartbeat = None
self.worker_start_failure_count = 0
self.added_to_proxies = False
self.workers = {}
self.ready = Flag()
if self.status >= JobStatus.RUNNING:
self.ready.set()
self.shutdown = Flag()
if self.status >= JobStatus.STOPPED:
self.shutdown.set()
_status_map = {
(JobStatus.CREATED, JobStatus.RUNNING): models.ClusterStatus.PENDING,
(JobStatus.CREATED, JobStatus.CLOSING): models.ClusterStatus.STOPPING,
(JobStatus.CREATED, JobStatus.STOPPED): models.ClusterStatus.STOPPING,
(JobStatus.CREATED, JobStatus.FAILED): models.ClusterStatus.STOPPING,
(JobStatus.SUBMITTED, JobStatus.RUNNING): models.ClusterStatus.PENDING,
(JobStatus.SUBMITTED, JobStatus.CLOSING): models.ClusterStatus.STOPPING,
(JobStatus.SUBMITTED, JobStatus.STOPPED): models.ClusterStatus.STOPPING,
(JobStatus.SUBMITTED, JobStatus.FAILED): models.ClusterStatus.STOPPING,
(JobStatus.RUNNING, JobStatus.RUNNING): models.ClusterStatus.RUNNING,
(JobStatus.RUNNING, JobStatus.CLOSING): models.ClusterStatus.STOPPING,
(JobStatus.RUNNING, JobStatus.STOPPED): models.ClusterStatus.STOPPING,
(JobStatus.RUNNING, JobStatus.FAILED): models.ClusterStatus.STOPPING,
(JobStatus.CLOSING, JobStatus.STOPPED): models.ClusterStatus.STOPPING,
(JobStatus.CLOSING, JobStatus.FAILED): models.ClusterStatus.STOPPING,
(JobStatus.STOPPED, JobStatus.STOPPED): models.ClusterStatus.STOPPED,
(JobStatus.FAILED, JobStatus.FAILED): models.ClusterStatus.FAILED,
}
def active_workers(self):
return [w for w in self.workers.values() if w.is_active()]
def is_active(self):
return self.target < JobStatus.STOPPED
def all_workers_at_least(self, status):
return all(w.status >= status for w in self.workers.values())
@property
def model_status(self):
return self._status_map[self.status, self.target]
def to_model(self):
return models.Cluster(
name=self.name,
username=self.username,
token=self.token,
options=self.options,
config=self.config,
status=self.model_status,
scheduler_address=self.scheduler_address,
dashboard_address=self.dashboard_address,
api_address=self.api_address,
tls_cert=self.tls_cert,
tls_key=self.tls_key,
start_time=self.start_time,
stop_time=self.stop_time,
)
class Worker:
"""Information on a worker.
Not all attributes on this object are publicly accessible. When writing a
backend, you may access the following attributes:
Attributes
----------
name : str
The worker name.
cluster : Cluster
The cluster associated with this worker.
state : dict
Any worker state, as yielded from ``do_start_worker``.
"""
def __init__(
self,
id=None,
name=None,
cluster=None,
status=None,
target=None,
state=None,
start_time=None,
stop_time=None,
close_expected=False,
):
self.id = id
self.name = name
self.cluster = cluster
self.status = status
self.target = target
self.state = state
self.start_time = start_time
self.stop_time = stop_time
self.close_expected = close_expected
def is_active(self):
return self.target < JobStatus.STOPPED
metadata = sa.MetaData()
clusters = sa.Table(
"clusters",
metadata,
sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
sa.Column("name", sa.Unicode(255), nullable=False, unique=True),
sa.Column("username", sa.Unicode(255), nullable=False),
sa.Column("status", _IntEnum(JobStatus), nullable=False),
sa.Column("target", _IntEnum(JobStatus), nullable=False),
sa.Column("count", sa.Integer, nullable=False),
sa.Column("options", _JSON, nullable=False),
sa.Column("config", _JSON, nullable=False),
sa.Column("state", _JSON, nullable=False),
sa.Column("token", sa.BINARY(140), nullable=False, unique=True),
sa.Column("scheduler_address", sa.Unicode(255), nullable=False),
sa.Column("dashboard_address", sa.Unicode(255), nullable=False),
sa.Column("api_address", sa.Unicode(255), nullable=False),
sa.Column("tls_credentials", sa.LargeBinary, nullable=False),
sa.Column("start_time", sa.Integer, nullable=False),
sa.Column("stop_time", sa.Integer, nullable=True),
)
workers = sa.Table(
"workers",
metadata,
sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
sa.Column("name", sa.Unicode(255), nullable=False),
sa.Column(
"cluster_id", sa.ForeignKey("clusters.id", ondelete="CASCADE"), nullable=False
),
sa.Column("status", _IntEnum(JobStatus), nullable=False),
sa.Column("target", _IntEnum(JobStatus), nullable=False),
sa.Column("state", _JSON, nullable=False),
sa.Column("start_time", sa.Integer, nullable=False),
sa.Column("stop_time", sa.Integer, nullable=True),
sa.Column("close_expected", sa.Integer, nullable=False),
)
class DataManager:
"""Holds the internal state for a single Dask Gateway.
Keeps the memory representation in-sync with the database.
"""
def __init__(self, url="sqlite:///:memory:", encrypt_keys=(), **kwargs):
if url.startswith("sqlite"):
kwargs["connect_args"] = {"check_same_thread": False}
if _is_in_memory_db(url):
kwargs["poolclass"] = sa.pool.StaticPool
self.fernet = None
else:
self.fernet = MultiFernet([Fernet(key) for key in encrypt_keys])
engine = sa.create_engine(url, **kwargs)
if url.startswith("sqlite"):
# Register PRAGMA foreigh_keys=on for sqlite
@sa.event.listens_for(engine, "connect")
def connect(dbapi_con, con_record):
cursor = dbapi_con.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
metadata.create_all(engine)
self.db = engine
self.username_to_clusters = defaultdict(dict)
self.name_to_cluster = {}
self.id_to_cluster = {}
# Load all existing clusters into memory
with self.db.begin() as connection:
for c in connection.execute(clusters.select()):
tls_cert, tls_key = self.decode_tls_credentials(c.tls_credentials)
token = self.decode_token(c.token)
cluster = Cluster(
id=c.id,
name=c.name,
username=c.username,
token=token,
options=c.options,
config=FrozenAttrDict(c.config),
status=c.status,
target=c.target,
count=c.count,
state=c.state,
scheduler_address=c.scheduler_address,
dashboard_address=c.dashboard_address,
api_address=c.api_address,
tls_cert=tls_cert,
tls_key=tls_key,
start_time=c.start_time,
stop_time=c.stop_time,
)
self.username_to_clusters[cluster.username][cluster.name] = cluster
self.id_to_cluster[cluster.id] = cluster
self.name_to_cluster[cluster.name] = cluster
# Next load all existing workers into memory
for w in connection.execute(workers.select()):
cluster = self.id_to_cluster[w.cluster_id]
worker = Worker(
id=w.id,
name=w.name,
status=w.status,
target=w.target,
cluster=cluster,
state=w.state,
start_time=w.start_time,
stop_time=w.stop_time,
close_expected=w.close_expected,
)
cluster.workers[worker.name] = worker
def cleanup_expired(self, max_age_in_seconds):
cutoff = timestamp() - max_age_in_seconds * 1000
with self.db.begin() as conn:
to_delete = conn.execute(
sa.select(clusters.c.id).where(clusters.c.stop_time < cutoff)
).fetchall()
if to_delete:
to_delete = [i for i, in to_delete]
conn.execute(
clusters.delete().where(clusters.c.id == sa.bindparam("id")),
[{"id": i} for i in to_delete],
)
for i in to_delete:
cluster = self.id_to_cluster.pop(i)
self.name_to_cluster.pop(cluster.name, None)
user_clusters = self.username_to_clusters[cluster.username]
user_clusters.pop(cluster.name)
if not user_clusters:
self.username_to_clusters.pop(cluster.username)
return len(to_delete)
def encrypt(self, b):
"""Encrypt bytes ``b``. If encryption is disabled this is a no-op"""
return b if self.fernet is None else self.fernet.encrypt(b)
def decrypt(self, b):
"""Decrypt bytes ``b``. If encryption is disabled this is a no-op"""
return b if self.fernet is None else self.fernet.decrypt(b)
def encode_tls_credentials(self, tls_cert, tls_key):
return self.encrypt(b";".join((tls_cert, tls_key)))
def decode_tls_credentials(self, data):
return self.decrypt(data).split(b";")
def encode_token(self, token):
return self.encrypt(token.encode("utf8"))
def decode_token(self, data):
return self.decrypt(data).decode()
def get_cluster(self, cluster_name):
return self.name_to_cluster.get(cluster_name)
def list_clusters(self, username=None, statuses=None):
if statuses is None:
select = lambda x: x.is_active()
else:
statuses = set(statuses)
select = lambda x: x.model_status in statuses
if username is None:
return [
cluster for cluster in self.name_to_cluster.values() if select(cluster)
]
else:
clusters = self.username_to_clusters.get(username)
if clusters is None:
return []
return [cluster for cluster in clusters.values() if select(cluster)]
def active_clusters(self):
for cluster in self.name_to_cluster.values():
if cluster.is_active():
yield cluster
def create_cluster(self, username, options, config):
"""Create a new cluster for a user"""
cluster_name = uuid.uuid4().hex
token = uuid.uuid4().hex
tls_cert, tls_key = new_keypair(cluster_name)
# Encode the tls credentials for storing in the database
tls_credentials = self.encode_tls_credentials(tls_cert, tls_key)
enc_token = self.encode_token(token)
common = {
"name": cluster_name,
"username": username,
"options": options,
"status": JobStatus.CREATED,
"target": JobStatus.RUNNING,
"count": 0,
"state": {},
"scheduler_address": "",
"dashboard_address": "",
"api_address": "",
"start_time": timestamp(),
}
with self.db.begin() as conn:
res = conn.execute(
clusters.insert().values(
tls_credentials=tls_credentials,
token=enc_token,
config=config,
**common,
)
)
cluster = Cluster(
id=res.inserted_primary_key[0],
token=token,
tls_cert=tls_cert,
tls_key=tls_key,
config=FrozenAttrDict(config),
**common,
)
self.id_to_cluster[cluster.id] = cluster
self.name_to_cluster[cluster_name] = cluster
self.username_to_clusters[username][cluster_name] = cluster
return cluster
def create_worker(self, cluster):
"""Create a new worker for a cluster"""
worker_name = uuid.uuid4().hex
common = {
"name": worker_name,
"status": JobStatus.CREATED,
"target": JobStatus.RUNNING,
"state": {},
"start_time": timestamp(),
"close_expected": False,
}
with self.db.begin() as conn:
res = conn.execute(workers.insert().values(cluster_id=cluster.id, **common))
worker = Worker(id=res.inserted_primary_key[0], cluster=cluster, **common)
cluster.workers[worker.name] = worker
return worker
def update_cluster(self, cluster, **kwargs):
"""Update a cluster's state"""
with self.db.begin() as conn:
conn.execute(
clusters.update().where(clusters.c.id == cluster.id).values(**kwargs)
)
for k, v in kwargs.items():
setattr(cluster, k, v)
def update_clusters(self, updates):
"""Update multiple clusters' states"""
if not updates:
return
with self.db.begin() as conn:
conn.execute(
clusters.update().where(clusters.c.id == sa.bindparam("_id")),
[{"_id": c.id, **u} for c, u in updates],
)
for c, u in updates:
for k, v in u.items():
setattr(c, k, v)
def update_worker(self, worker, **kwargs):
"""Update a worker's state"""
with self.db.begin() as conn:
conn.execute(
workers.update().where(workers.c.id == worker.id).values(**kwargs)
)
for k, v in kwargs.items():
setattr(worker, k, v)
def update_workers(self, updates):
"""Update multiple workers' states"""
if not updates:
return
with self.db.begin() as conn:
conn.execute(
workers.update().where(workers.c.id == sa.bindparam("_id")),
[{"_id": w.id, **u} for w, u in updates],
)
for w, u in updates:
for k, v in u.items():
setattr(w, k, v)
class DBBackendBase(Backend):
"""A base class for defining backends that rely on a database for managing state.
Subclasses should define the following methods:
- ``do_setup``
- ``do_cleanup``
- ``do_start_cluster``
- ``do_stop_cluster``
- ``do_check_clusters``
- ``do_start_worker``
- ``do_stop_worker``
- ``do_check_workers``
"""
db_url = Unicode(
"sqlite:///:memory:",
help="""
The URL for the database. Default is in-memory only.
If not in-memory, ``db_encrypt_keys`` must also be set.
""",
config=True,
)
db_encrypt_keys = List(
help="""
A list of keys to use to encrypt private data in the database. Can also
be set by the environment variable ``DASK_GATEWAY_ENCRYPT_KEYS``, where
the value is a ``;`` delimited string of encryption keys.
Each key should be a base64-encoded 32 byte value, and should be
cryptographically random. Lacking other options, openssl can be used to
generate a single key via:
.. code-block:: shell
$ openssl rand -base64 32
A single key is valid, multiple keys can be used to support key rotation.
""",
config=True,
)
@default("db_encrypt_keys")
def _db_encrypt_keys_default(self):
keys = [
k.strip()
for k in os.environb.get(b"DASK_GATEWAY_ENCRYPT_KEYS", b"").split(b";")
if k.strip()
]
return self._db_encrypt_keys_validate({"value": keys})
@validate("db_encrypt_keys")
def _db_encrypt_keys_validate(self, proposal):
if not proposal["value"] and not _is_in_memory_db(self.db_url):
raise ValueError(
"Must configure `db_encrypt_keys`/`DASK_GATEWAY_ENCRYPT_KEYS` "
"when not using an in-memory database"
)
return [_normalize_encrypt_key(k) for k in proposal["value"]]
db_debug = Bool(
False, help="If True, all database operations will be logged", config=True
)
db_cleanup_period = Float(
600,
help="""
Time (in seconds) between database cleanup tasks.
This sets how frequently old records are removed from the database.
This shouldn't be too small (to keep the overhead low), but should be
smaller than ``db_record_max_age`` (probably by an order of magnitude).
""",
config=True,
)
db_cluster_max_age = Float(
3600 * 24,
help="""
Max time (in seconds) to keep around records of completed clusters.
Every ``db_cleanup_period``, completed clusters older than
``db_cluster_max_age`` are removed from the database.
""",
config=True,
)
stop_clusters_on_shutdown = Bool(
True,
help="""
Whether to stop active clusters on gateway shutdown.
If true, all active clusters will be stopped before shutting down the
gateway. Set to False to leave active clusters running.
""",
config=True,
)
@validate("stop_clusters_on_shutdown")
def _stop_clusters_on_shutdown_validate(self, proposal):
if not proposal.value and _is_in_memory_db(self.db_url):
raise ValueError(
"When using an in-memory database, `stop_clusters_on_shutdown` "
"must be True"
)
return proposal.value
cluster_status_period = Float(
30,
help="""
Time (in seconds) between cluster status checks.
A smaller period will detect failed clusters sooner, but will use more
resources. A larger period will provide slower feedback in the presence
of failures.
""",
config=True,
)
worker_status_period = Float(
30,
help="""
Time (in seconds) between worker status checks.
A smaller period will detect failed workers sooner, but will use more
resources. A larger period will provide slower feedback in the presence
of failures.
""",
config=True,
)
cluster_heartbeat_period = Integer(
15,
help="""
Time (in seconds) between cluster heartbeats to the gateway.
A smaller period will detect failed workers sooner, but will use more
resources. A larger period will provide slower feedback in the presence
of failures.
""",
config=True,
)
cluster_heartbeat_timeout = Float(
help="""
Timeout (in seconds) before killing a dask cluster that's failed to heartbeat.
This should be greater than ``cluster_heartbeat_period``. Defaults to
``2 * cluster_heartbeat_period``.
""",
config=True,
)
@default("cluster_heartbeat_timeout")
def _default_cluster_heartbeat_timeout(self):
return self.cluster_heartbeat_period * 2
cluster_start_timeout = Float(
60,
help="""
Timeout (in seconds) before giving up on a starting dask cluster.
""",
config=True,
)
worker_start_timeout = Float(
60,
help="""
Timeout (in seconds) before giving up on a starting dask worker.
""",
config=True,
)
check_timeouts_period = Float(
help="""
Time (in seconds) between timeout checks.
This shouldn't be too small (to keep the overhead low), but should be
smaller than ``cluster_heartbeat_timeout``, ``cluster_start_timeout``,
and ``worker_start_timeout``.
""",
config=True,
)
@default("check_timeouts_period")
def _default_check_timeouts_period(self):
min_timeout = min(
self.cluster_heartbeat_timeout,
self.cluster_start_timeout,
self.worker_start_timeout,
)
return min(20, min_timeout / 2)
worker_start_failure_limit = Integer(
3,
help="""
A limit on the number of failed attempts to start a worker before the
cluster is marked as failed.
Every worker that fails to start (timeouts exempt) increments a
counter. The counter is reset if a worker successfully starts. If the
counter ever exceeds this limit, the cluster is marked as failed and is
shutdown.
""",
config=True,
)
parallelism = Integer(
20,
help="""
Number of handlers to use for starting/stopping clusters.
""",
config=True,
)
backoff_base_delay = Float(
0.1,
help="""
Base delay (in seconds) for backoff when retrying after failures.
If an operation fails, it is retried after a backoff computed as:
```
min(backoff_max_delay, backoff_base_delay * 2 ** num_failures)
```
""",
config=True,
)
backoff_max_delay = Float(
300,
help="""
Max delay (in seconds) for backoff policy when retrying after failures.
""",
config=True,
)
api_url = Unicode(
help="""
The address that internal components (e.g. dask clusters)
will use when contacting the gateway.
Defaults to `{proxy_address}/{prefix}/api`, set manually if a different
address should be used.
""",
config=True,
)
@default("api_url")
def _api_url_default(self):
proxy = self.proxy
scheme = "https" if proxy.tls_cert else "http"
address = normalize_address(proxy.address, resolve_host=True)
return f"{scheme}://{address}{proxy.prefix}/api"
async def setup(self, app):
await super().setup(app)
# Setup reconcilation queues
self.queue = WorkQueue(
backoff=Backoff(
base_delay=self.backoff_base_delay, max_delay=self.backoff_max_delay
)
)
self.reconcilers = [
asyncio.ensure_future(self.reconciler_loop())
for _ in range(self.parallelism)
]
# Start the proxy
self.proxy = Proxy(parent=self, log=self.log)
await self.proxy.setup(app)
# Load the database
self.db = DataManager(
url=self.db_url, echo=self.db_debug, encrypt_keys=self.db_encrypt_keys
)
# Start background tasks
self.task_pool = TaskPool()
self.task_pool.spawn(self.check_timeouts_loop())
self.task_pool.spawn(self.check_clusters_loop())
self.task_pool.spawn(self.check_workers_loop())
self.task_pool.spawn(self.cleanup_db_loop())
# Load all active clusters/workers into reconcilation queues
for cluster in self.db.name_to_cluster.values():
if cluster.status < JobStatus.STOPPED:
self.queue.put(cluster)
for worker in cluster.workers.values():
if worker.status < JobStatus.STOPPED:
self.queue.put(worker)
# Further backend-specific setup
await self.do_setup()
self.log.info(
"Backend started, clusters will contact api server at %s", self.api_url
)
async def cleanup(self):
if hasattr(self, "task_pool"):
# Stop background tasks
await self.task_pool.close()
if hasattr(self, "db"):
if self.stop_clusters_on_shutdown:
# Request all active clusters be stopped
active = list(self.db.active_clusters())
if active:
self.log.info("Stopping %d active clusters...", len(active))
self.db.update_clusters(
[(c, {"target": JobStatus.FAILED}) for c in active]
)
for c in active:
self.queue.put(c)
# Wait until all clusters are shutdown
pending_shutdown = [
c
for c in self.db.name_to_cluster.values()
if c.status < JobStatus.STOPPED
]
if pending_shutdown:
await asyncio.wait(
[asyncio.ensure_future(c.shutdown) for c in pending_shutdown]
)
# Stop reconcilation queues
if hasattr(self, "reconcilers"):
self.queue.close()
await asyncio.gather(*self.reconcilers, return_exceptions=True)
await self.do_cleanup()
if hasattr(self, "proxy"):
await self.proxy.cleanup()
await super().cleanup()
async def list_clusters(self, username=None, statuses=None):
clusters = self.db.list_clusters(username=username, statuses=statuses)
return [c.to_model() for c in clusters]
async def get_cluster(self, cluster_name, wait=False):
cluster = self.db.get_cluster(cluster_name)
if cluster is None:
return None
if wait:
try:
await asyncio.wait_for(cluster.ready, 20)
except asyncio.TimeoutError:
pass
return cluster.to_model()
async def start_cluster(self, user, cluster_options):
options, config = await self.process_cluster_options(user, cluster_options)
cluster = self.db.create_cluster(user.name, options, config.to_dict())
self.log.info("Created cluster %s for user %s", cluster.name, user.name)
self.queue.put(cluster)
return cluster.name
async def stop_cluster(self, cluster_name, failed=False):
cluster = self.db.get_cluster(cluster_name)
if cluster is None:
return
if cluster.target <= JobStatus.RUNNING:
self.log.info("Stopping cluster %s", cluster.name)
target = JobStatus.FAILED if failed else JobStatus.STOPPED
self.db.update_cluster(cluster, target=target)
self.queue.put(cluster)
async def on_cluster_heartbeat(self, cluster_name, msg):
cluster = self.db.get_cluster(cluster_name)
if cluster is None or cluster.target > JobStatus.RUNNING:
return
cluster.last_heartbeat = timestamp()
if cluster.status == JobStatus.RUNNING:
cluster_update = {}
else:
cluster_update = {
"api_address": msg["api_address"],
"scheduler_address": msg["scheduler_address"],
"dashboard_address": msg["dashboard_address"],
}
count = msg["count"]
active_workers = set(msg["active_workers"])
closing_workers = set(msg["closing_workers"])
closed_workers = set(msg["closed_workers"])
self.log.info(
"Cluster %s heartbeat [count: %d, n_active: %d, n_closing: %d, n_closed: %d]",
cluster_name,
count,
len(active_workers),
len(closing_workers),
len(closed_workers),
)
max_workers = cluster.config.get("cluster_max_workers")
if max_workers is not None and count > max_workers:
# This shouldn't happen under normal operation, but could if the
# user does something malicious (or there's a bug).
self.log.info(
"Cluster %s heartbeat requested %d workers, exceeding limit of %s.",
cluster_name,
count,
max_workers,
)
count = max_workers
if count != cluster.count:
cluster_update["count"] = count
created_workers = []
submitted_workers = []
target_updates = []
newly_running = []
close_expected = []
for worker in cluster.workers.values():
if worker.status >= JobStatus.STOPPED:
continue
elif worker.name in closing_workers:
if worker.status < JobStatus.RUNNING:
newly_running.append(worker)
close_expected.append(worker)
elif worker.name in active_workers:
if worker.status < JobStatus.RUNNING:
newly_running.append(worker)
elif worker.name in closed_workers:
target = (
JobStatus.STOPPED if worker.close_expected else JobStatus.FAILED
)
target_updates.append((worker, {"target": target}))
else:
if worker.status == JobStatus.SUBMITTED: