forked from dstackai/dstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfleets.py
More file actions
1407 lines (1271 loc) · 50.8 KB
/
fleets.py
File metadata and controls
1407 lines (1271 loc) · 50.8 KB
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 uuid
from collections.abc import Callable
from datetime import datetime
from functools import wraps
from typing import List, Literal, Optional, Tuple, TypeVar, Union
from sqlalchemy import and_, exists, false, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased, joinedload, selectinload
from dstack._internal.core.backends.base.backend import Backend
from dstack._internal.core.backends.features import BACKENDS_WITH_CREATE_INSTANCE_SUPPORT
from dstack._internal.core.errors import (
ForbiddenError,
ResourceExistsError,
ServerClientError,
)
from dstack._internal.core.models.common import ApplyAction, CoreModel
from dstack._internal.core.models.envs import Env
from dstack._internal.core.models.fleets import (
ApplyFleetPlanInput,
Fleet,
FleetConfiguration,
FleetPlan,
FleetSpec,
FleetStatus,
InstanceGroupPlacement,
SSHHostParams,
SSHParams,
)
from dstack._internal.core.models.instances import (
InstanceOfferWithAvailability,
InstanceStatus,
InstanceTerminationReason,
SSHConnectionParams,
SSHKey,
)
from dstack._internal.core.models.placement import PlacementGroup
from dstack._internal.core.models.profiles import (
Profile,
SpotPolicy,
)
from dstack._internal.core.models.projects import Project
from dstack._internal.core.models.resources import ResourcesSpec
from dstack._internal.core.models.runs import (
JobProvisioningData,
Requirements,
RunStatus,
get_policy_map,
)
from dstack._internal.core.models.users import GlobalRole
from dstack._internal.core.services import validate_dstack_resource_name
from dstack._internal.core.services.diff import ModelDiff, copy_model, diff_models
from dstack._internal.server.db import get_db, is_db_postgres, is_db_sqlite, sqlite_commit
from dstack._internal.server.models import (
ExportedFleetModel,
FleetModel,
ImportModel,
InstanceModel,
JobModel,
MemberModel,
ProjectModel,
RunModel,
UserModel,
)
from dstack._internal.server.services import events
from dstack._internal.server.services import instances as instances_services
from dstack._internal.server.services import offers as offers_services
from dstack._internal.server.services.instances import (
get_instance_remote_connection_info,
list_active_remote_instances,
switch_instance_status,
)
from dstack._internal.server.services.locking import (
get_locker,
string_to_lock_id,
)
from dstack._internal.server.services.pipelines import PipelineHinterProtocol
from dstack._internal.server.services.plugins import apply_plugin_policies
from dstack._internal.server.services.projects import (
get_member,
get_member_permissions,
list_user_project_models,
project_model_to_project,
)
from dstack._internal.server.services.resources import set_resources_defaults
from dstack._internal.utils import random_names
from dstack._internal.utils.common import (
EntityID,
EntityName,
EntityNameOrID,
get_current_datetime,
)
from dstack._internal.utils.logging import get_logger
from dstack._internal.utils.ssh import pkey_from_str
logger = get_logger(__name__)
def switch_fleet_status(
session: AsyncSession,
fleet_model: FleetModel,
new_status: FleetStatus,
actor: events.AnyActor = events.SystemActor(),
):
"""
Switch fleet status.
"""
old_status = fleet_model.status
if old_status == new_status:
return
fleet_model.status = new_status
emit_fleet_status_change_event(
session=session,
fleet_model=fleet_model,
old_status=old_status,
new_status=new_status,
status_message=fleet_model.status_message,
actor=actor,
)
def emit_fleet_status_change_event(
session: AsyncSession,
fleet_model: FleetModel,
old_status: FleetStatus,
new_status: FleetStatus,
status_message: Optional[str],
actor: events.AnyActor = events.SystemActor(),
) -> None:
if old_status == new_status:
return
msg = get_fleet_status_change_message(
old_status=old_status,
new_status=new_status,
status_message=status_message,
)
events.emit(session, msg, actor=actor, targets=[events.Target.from_model(fleet_model)])
def get_fleet_status_change_message(
old_status: FleetStatus,
new_status: FleetStatus,
status_message: Optional[str],
) -> str:
msg = f"Fleet status changed {old_status.upper()} -> {new_status.upper()}"
if status_message is not None:
msg += f" ({status_message})"
return msg
async def list_projects_with_no_active_fleets(
session: AsyncSession,
user: UserModel,
) -> List[Project]:
"""
Returns all projects where the user is a member that have no active fleets,
neither owned nor imported.
Active fleets are those with `deleted == False`. Projects with only deleted fleets
(or no fleets) are included. Deleted projects are excluded.
Applies to all users (both regular users and admins require membership).
"""
active_fleet_alias = aliased(FleetModel)
member_alias = aliased(MemberModel)
query = (
select(ProjectModel)
.join(
member_alias,
and_(
member_alias.project_id == ProjectModel.id,
member_alias.user_id == user.id,
),
)
.outerjoin(
active_fleet_alias,
and_(
or_(
active_fleet_alias.project_id == ProjectModel.id,
exists().where(
ImportModel.project_id == ProjectModel.id,
ImportModel.export_id == ExportedFleetModel.export_id,
ExportedFleetModel.fleet_id == active_fleet_alias.id,
),
),
active_fleet_alias.deleted == False,
),
)
.where(
ProjectModel.deleted == False,
active_fleet_alias.id.is_(None),
)
.order_by(ProjectModel.created_at)
)
res = await session.execute(query)
project_models = list(res.scalars().unique().all())
return [
project_model_to_project(p, include_backends=False, include_members=False)
for p in project_models
]
async def list_fleets(
session: AsyncSession,
user: UserModel,
project_name: Optional[str],
only_active: bool,
include_imported: bool,
prev_created_at: Optional[datetime],
prev_id: Optional[uuid.UUID],
limit: int,
ascending: bool,
) -> List[Fleet]:
projects = await list_user_project_models(
session=session,
user=user,
only_names=True,
)
if project_name is not None:
projects = [p for p in projects if p.name == project_name]
fleet_models = await list_projects_fleet_models(
session=session,
projects=projects,
only_active=only_active,
include_imported=include_imported,
prev_created_at=prev_created_at,
prev_id=prev_id,
limit=limit,
ascending=ascending,
)
return [fleet_model_to_fleet(v) for v in fleet_models]
async def list_projects_fleet_models(
session: AsyncSession,
projects: List[ProjectModel],
only_active: bool,
include_imported: bool,
prev_created_at: Optional[datetime],
prev_id: Optional[uuid.UUID],
limit: int,
ascending: bool,
) -> List[FleetModel]:
filters = []
project_ids = {p.id for p in projects}
is_fleet_imported_subquery = exists().where(
ImportModel.project_id.in_(project_ids),
ImportModel.export_id == ExportedFleetModel.export_id,
ExportedFleetModel.fleet_id == FleetModel.id,
)
filters.append(
or_(
FleetModel.project_id.in_(project_ids),
is_fleet_imported_subquery if include_imported else false(),
)
)
if only_active:
filters.append(FleetModel.deleted == False)
if prev_created_at is not None:
if ascending:
if prev_id is None:
filters.append(FleetModel.created_at > prev_created_at)
else:
filters.append(
or_(
FleetModel.created_at > prev_created_at,
and_(FleetModel.created_at == prev_created_at, FleetModel.id < prev_id),
)
)
else:
if prev_id is None:
filters.append(FleetModel.created_at < prev_created_at)
else:
filters.append(
or_(
FleetModel.created_at < prev_created_at,
and_(FleetModel.created_at == prev_created_at, FleetModel.id > prev_id),
)
)
order_by = (FleetModel.created_at.desc(), FleetModel.id)
if ascending:
order_by = (FleetModel.created_at.asc(), FleetModel.id.desc())
res = await session.execute(
select(FleetModel)
.where(*filters)
.order_by(*order_by)
.limit(limit)
.options(
joinedload(FleetModel.project).load_only(ProjectModel.name),
selectinload(FleetModel.instances.and_(InstanceModel.deleted == False)),
)
)
fleet_models = list(res.unique().scalars().all())
return fleet_models
async def list_project_fleets(
session: AsyncSession,
project: ProjectModel,
names: Optional[List[str]] = None,
include_imported: bool = False,
) -> List[Fleet]:
fleet_models = await list_project_fleet_models(
session=session, project=project, names=names, include_imported=include_imported
)
return [fleet_model_to_fleet(v) for v in fleet_models]
async def list_project_fleet_models(
session: AsyncSession,
project: ProjectModel,
names: Optional[List[str]] = None,
include_imported: bool = False,
include_deleted: bool = False,
include_instances: bool = True,
) -> List[FleetModel]:
filters = []
is_fleet_imported_subquery = exists().where(
ImportModel.project_id == project.id,
ImportModel.export_id == ExportedFleetModel.export_id,
ExportedFleetModel.fleet_id == FleetModel.id,
)
filters.append(
or_(
FleetModel.project_id == project.id,
is_fleet_imported_subquery if include_imported else false(),
)
)
if names is not None:
filters.append(FleetModel.name.in_(names))
if not include_deleted:
filters.append(FleetModel.deleted == False)
options = [joinedload(FleetModel.project).load_only(ProjectModel.name)]
if include_instances:
options.append(selectinload(FleetModel.instances.and_(InstanceModel.deleted == False)))
res = await session.execute(select(FleetModel).where(*filters).options(*options))
return list(res.unique().scalars().all())
async def get_fleet(
session: AsyncSession,
project: ProjectModel,
name_or_id: EntityNameOrID,
include_sensitive: bool = False,
) -> Optional[Fleet]:
if isinstance(name_or_id, EntityID):
fleet_model = await get_project_fleet_model_by_id(
session=session, project=project, fleet_id=name_or_id.id
)
else:
fleet_model = await get_project_fleet_model_by_name(
session=session, project=project, name=name_or_id.name
)
if fleet_model is None:
return None
return fleet_model_to_fleet(fleet_model, include_sensitive=include_sensitive)
async def get_project_fleet_model_by_id(
session: AsyncSession,
project: ProjectModel,
fleet_id: uuid.UUID,
) -> Optional[FleetModel]:
filters = [
FleetModel.id == fleet_id,
FleetModel.project_id == project.id,
]
res = await session.execute(
select(FleetModel)
.where(*filters)
.options(
joinedload(FleetModel.instances.and_(InstanceModel.deleted == False)),
joinedload(FleetModel.project).load_only(ProjectModel.name),
)
)
return res.unique().scalar_one_or_none()
async def get_project_fleet_model_by_name(
session: AsyncSession,
project: ProjectModel,
name: str,
include_deleted: bool = False,
) -> Optional[FleetModel]:
filters = [
FleetModel.name == name,
FleetModel.project_id == project.id,
]
if not include_deleted:
filters.append(FleetModel.deleted == False)
res = await session.execute(
select(FleetModel)
.where(*filters)
.options(
joinedload(FleetModel.instances.and_(InstanceModel.deleted == False)),
joinedload(FleetModel.project).load_only(ProjectModel.name),
)
)
return res.unique().scalar_one_or_none()
async def get_plan(
session: AsyncSession,
project: ProjectModel,
user: UserModel,
spec: FleetSpec,
) -> FleetPlan:
# Spec must be copied by parsing to calculate merged_profile
effective_spec = copy_model(spec)
effective_spec = await apply_plugin_policies(
user=user.name,
project=project.name,
spec=effective_spec,
)
# Spec must be copied by parsing to calculate merged_profile
effective_spec = copy_model(effective_spec)
_validate_fleet_spec_and_set_defaults(effective_spec)
action = ApplyAction.CREATE
current_fleet: Optional[Fleet] = None
current_fleet_id: Optional[uuid.UUID] = None
if effective_spec.configuration.name is not None:
current_fleet = await get_fleet(
session=session,
project=project,
name_or_id=EntityName(effective_spec.configuration.name),
include_sensitive=True,
)
if current_fleet is not None:
_set_fleet_spec_defaults(current_fleet.spec)
if _can_update_fleet_spec(current_fleet.spec, effective_spec):
action = ApplyAction.UPDATE
current_fleet_id = current_fleet.id
await _check_ssh_hosts_not_yet_added(session, effective_spec, current_fleet_id)
offers = []
if effective_spec.configuration.ssh_config is None:
offers_with_backends = await get_create_instance_offers(
project=project,
profile=effective_spec.merged_profile,
requirements=get_fleet_requirements(effective_spec),
fleet_spec=effective_spec,
blocks=effective_spec.configuration.blocks,
)
offers = [offer for _, offer in offers_with_backends]
_remove_fleet_spec_sensitive_info(effective_spec)
if current_fleet is not None:
_remove_fleet_spec_sensitive_info(current_fleet.spec)
plan = FleetPlan(
project_name=project.name,
user=user.name,
spec=spec,
effective_spec=effective_spec,
current_resource=current_fleet,
offers=offers[:50],
total_offers=len(offers),
max_offer_price=max((offer.price for offer in offers), default=None),
action=action,
)
return plan
async def get_create_instance_offers(
project: ProjectModel,
profile: Profile,
requirements: Requirements,
placement_group: Optional[PlacementGroup] = None,
fleet_spec: Optional[FleetSpec] = None,
fleet_model: Optional[FleetModel] = None,
blocks: Union[int, Literal["auto"]] = 1,
exclude_not_available: bool = False,
master_job_provisioning_data: Optional[JobProvisioningData] = None,
infer_master_job_provisioning_data_from_fleet_instances: bool = True,
) -> List[Tuple[Backend, InstanceOfferWithAvailability]]:
multinode = False
if fleet_spec is not None:
multinode = fleet_spec.configuration.placement == InstanceGroupPlacement.CLUSTER
if fleet_model is not None:
fleet_spec_from_model = get_fleet_spec(fleet_model)
multinode = fleet_spec_from_model.configuration.placement == InstanceGroupPlacement.CLUSTER
# The caller may override the current cluster master explicitly instead
# of inferring placement restrictions from the loaded fleet instances.
if (
master_job_provisioning_data is None
and infer_master_job_provisioning_data_from_fleet_instances
):
for instance in fleet_model.instances:
jpd = instances_services.get_instance_provisioning_data(instance)
if jpd is not None:
master_job_provisioning_data = jpd
break
offers = await offers_services.get_offers_by_requirements(
project=project,
profile=profile,
requirements=requirements,
exclude_not_available=exclude_not_available,
multinode=multinode,
master_job_provisioning_data=master_job_provisioning_data,
placement_group=placement_group,
blocks=blocks,
)
offers = [
(backend, offer)
for backend, offer in offers
if offer.backend in BACKENDS_WITH_CREATE_INSTANCE_SUPPORT
]
return offers
async def apply_plan(
session: AsyncSession,
user: UserModel,
project: ProjectModel,
plan: ApplyFleetPlanInput,
force: bool,
pipeline_hinter: PipelineHinterProtocol,
) -> Fleet:
spec = await apply_plugin_policies(
user=user.name,
project=project.name,
spec=plan.spec,
)
# Spec must be copied by parsing to calculate merged_profile
spec = copy_model(spec)
_validate_fleet_spec_and_set_defaults(spec)
if spec.configuration.ssh_config is not None:
_check_can_manage_ssh_fleets(user=user, project=project)
configuration = spec.configuration
if configuration.name is None:
return await _create_fleet(
session=session,
project=project,
user=user,
spec=spec,
pipeline_hinter=pipeline_hinter,
)
fleet_model = await get_project_fleet_model_by_name(
session=session,
project=project,
name=configuration.name,
)
if fleet_model is None:
return await _create_fleet(
session=session,
project=project,
user=user,
spec=spec,
pipeline_hinter=pipeline_hinter,
)
instances_ids = sorted(i.id for i in fleet_model.instances if not i.deleted)
await session.commit()
async with (
get_locker(get_db().dialect_name).lock_ctx(FleetModel.__tablename__, [fleet_model.id]),
get_locker(get_db().dialect_name).lock_ctx(InstanceModel.__tablename__, instances_ids),
):
# Refetch after lock
# TODO: Lock instances with FOR UPDATE?
# We do not respect InstanceModel.lock_* fields here because FleetPipeline does not update SSH instances.
# TODO: Respect InstanceModel.lock_* fields if FleetPipeline and apply update the same instances.
res = await session.execute(
select(FleetModel)
.where(
FleetModel.project_id == project.id,
FleetModel.id == fleet_model.id,
FleetModel.deleted == False,
)
.options(
selectinload(FleetModel.instances)
.joinedload(InstanceModel.jobs)
.load_only(JobModel.id)
)
# `is_fleet_in_use()` only needs active run presence/status.
.options(
selectinload(
FleetModel.runs.and_(RunModel.status.not_in(RunStatus.finished_statuses()))
).load_only(RunModel.id, RunModel.status)
)
.execution_options(populate_existing=True)
.order_by(FleetModel.id) # take locks in order
.with_for_update(key_share=True)
)
fleet_model = res.scalars().unique().one_or_none()
if fleet_model is not None:
if fleet_model.lock_expires_at is not None:
# TODO: Make the endpoint fully async so we don't need to lock and error:
# put the request in queue and process in the background.
raise ServerClientError(
"Failed to update fleet: fleet is being processed currently. Try again later."
)
return await _update_fleet(
session=session,
user=user,
project=project,
spec=spec,
current_resource=plan.current_resource,
force=force,
fleet_model=fleet_model,
)
return await _create_fleet(
session=session,
project=project,
user=user,
spec=spec,
pipeline_hinter=pipeline_hinter,
)
async def create_fleet(
session: AsyncSession,
project: ProjectModel,
user: UserModel,
spec: FleetSpec,
pipeline_hinter: PipelineHinterProtocol,
) -> Fleet:
spec = await apply_plugin_policies(
user=user.name,
project=project.name,
spec=spec,
)
# Spec must be copied by parsing to calculate merged_profile
spec = copy_model(spec)
_validate_fleet_spec_and_set_defaults(spec)
if spec.configuration.ssh_config is not None:
_check_can_manage_ssh_fleets(user=user, project=project)
return await _create_fleet(
session=session, project=project, user=user, spec=spec, pipeline_hinter=pipeline_hinter
)
def create_fleet_instance_model(
session: AsyncSession,
project: ProjectModel,
username: str,
spec: FleetSpec,
instance_num: int,
instance_id: Optional[uuid.UUID] = None,
) -> InstanceModel:
profile = spec.merged_profile
requirements = get_fleet_requirements(spec)
instance_model = instances_services.create_instance_model(
session=session,
project=project,
username=username,
profile=profile,
requirements=requirements,
instance_name=f"{spec.configuration.name}-{instance_num}",
instance_num=instance_num,
instance_id=instance_id,
reservation=spec.merged_profile.reservation,
blocks=spec.configuration.blocks,
tags=spec.configuration.tags,
)
return instance_model
async def create_fleet_ssh_instance_model(
project: ProjectModel,
spec: FleetSpec,
ssh_params: SSHParams,
env: Env,
instance_num: int,
host: Union[SSHHostParams, str],
) -> InstanceModel:
if isinstance(host, str):
hostname = host
ssh_user = ssh_params.user
ssh_key = ssh_params.ssh_key
port = ssh_params.port
proxy_jump = ssh_params.proxy_jump
internal_ip = None
blocks = spec.configuration.blocks
else:
hostname = host.hostname
ssh_user = host.user or ssh_params.user
ssh_key = host.ssh_key or ssh_params.ssh_key
port = host.port or ssh_params.port
proxy_jump = host.proxy_jump or ssh_params.proxy_jump
internal_ip = host.internal_ip
blocks = host.blocks
if ssh_user is None or ssh_key is None:
# This should not be reachable but checked by fleet spec validation
raise ServerClientError("ssh key or user not specified")
if proxy_jump is not None:
assert proxy_jump.ssh_key is not None
ssh_proxy = SSHConnectionParams(
hostname=proxy_jump.hostname,
port=proxy_jump.port or 22,
username=proxy_jump.user,
)
ssh_proxy_keys = [proxy_jump.ssh_key]
else:
ssh_proxy = None
ssh_proxy_keys = None
instance_model = await instances_services.create_ssh_instance_model(
project=project,
instance_name=f"{spec.configuration.name}-{instance_num}",
instance_num=instance_num,
region="remote",
host=hostname,
ssh_user=ssh_user,
ssh_keys=[ssh_key],
ssh_proxy=ssh_proxy,
ssh_proxy_keys=ssh_proxy_keys,
env=env,
internal_ip=internal_ip,
instance_network=ssh_params.network,
port=port or 22,
blocks=blocks,
)
return instance_model
async def delete_fleets(
session: AsyncSession,
project: ProjectModel,
user: UserModel,
names: List[str],
instance_nums: Optional[List[int]] = None,
):
res = await session.execute(
select(FleetModel.id)
.where(
FleetModel.project_id == project.id,
FleetModel.name.in_(names),
FleetModel.deleted == False,
)
.order_by(FleetModel.id)
)
fleets_ids = list(res.scalars().unique().all())
stmt = (
select(InstanceModel.id)
.where(
InstanceModel.fleet_id.in_(fleets_ids),
InstanceModel.deleted == False,
)
.order_by(InstanceModel.id)
)
if instance_nums is not None:
stmt = stmt.where(InstanceModel.instance_num.in_(instance_nums))
res = await session.execute(stmt)
instances_ids = list(res.scalars().unique().all())
await sqlite_commit(session)
async with (
get_locker(get_db().dialect_name).lock_ctx(FleetModel.__tablename__, fleets_ids),
get_locker(get_db().dialect_name).lock_ctx(InstanceModel.__tablename__, instances_ids),
):
# Retry locking fleets to increase lock acquisition chances.
# This hack is needed until requests are queued.
fleet_models = []
for i in range(10):
res = await session.execute(
select(FleetModel)
.where(
FleetModel.project_id == project.id,
FleetModel.id.in_(fleets_ids),
FleetModel.deleted == False,
FleetModel.lock_expires_at.is_(None),
)
.options(
selectinload(FleetModel.instances.and_(InstanceModel.id.in_(instances_ids)))
.selectinload(InstanceModel.jobs)
.load_only(JobModel.id)
)
.options(
selectinload(
FleetModel.runs.and_(RunModel.status.not_in(RunStatus.finished_statuses()))
).load_only(RunModel.status)
)
.order_by(FleetModel.id) # take locks in order
.with_for_update(key_share=True, of=FleetModel)
.execution_options(populate_existing=True)
)
fleet_models = res.scalars().unique().all()
if len(fleet_models) == len(fleets_ids):
break
await asyncio.sleep(0.5)
if len(fleet_models) != len(fleets_ids):
# TODO: Make the endpoint fully async so we don't need to lock and error.
msg = (
"Failed to delete fleets: fleets are being processed currently. Try again later."
if instance_nums is None
else "Failed to delete fleet instances: fleets are being processed currently. Try again later."
)
raise ServerClientError(msg)
# Retry locking instances to increase lock acquisition chances.
# This hack is needed until requests are queued.
instances_left_to_lock = set(instances_ids)
for i in range(10):
res = await session.execute(
select(InstanceModel.id)
.where(
InstanceModel.id.in_(instances_left_to_lock),
InstanceModel.deleted == False,
InstanceModel.lock_expires_at.is_(None),
)
.order_by(InstanceModel.id) # take locks in order
.with_for_update(key_share=True, of=InstanceModel)
.execution_options(populate_existing=True)
)
instances_left_to_lock.difference_update(res.scalars().unique().all())
if len(instances_left_to_lock) == 0:
break
await asyncio.sleep(0.5)
if len(instances_left_to_lock) > 0:
msg = (
"Failed to delete fleets: fleet instances are being processed currently. Try again later."
if instance_nums is None
else "Failed to delete fleet instances: fleet instances are being processed currently. Try again later."
)
raise ServerClientError(msg)
for fleet_model in fleet_models:
fleet_spec = get_fleet_spec(fleet_model)
if fleet_spec.configuration.ssh_config is not None:
_check_can_manage_ssh_fleets(user=user, project=project)
if instance_nums is None:
logger.info("Deleting fleets: %s", [f.name for f in fleet_models])
else:
logger.info(
"Deleting fleets %s instances %s", [f.name for f in fleet_models], instance_nums
)
for fleet_model in fleet_models:
_terminate_fleet_instances(
session=session, fleet_model=fleet_model, instance_nums=instance_nums, actor=user
)
# TERMINATING fleets are deleted by process_fleets after instances are terminated
if instance_nums is None:
switch_fleet_status(
session,
fleet_model,
FleetStatus.TERMINATING,
actor=events.UserActor.from_user(user),
)
await session.commit()
def fleet_model_to_fleet(
fleet_model: FleetModel,
include_deleted_instances: bool = False,
include_sensitive: bool = False,
) -> Fleet:
instance_models = fleet_model.instances
if not include_deleted_instances:
instance_models = [i for i in instance_models if not i.deleted]
instances = [instances_services.instance_model_to_instance(i) for i in instance_models]
instances = sorted(instances, key=lambda i: i.instance_num)
spec = get_fleet_spec(fleet_model)
if not include_sensitive:
_remove_fleet_spec_sensitive_info(spec)
return Fleet(
id=fleet_model.id,
name=fleet_model.name,
project_name=fleet_model.project.name,
spec=spec,
created_at=fleet_model.created_at,
status=fleet_model.status,
status_message=fleet_model.status_message,
instances=instances,
)
def get_fleet_spec(fleet_model: FleetModel) -> FleetSpec:
return FleetSpec.__response__.parse_raw(fleet_model.spec)
async def generate_fleet_name(session: AsyncSession, project: ProjectModel) -> str:
res = await session.execute(
select(FleetModel.name).where(
FleetModel.project_id == project.id,
FleetModel.deleted == False,
)
)
names = set(res.scalars().all())
while True:
name = random_names.generate_name()
if name not in names:
return name
def is_fleet_in_use(fleet_model: FleetModel, instance_nums: Optional[List[int]] = None) -> bool:
instances_in_use = [i for i in fleet_model.instances if i.jobs and not i.deleted]
selected_instance_in_use = instances_in_use
if instance_nums is not None:
selected_instance_in_use = [i for i in instances_in_use if i.instance_num in instance_nums]
active_runs = [r for r in fleet_model.runs if not r.status.is_finished()]
return len(selected_instance_in_use) > 0 or len(instances_in_use) == 0 and len(active_runs) > 0
def is_fleet_empty(fleet_model: FleetModel) -> bool:
active_instances = [i for i in fleet_model.instances if not i.deleted]
return len(active_instances) == 0
def is_cloud_cluster(fleet_model: FleetModel) -> bool:
fleet_spec = get_fleet_spec(fleet_model)
return (
fleet_spec.configuration.placement == InstanceGroupPlacement.CLUSTER
and fleet_spec.configuration.ssh_config is None
)
def get_fleet_requirements(fleet_spec: FleetSpec) -> Requirements:
profile = fleet_spec.merged_profile
requirements = Requirements(
resources=fleet_spec.configuration.resources or ResourcesSpec(),
max_price=profile.max_price,
spot=get_policy_map(profile.spot_policy, default=SpotPolicy.ONDEMAND),
reservation=fleet_spec.configuration.reservation,
multinode=fleet_spec.configuration.placement == InstanceGroupPlacement.CLUSTER,
)
return requirements
def get_next_instance_num(taken_instance_nums: set[int]) -> int:
if not taken_instance_nums:
return 0
min_instance_num = min(taken_instance_nums)
if min_instance_num > 0:
return 0
instance_num = min_instance_num + 1
while True:
if instance_num not in taken_instance_nums:
return instance_num
instance_num += 1
def get_fleet_master_instance_provisioning_data(
fleet_model: FleetModel,
fleet_spec: FleetSpec,
) -> Optional[JobProvisioningData]:
if fleet_spec.configuration.placement != InstanceGroupPlacement.CLUSTER:
return None
if fleet_model.current_master_instance_id is not None:
for instance_model in fleet_model.instances:
if (
instance_model.id == fleet_model.current_master_instance_id
and not instance_model.deleted
and instance_model.job_provisioning_data is not None
):
return JobProvisioningData.__response__.parse_raw(
instance_model.job_provisioning_data
)
# TODO: Drop the legacy instance-list fallback after scheduled tasks stop
# inferring cluster masters from loaded fleet instances.
for instance_model in fleet_model.instances:
if not instance_model.deleted and instance_model.job_provisioning_data is not None:
return JobProvisioningData.__response__.parse_raw(instance_model.job_provisioning_data)
return None
def can_create_new_cloud_instance_in_fleet(fleet_model: FleetModel, fleet_spec: FleetSpec) -> bool:
if fleet_spec.configuration.ssh_config is not None:
return False
active_instances = [i for i in fleet_model.instances if i.status.is_active()]
# nodes.max is a soft limit that can be exceeded when provisioning concurrently.
# The fleet consolidation logic will remove redundant nodes eventually.
if (
fleet_spec.configuration.nodes is not None
and fleet_spec.configuration.nodes.max is not None
and len(active_instances) >= fleet_spec.configuration.nodes.max
):
return False
return True
def check_can_create_new_cloud_instance_in_fleet(fleet_model: FleetModel, fleet_spec: FleetSpec):
if not can_create_new_cloud_instance_in_fleet(fleet_model, fleet_spec):
raise ValueError("Cannot fit new cloud instance into fleet")
async def _create_fleet(
session: AsyncSession,
project: ProjectModel,
user: UserModel,
spec: FleetSpec,
pipeline_hinter: PipelineHinterProtocol,
) -> Fleet:
lock_namespace = f"fleet_names_{project.name}"
if is_db_sqlite():