-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathagent.py
More file actions
2344 lines (2159 loc) · 95.7 KB
/
agent.py
File metadata and controls
2344 lines (2159 loc) · 95.7 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
from __future__ import annotations
import asyncio
import base64
import json
import logging
import os
import re
import secrets
import shutil
import signal
import struct
import sys
from collections.abc import AsyncGenerator, Iterable, Mapping, MutableMapping, Sequence
from dataclasses import dataclass
from decimal import Decimal
from functools import partial
from http import HTTPStatus
from importlib.resources import files
from io import StringIO
from pathlib import Path
from subprocess import CalledProcessError
from subprocess import run as subprocess_run
from typing import (
TYPE_CHECKING,
Any,
Final,
cast,
override,
)
from uuid import UUID
import aiofiles
import aiohttp
import aiotools
import zmq
import zmq.asyncio
from aiodocker.docker import Docker, DockerContainer
from aiodocker.exceptions import DockerContainerError, DockerError
from aiodocker.types import PortInfo
from aiomonitor.task import preserve_termination_log
from aiotools import TaskGroup
from async_timeout import timeout
from ai.backend.agent.agent import (
ACTIVE_STATUS_SET,
AbstractAgent,
AbstractKernelCreationContext,
AgentClass,
ScanImagesResult,
)
from ai.backend.agent.config.unified import AgentUnifiedConfig, ContainerSandboxType, ScratchType
from ai.backend.agent.docker.intrinsic import (
DockerStatsStreamer,
)
from ai.backend.agent.etcd import AgentEtcdClientView
from ai.backend.agent.exception import (
ContainerCreationError,
InvalidArgumentError,
UnsupportedResource,
)
from ai.backend.agent.fs import create_scratch_filesystem, destroy_scratch_filesystem
from ai.backend.agent.kernel import AbstractKernel, KernelRegistry
from ai.backend.agent.kernel_registry.adapter import (
KernelRecoveryDataAdapter,
KernelRecoveryDataAdapterTarget,
)
from ai.backend.agent.kernel_registry.container.creator import (
ContainerBasedKernelRegistryCreatorArgs,
ContainerBasedLoaderWriterCreator,
)
from ai.backend.agent.kernel_registry.pickle.creator import (
PickleBasedKernelRegistryCreatorArgs,
PickleBasedLoaderWriterCreator,
)
from ai.backend.agent.kernel_registry.recovery.docker_recovery import (
DockerKernelRegistryRecovery,
)
from ai.backend.agent.kernel_registry.writer.types import KernelRegistrySaveMetadata
from ai.backend.agent.plugin.network import (
ContainerNetworkCapability,
ContainerNetworkInfo,
NetworkPluginContext,
)
from ai.backend.agent.proxy import DomainSocketProxy, proxy_connection
from ai.backend.agent.resources import (
AbstractComputePlugin,
ComputerContext,
KernelResourceSpec,
Mount,
known_slot_types,
)
from ai.backend.agent.scratch import create_loop_filesystem, destroy_loop_filesystem
from ai.backend.agent.types import (
AgentEventData,
Container,
KernelOwnershipData,
LifecycleEvent,
MountInfo,
Port,
VolumeInfo,
)
from ai.backend.agent.utils import (
closing_async,
container_pid_to_host_pid,
get_arch_name,
get_kernel_id_from_container,
get_safe_ulimit,
host_pid_to_container_pid,
update_nested_dict,
)
from ai.backend.common.asyncio import current_loop
from ai.backend.common.cgroup import get_cgroup_mount_point
from ai.backend.common.data.image.types import InstalledImageInfo
from ai.backend.common.docker import (
MAX_KERNELSPEC,
MIN_KERNELSPEC,
ImageRef,
KernelFeatures,
LabelName,
)
from ai.backend.common.dto.agent.response import PurgeImageResp, PurgeImagesResp
from ai.backend.common.dto.manager.rpc_request import PurgeImagesReq
from ai.backend.common.events.dispatcher import EventProducer
from ai.backend.common.events.kernel import KernelLifecycleEventReason
from ai.backend.common.exception import ImageNotAvailable, InvalidImageName, InvalidImageTag
from ai.backend.common.files import AsyncFileWriter
from ai.backend.common.json import (
dump_json,
load_json,
)
from ai.backend.common.plugin.monitor import ErrorPluginContext, StatsPluginContext
from ai.backend.common.types import (
AgentId,
AutoPullBehavior,
BinarySize,
ClusterInfo,
ClusterSSHPortMapping,
ContainerId,
ContainerStatus,
DeviceId,
DeviceName,
ImageCanonical,
ImageConfig,
ImageRegistry,
KernelCreationConfig,
KernelId,
MountPermission,
MountTypes,
ResourceGroupType,
ResourceSlot,
Sentinel,
ServicePort,
SessionId,
SlotName,
current_resource_slots,
)
from ai.backend.logging import BraceStyleAdapter
from ai.backend.logging.formatter import pretty
from .kernel import DockerKernel
from .utils import PersistentServiceContainer
if TYPE_CHECKING:
from ai.backend.common.auth import PublicKey
log = BraceStyleAdapter(logging.getLogger(__spec__.name))
eof_sentinel = Sentinel.TOKEN
LDD_GLIBC_REGEX = re.compile(r"^ldd \([^\)]+\) ([\d\.]+)$")
LDD_MUSL_REGEX = re.compile(r"^musl libc .+$")
known_glibc_distros: Final[dict[float, str]] = {
2.17: "centos7.6",
2.27: "ubuntu18.04",
2.28: "centos8.0",
2.31: "ubuntu20.04",
2.34: "centos9.0",
2.35: "ubuntu22.04",
2.39: "ubuntu24.04",
}
deeplearning_image_keys = {
"tensorflow",
"caffe",
"keras",
"torch",
"mxnet",
"theano",
}
deeplearning_sample_volume = VolumeInfo(
"deeplearning-samples",
"/home/work/samples",
"ro",
)
async def get_extra_volumes(docker: Docker, lang: str) -> list[VolumeInfo]:
avail_volumes = (await docker.volumes.list())["Volumes"] # type: ignore[no-untyped-call]
if not avail_volumes:
return []
avail_volume_names = {v["Name"] for v in avail_volumes}
# deeplearning specialization
# TODO: extract as config
volume_list = []
for k in deeplearning_image_keys:
if k in lang:
volume_list.append(deeplearning_sample_volume)
break
# Mount only actually existing volumes
mount_list = []
for vol in volume_list:
if vol.name in avail_volume_names:
mount_list.append(vol)
else:
log.info(
"skipped attaching extra volume {0} to a kernel based on image {1}",
vol.name,
lang,
)
return mount_list
def container_from_docker_container(src: DockerContainer) -> Container:
ports = []
for private_port, host_ports in src["NetworkSettings"]["Ports"].items():
private_port = int(private_port.split("/")[0])
if host_ports is None:
host_ip = "127.0.0.1"
host_port = 0
else:
host_ip = host_ports[0]["HostIp"]
host_port = int(host_ports[0]["HostPort"])
ports.append(Port(host_ip, private_port, host_port))
return Container(
id=ContainerId(src.id),
status=src["State"]["Status"],
image=src["Config"]["Image"],
labels=src["Config"]["Labels"],
ports=ports,
backend_obj=src,
)
async def _clean_scratch(
loop: asyncio.AbstractEventLoop,
scratch_type: str,
scratch_root: Path,
kernel_id: KernelId,
) -> None:
scratch_dir = scratch_root / str(kernel_id)
tmp_dir = scratch_root / f"{kernel_id}_tmp"
try:
if sys.platform.startswith("linux") and scratch_type == "memory":
await destroy_scratch_filesystem(scratch_dir)
await destroy_scratch_filesystem(tmp_dir)
await loop.run_in_executor(None, shutil.rmtree, scratch_dir)
await loop.run_in_executor(None, shutil.rmtree, tmp_dir)
elif sys.platform.startswith("linux") and scratch_type == "hostfile":
await destroy_loop_filesystem(scratch_root, kernel_id)
else:
await loop.run_in_executor(None, shutil.rmtree, scratch_dir)
except CalledProcessError:
pass
except FileNotFoundError:
pass
def _DockerError_reduce(self: DockerError) -> tuple[type, tuple[Any, ...]]:
return (
type(self),
(self.status, {"message": self.message}, *self.args),
)
def _DockerContainerError_reduce(self: DockerContainerError) -> tuple[type, tuple[Any, ...]]:
return (
type(self),
(self.status, {"message": self.message}, self.container_id, *self.args),
)
@dataclass
class DockerPurgeImageReq:
image: str
force: bool
noprune: bool
class DockerKernelCreationContext(AbstractKernelCreationContext[DockerKernel]):
scratch_dir: Path
tmp_dir: Path
config_dir: Path
work_dir: Path
container_configs: list[Mapping[str, Any]]
domain_socket_proxies: list[DomainSocketProxy]
computer_docker_args: dict[str, Any]
port_pool: set[int]
agent_sockpath: Path
resource_lock: asyncio.Lock
cluster_ssh_port_mapping: ClusterSSHPortMapping | None
gwbridge_subnet: str | None
network_plugin_ctx: NetworkPluginContext
def __init__(
self,
ownership_data: KernelOwnershipData,
event_producer: EventProducer,
kernel_image: ImageRef,
kernel_config: KernelCreationConfig,
distro: str,
local_config: AgentUnifiedConfig,
computers: Mapping[DeviceName, ComputerContext],
port_pool: set[int],
agent_sockpath: Path,
resource_lock: asyncio.Lock,
network_plugin_ctx: NetworkPluginContext,
restarting: bool = False,
cluster_ssh_port_mapping: ClusterSSHPortMapping | None = None,
gwbridge_subnet: str | None = None,
) -> None:
super().__init__(
ownership_data,
event_producer,
kernel_image,
kernel_config,
distro,
local_config,
computers,
restarting=restarting,
)
kernel_id = ownership_data.kernel_id
scratch_dir = (self.local_config.container.scratch_root / str(kernel_id)).resolve()
tmp_dir = (self.local_config.container.scratch_root / f"{kernel_id}_tmp").resolve()
self.scratch_dir = scratch_dir
self.tmp_dir = tmp_dir
self.config_dir = scratch_dir / "config"
self.work_dir = scratch_dir / "work"
self.port_pool = port_pool
self.agent_sockpath = agent_sockpath
self.resource_lock = resource_lock
self.container_configs = []
self.domain_socket_proxies = []
self.computer_docker_args = {}
self.cluster_ssh_port_mapping = cluster_ssh_port_mapping
self.gwbridge_subnet = gwbridge_subnet
self.network_plugin_ctx = network_plugin_ctx
def _kernel_resource_spec_read(self, filename: Path | str) -> KernelResourceSpec:
filepath = Path(filename)
with filepath.open() as f:
return KernelResourceSpec.read_from_file(f)
@override
async def get_extra_envs(self) -> Mapping[str, str]:
return {}
@override
async def prepare_resource_spec(self) -> tuple[KernelResourceSpec, Mapping[str, Any] | None]:
loop = current_loop()
if self.restarting:
resource_spec = await loop.run_in_executor(
None, self._kernel_resource_spec_read, self.config_dir / "resource.txt"
)
resource_opts = None
else:
slots = ResourceSlot.from_json(self.kernel_config["resource_slots"])
# Ensure that we have intrinsic slots.
if SlotName("cpu") not in slots:
raise UnsupportedResource("cpu slot is required")
if SlotName("mem") not in slots:
raise UnsupportedResource("mem slot is required")
# accept unknown slot type with zero values
# but reject if they have non-zero values.
for st, sv in slots.items():
if st not in known_slot_types and sv != Decimal(0):
raise UnsupportedResource(st)
# sanitize the slots
current_resource_slots.set(known_slot_types)
slots = slots.normalize_slots(ignore_unknown=True)
resource_spec = KernelResourceSpec(
allocations={},
slots=slots.copy(),
mounts=[],
scratch_disk_size=0, # TODO: implement (#70)
)
resource_opts = self.kernel_config.get("resource_opts", {})
return resource_spec, resource_opts
def _chown_paths_if_root(self, paths: Iterable[Path], uid: int | None, gid: int | None) -> None:
if os.geteuid() == 0: # only possible when I am root.
for p in paths:
if KernelFeatures.UID_MATCH in self.kernel_features:
valid_uid = uid if uid is not None else self.local_config.container.kernel_uid
valid_gid = gid if gid is not None else self.local_config.container.kernel_gid
else:
stat = p.stat()
valid_uid = uid if uid is not None else stat.st_uid
valid_gid = gid if gid is not None else stat.st_gid
try:
int_uid = int(valid_uid)
int_gid = int(valid_gid)
except (TypeError, ValueError):
log.exception(
"invalid uid/gid to chown: {}/{}, skip chown", valid_uid, valid_gid
)
continue
try:
os.chown(p, int_uid, int_gid)
except OSError as e:
log.exception(
"failed to chown {} to {}/{} (error: {})", p, int_uid, int_gid, repr(e)
)
@override
async def prepare_scratch(self) -> None:
loop = current_loop()
# Create the scratch, config, and work directories.
scratch_type = self.local_config.container.scratch_type
scratch_root = self.local_config.container.scratch_root
scratch_size = self.local_config.container.scratch_size
if sys.platform.startswith("linux") and scratch_type == "memory":
await loop.run_in_executor(None, partial(self.tmp_dir.mkdir, exist_ok=True))
await create_scratch_filesystem(self.scratch_dir, 64)
await create_scratch_filesystem(self.tmp_dir, 64)
elif sys.platform.startswith("linux") and scratch_type == "hostfile":
await create_loop_filesystem(scratch_root, scratch_size, self.kernel_id)
else:
await loop.run_in_executor(None, partial(self.scratch_dir.mkdir, exist_ok=True))
def _create_scratch_dirs() -> None:
self.config_dir.mkdir(parents=True, exist_ok=True)
self.config_dir.chmod(0o755)
self.work_dir.mkdir(parents=True, exist_ok=True)
self.work_dir.chmod(0o755)
await loop.run_in_executor(None, _create_scratch_dirs)
if not self.restarting:
# Since these files are bind-mounted inside a bind-mounted directory,
# we need to touch them first to avoid their "ghost" files are created
# as root in the host-side filesystem, which prevents deletion of scratch
# directories when the agent is running as non-root.
def _clone_dotfiles() -> None:
jupyter_custom_css_path = Path(
str(files("ai.backend.runner").joinpath("jupyter-custom.css"))
)
logo_path = Path(str(files("ai.backend.runner").joinpath("logo.svg")))
font_path = Path(str(files("ai.backend.runner").joinpath("roboto.ttf")))
font_italic_path = Path(
str(files("ai.backend.runner").joinpath("roboto-italic.ttf"))
)
bashrc_path = Path(str(files("ai.backend.runner").joinpath(".bashrc")))
bash_profile_path = Path(str(files("ai.backend.runner").joinpath(".bash_profile")))
zshrc_path = Path(str(files("ai.backend.runner").joinpath(".zshrc")))
vimrc_path = Path(str(files("ai.backend.runner").joinpath(".vimrc")))
tmux_conf_path = Path(str(files("ai.backend.runner").joinpath(".tmux.conf")))
persistent_files_warning_doc_path = Path(
str(
files("ai.backend.runner").joinpath("DO_NOT_STORE_PERSISTENT_FILES_HERE.md")
)
)
jupyter_custom_dir = self.work_dir / ".jupyter" / "custom"
jupyter_custom_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(jupyter_custom_css_path.resolve(), jupyter_custom_dir / "custom.css")
shutil.copy(logo_path.resolve(), jupyter_custom_dir / "logo.svg")
shutil.copy(font_path.resolve(), jupyter_custom_dir / "roboto.ttf")
shutil.copy(font_italic_path.resolve(), jupyter_custom_dir / "roboto-italic.ttf")
shutil.copy(bashrc_path.resolve(), self.work_dir / ".bashrc")
shutil.copy(bash_profile_path.resolve(), self.work_dir / ".bash_profile")
shutil.copy(zshrc_path.resolve(), self.work_dir / ".zshrc")
shutil.copy(vimrc_path.resolve(), self.work_dir / ".vimrc")
shutil.copy(tmux_conf_path.resolve(), self.work_dir / ".tmux.conf")
shutil.copy(
persistent_files_warning_doc_path.resolve(),
self.work_dir / "DO_NOT_STORE_PERSISTENT_FILES_HERE.md",
)
def chown_scratch(uid: int | None, gid: int | None) -> None:
paths = [
self.work_dir,
self.work_dir / ".jupyter",
self.work_dir / ".jupyter" / "custom",
self.work_dir / ".bashrc",
self.work_dir / ".bash_profile",
self.work_dir / ".zshrc",
self.work_dir / ".vimrc",
self.work_dir / ".tmux.conf",
self.work_dir / "DO_NOT_STORE_PERSISTENT_FILES_HERE.md",
]
self._chown_paths_if_root(paths, uid, gid)
do_override = False
if (ouid := self.get_overriding_uid()) is not None:
do_override = True
if (ogid := self.get_overriding_gid()) is not None:
do_override = True
if do_override:
chown_scratch(ouid, ogid)
else:
if KernelFeatures.UID_MATCH in self.kernel_features:
chown_scratch(
self.local_config.container.kernel_uid,
self.local_config.container.kernel_gid,
)
await loop.run_in_executor(None, _clone_dotfiles)
@override
async def get_intrinsic_mounts(self) -> Sequence[Mount]:
loop = current_loop()
# scratch/config/tmp mounts
mounts: list[Mount] = [
Mount(
MountTypes.BIND, self.config_dir, Path("/home/config"), MountPermission.READ_ONLY
),
Mount(MountTypes.BIND, self.work_dir, Path("/home/work"), MountPermission.READ_WRITE),
]
if (
sys.platform.startswith("linux")
and self.local_config.container.scratch_type == ScratchType.MEMORY
):
mounts.append(
Mount(
MountTypes.BIND,
self.tmp_dir,
Path("/tmp"),
MountPermission.READ_WRITE,
)
)
# /etc/localtime and /etc/timezone mounts
if sys.platform.startswith("linux"):
localtime_file = Path("/etc/localtime")
timezone_file = Path("/etc/timezone")
if localtime_file.exists():
mounts.append(
Mount(
type=MountTypes.BIND,
source=localtime_file,
target=localtime_file,
permission=MountPermission.READ_ONLY,
)
)
if timezone_file.exists():
mounts.append(
Mount(
type=MountTypes.BIND,
source=timezone_file,
target=timezone_file,
permission=MountPermission.READ_ONLY,
)
)
# lxcfs mounts
lxcfs_root = Path("/var/lib/lxcfs")
if lxcfs_root.is_dir():
mounts.extend(
Mount(
MountTypes.BIND,
lxcfs_proc_path,
"/" / lxcfs_proc_path.relative_to(lxcfs_root),
MountPermission.READ_WRITE,
)
for lxcfs_proc_path in (lxcfs_root / "proc").iterdir()
if lxcfs_proc_path.stat().st_size > 0
)
mounts.extend(
Mount(
MountTypes.BIND,
lxcfs_root / path,
"/" / Path(path),
MountPermission.READ_WRITE,
)
for path in [
"sys/devices/system/cpu",
"sys/devices/system/cpu/online",
]
if Path(lxcfs_root / path).exists()
)
# extra mounts
async with closing_async(Docker()) as docker:
extra_mount_list = await get_extra_volumes(docker, self.image_ref.short)
for v in extra_mount_list:
permission = MountPermission.READ_ONLY if v.mode == "ro" else MountPermission.READ_WRITE
mounts.append(
Mount(MountTypes.VOLUME, Path(v.name), Path(v.container_path), permission)
)
# debug mounts
if self.local_config.debug.coredump.enabled:
mounts.append(
Mount(
MountTypes.BIND,
self.local_config.debug.coredump.path,
self.local_config.debug.coredump.core_path,
MountPermission.READ_WRITE,
)
)
# agent-socket mount
if sys.platform != "darwin":
mounts.append(
Mount(
MountTypes.BIND,
self.agent_sockpath,
Path("/opt/kernel/agent.sock"),
MountPermission.READ_WRITE,
)
)
ipc_base_path = self.local_config.agent.ipc_base_path
# domain-socket proxy mount
# (used for special service containers such image importer)
for host_sock_path in self.internal_data.get("domain_socket_proxies", []):
await loop.run_in_executor(
None, partial((ipc_base_path / "proxy").mkdir, parents=True, exist_ok=True)
)
host_proxy_path = ipc_base_path / "proxy" / f"{secrets.token_hex(12)}.sock"
proxy_server = await asyncio.start_unix_server(
aiotools.apartial(proxy_connection, host_sock_path), str(host_proxy_path)
)
await loop.run_in_executor(None, host_proxy_path.chmod, 0o666)
self.domain_socket_proxies.append(
DomainSocketProxy(
Path(host_sock_path),
host_proxy_path,
proxy_server,
)
)
mounts.append(
Mount(
MountTypes.BIND,
host_proxy_path,
host_sock_path,
MountPermission.READ_WRITE,
)
)
return mounts
@override
def resolve_krunner_filepath(self, filename: str) -> Path:
return Path(str(files("ai.backend.runner").joinpath("../" + filename))).resolve()
@override
def get_runner_mount(
self,
type: MountTypes,
src: str | Path,
target: str | Path,
perm: MountPermission = MountPermission.READ_ONLY,
opts: Mapping[str, Any] | None = None,
) -> Mount:
return Mount(
type,
Path(src),
Path(target),
MountPermission(perm),
opts=opts,
)
@override
async def apply_network(self, cluster_info: ClusterInfo) -> None:
# FIXME: find out way to inect network ID to kernel resource spec
match cluster_info["network_config"].get("mode"):
case "bridge":
self.container_configs.append({
"HostConfig": {
"NetworkMode": cluster_info["network_config"]["network_name"],
},
"NetworkingConfig": {
"EndpointsConfig": {
cluster_info["network_config"]["network_name"]: {
"Aliases": [self.kernel_config["cluster_hostname"]],
},
},
},
})
case mode if mode:
try:
plugin = self.network_plugin_ctx.plugins[mode]
except KeyError as e:
raise RuntimeError(f"Network plugin {mode} not loaded!") from e
container_config = await plugin.join_network(
self.kernel_config, cluster_info, **cluster_info["network_config"]
)
self.container_configs.append(container_config)
if self.gwbridge_subnet is not None:
self.container_configs.append({
"Env": [f"OMPI_MCA_btl_tcp_if_exclude=127.0.0.1/32,{self.gwbridge_subnet}"],
})
if self.local_config.container.alternative_bridge is not None:
self.container_configs.append({
"HostConfig": {
"NetworkMode": self.local_config.container.alternative_bridge,
},
})
# RDMA mounts
ib_root = Path("/dev/infiniband")
if ib_root.is_dir() and (ib_root / "uverbs0").exists():
self.container_configs.append({
"HostConfig": {
"Devices": [
{
"PathOnHost": "/dev/infiniband",
"PathInContainer": "/dev/infiniband",
"CgroupPermissions": "rwm",
},
],
},
})
@override
async def prepare_ssh(self, cluster_info: ClusterInfo) -> None:
sshkey = cluster_info["ssh_keypair"]
def _write_config() -> None:
try:
ssh_dir = self.config_dir / "ssh"
ssh_dir.mkdir(parents=True, exist_ok=True)
paths_to_chown: list[Path] = []
# Generate dropbear host key for container SSH server
host_key_path = ssh_dir / "dropbear_rsa_host_key"
arch = get_arch_name()
dropbearmulti_path = self.resolve_krunner_filepath(
f"runner/dropbearmulti.{arch}.bin"
)
if not dropbearmulti_path.exists():
raise FileNotFoundError(
f"dropbearmulti binary not found at {dropbearmulti_path}"
)
# If the host key already exists, we assume it's valid and skip generation.
if not host_key_path.is_file():
try:
subprocess_run(
[
str(dropbearmulti_path),
"dropbearkey",
"-t",
"rsa",
"-s",
"2048",
"-f",
str(host_key_path),
],
check=True,
capture_output=True,
)
host_key_path.chmod(0o600)
except CalledProcessError as e:
stderr = e.stderr.decode("utf-8", "replace") if e.stderr else ""
stdout = e.stdout.decode("utf-8", "replace") if e.stdout else ""
log.warning(
"dropbearkey failed. Host key will regenerate on container startup. Return code {code}, stdout: {stdout}, stderr: {stderr}",
code=e.returncode,
stdout=stdout,
stderr=stderr,
)
except OSError as e:
log.warning(
"failed to execute dropbearmulti for host key generation. Host key will regenerate on container startup: {}",
repr(e),
)
paths_to_chown.append(host_key_path)
# Write provided SSH keypair for cluster access if exists
if sshkey is not None:
cluster_priv_key_path = ssh_dir / "id_cluster"
cluster_pub_key_path = ssh_dir / "id_cluster.pub"
cluster_priv_key_path.write_text(sshkey["private_key"])
cluster_pub_key_path.write_text(sshkey["public_key"])
cluster_priv_key_path.chmod(0o600)
paths_to_chown.extend([cluster_priv_key_path, cluster_pub_key_path])
if cluster_ssh_port_mapping := cluster_info["cluster_ssh_port_mapping"]:
port_mapping_json_path = ssh_dir / "port-mapping.json"
port_mapping_json_path.write_bytes(dump_json(cluster_ssh_port_mapping))
# Set ownership for all created files
ouid = self.get_overriding_uid()
ogid = self.get_overriding_gid()
if ouid is not None or ogid is not None:
self._chown_paths_if_root(paths_to_chown, ouid, ogid)
elif KernelFeatures.UID_MATCH in self.kernel_features:
self._chown_paths_if_root(
paths_to_chown,
self.local_config.container.kernel_uid,
self.local_config.container.kernel_gid,
)
except Exception:
log.exception("error while writing SSH keys")
await current_loop().run_in_executor(None, _write_config)
@override
async def process_mounts(self, mounts: Sequence[Mount]) -> None:
def fix_unsupported_perm(folder_perm: MountPermission) -> MountPermission:
if folder_perm == MountPermission.RW_DELETE:
# TODO: enforce readable/writable but not deletable
# (Currently docker's READ_WRITE includes DELETE)
return MountPermission.READ_WRITE
return folder_perm
container_config = {
"HostConfig": {
"Mounts": [
{
"Target": str(mount.target),
"Source": str(mount.source),
"Type": mount.type.value,
"ReadOnly": (
fix_unsupported_perm(mount.permission) == MountPermission.READ_ONLY
),
f"{mount.type.value.capitalize()}Options": mount.opts if mount.opts else {},
}
for mount in mounts
],
},
}
self.container_configs.append(container_config)
@override
async def apply_accelerator_allocation(
self,
computer: AbstractComputePlugin,
device_alloc: Mapping[SlotName, Mapping[DeviceId, Decimal]],
) -> None:
async with closing_async(Docker()) as docker:
update_nested_dict(
self.computer_docker_args,
await computer.generate_docker_args(docker, device_alloc),
)
@override
async def generate_accelerator_mounts(
self,
computer: AbstractComputePlugin,
device_alloc: Mapping[SlotName, Mapping[DeviceId, Decimal]],
) -> list[MountInfo]:
src_path = self.config_dir / str(computer.key)
src_path.mkdir(exist_ok=True)
return await computer.generate_mounts(src_path, device_alloc)
@override
async def prepare_container(
self,
resource_spec: KernelResourceSpec,
environ: Mapping[str, str],
service_ports: list[ServicePort],
cluster_info: ClusterInfo,
) -> DockerKernel:
loop = current_loop()
ouid = self.get_overriding_uid()
ogid = self.get_overriding_gid()
if self.restarting:
pass
else:
# Create bootstrap.sh into workdir if needed
if bootstrap := self.kernel_config.get("bootstrap_script"):
def _write_user_bootstrap_script() -> None:
(self.work_dir / "bootstrap.sh").write_text(bootstrap)
if ouid is not None or ogid is not None:
self._chown_paths_if_root([self.work_dir / "bootstrap.sh"], ouid, ogid)
else:
if KernelFeatures.UID_MATCH in self.kernel_features:
self._chown_paths_if_root(
[self.work_dir / "bootstrap.sh"],
self.local_config.container.kernel_uid,
self.local_config.container.kernel_gid,
)
await loop.run_in_executor(None, _write_user_bootstrap_script)
with StringIO() as buf:
for k, v in environ.items():
buf.write(f"{k}={v}\n")
accel_envs = self.computer_docker_args.get("Env", [])
for env in accel_envs:
buf.write(f"{env}\n")
await loop.run_in_executor(
None,
(self.config_dir / "environ.txt").write_bytes,
buf.getvalue().encode("utf8"),
)
with StringIO() as buf:
resource_spec.write_to_file(buf)
for dev_type, device_alloc in resource_spec.allocations.items():
device_plugin = self.computers[dev_type].instance
kvpairs = await device_plugin.generate_resource_data(device_alloc)
for k, v in kvpairs.items():
buf.write(f"{k}={v}\n")
await loop.run_in_executor(
None,
(self.config_dir / "resource.txt").write_bytes,
buf.getvalue().encode("utf8"),
)
shutil.copyfile(self.config_dir / "environ.txt", self.config_dir / "environ_base.txt")
shutil.copyfile(self.config_dir / "resource.txt", self.config_dir / "resource_base.txt")
# TODO: refactor out dotfiles/sshkey initialization to the base agent?
docker_creds = self.internal_data.get("docker_credentials")
if docker_creds:
await loop.run_in_executor(
None,
(self.config_dir / "docker-creds.json").write_bytes,
dump_json(docker_creds),
)
# Create SSH keypair only if ssh_keypair internal_data exists and
# /home/work/.ssh folder is not mounted.
if self.internal_data.get("ssh_keypair"):
for mount in resource_spec.mounts:
container_path = str(mount).split(":")[1]
if container_path == "/home/work/.ssh":
break
else:
pubkey = self.internal_data["ssh_keypair"]["public_key"].encode("ascii")
privkey = self.internal_data["ssh_keypair"]["private_key"].encode("ascii")
ssh_dir = self.work_dir / ".ssh"
def _populate_ssh_config() -> None:
ssh_dir.mkdir(parents=True, exist_ok=True)
ssh_dir.chmod(0o700)
(ssh_dir / "authorized_keys").write_bytes(pubkey)
(ssh_dir / "authorized_keys").chmod(0o600)
if not (ssh_dir / "id_rsa").is_file():
(ssh_dir / "id_rsa").write_bytes(privkey)
(ssh_dir / "id_rsa").chmod(0o600)
(self.work_dir / "id_container").write_bytes(privkey)
(self.work_dir / "id_container").chmod(0o600)
def chown_idfile(uid: int | None, gid: int | None) -> None:
paths = [
ssh_dir,
ssh_dir / "authorized_keys",
ssh_dir / "id_rsa",
self.work_dir / "id_container",
]
self._chown_paths_if_root(paths, uid, gid)
if ouid is not None or ogid is not None:
chown_idfile(ouid, ogid)
else:
if KernelFeatures.UID_MATCH in self.kernel_features:
chown_idfile(
self.local_config.container.kernel_uid,
self.local_config.container.kernel_gid,
)
await loop.run_in_executor(None, _populate_ssh_config)
# higher priority dotfiles are stored last to support overwriting
for dotfile in self.internal_data.get("dotfiles", []):
if dotfile["path"].startswith("/"):
if dotfile["path"].startswith("/home/"):
path_arr = dotfile["path"].split("/")
file_path: Path = self.scratch_dir / "/".join(path_arr[2:])
else:
file_path = Path(dotfile["path"])
else:
file_path = self.work_dir / dotfile["path"]
file_path.parent.mkdir(parents=True, exist_ok=True)
dotfile_content = dotfile["data"]
if not dotfile_content.endswith("\n"):
dotfile_content += "\n"
await loop.run_in_executor(None, file_path.write_text, dotfile_content)
tmp = Path(file_path)
tmp_paths: list[Path] = []
while tmp != self.work_dir:
tmp.chmod(int(dotfile["perm"], 8))
tmp_paths.append(tmp)
tmp = tmp.parent
if ouid is not None or ogid is not None:
self._chown_paths_if_root(tmp_paths, ouid, ogid)
else:
if KernelFeatures.UID_MATCH in self.kernel_features:
self._chown_paths_if_root(
tmp_paths,