-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathagent.py
More file actions
3875 lines (3586 loc) · 160 KB
/
agent.py
File metadata and controls
3875 lines (3586 loc) · 160 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 enum
import errno
import logging
import pickle
import re
import signal
import sys
import traceback
import weakref
import zlib
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from collections.abc import (
AsyncGenerator,
Awaitable,
Callable,
Coroutine,
Generator,
Iterable,
Mapping,
MutableMapping,
MutableSequence,
Sequence,
)
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC
from decimal import Decimal
from importlib.resources import files
from io import SEEK_END, BytesIO
from itertools import chain
from pathlib import Path
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
Concatenate,
Final,
Literal,
ParamSpec,
cast,
)
from uuid import UUID
import aiotools
import attrs
import zmq
import zmq.asyncio
from async_timeout import timeout
from cachetools import LRUCache, cached
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError
from tenacity import (
AsyncRetrying,
RetryError,
TryAgain,
retry_if_exception_type,
stop_after_attempt,
stop_after_delay,
wait_fixed,
)
from trafaret import DataError
from ai.backend.agent.errors import (
AsyncioTaskNotAvailableError,
InvalidChunkSizeError,
KernelNotFoundError,
)
from ai.backend.agent.etcd import AgentEtcdClientView
from ai.backend.agent.metrics.metric import (
StatScope,
StatTaskObserver,
SyncContainerLifecycleObserver,
)
from ai.backend.common import msgpack
from ai.backend.common.asyncio import cancel_tasks, current_loop
from ai.backend.common.bgtask.bgtask import BackgroundTaskManager
from ai.backend.common.clients.valkey_client.valkey_bgtask.client import ValkeyBgtaskClient
from ai.backend.common.clients.valkey_client.valkey_container_log.client import (
ValkeyContainerLogClient,
)
from ai.backend.common.clients.valkey_client.valkey_image.client import ValkeyImageClient
from ai.backend.common.clients.valkey_client.valkey_schedule import ValkeyScheduleClient
from ai.backend.common.clients.valkey_client.valkey_stat.client import ValkeyStatClient
from ai.backend.common.clients.valkey_client.valkey_stream.client import ValkeyStreamClient
from ai.backend.common.config import model_definition_iv
from ai.backend.common.data.agent.types import AgentInfo, ImageOpts
from ai.backend.common.data.image.types import InstalledImageInfo, ScannedImage
from ai.backend.common.defs import (
REDIS_BGTASK_DB,
REDIS_CONTAINER_LOG,
REDIS_IMAGE_DB,
REDIS_LIVE_DB,
REDIS_STATISTICS_DB,
REDIS_STREAM_DB,
UNKNOWN_CONTAINER_ID,
RedisRole,
)
from ai.backend.common.docker import (
DEFAULT_KERNEL_FEATURE,
MAX_KERNELSPEC,
MIN_KERNELSPEC,
ImageRef,
KernelFeatures,
LabelName,
)
from ai.backend.common.dto.agent.response import CodeCompletionResp, PurgeImagesResp
from ai.backend.common.dto.manager.rpc_request import PurgeImagesReq
from ai.backend.common.events.dispatcher import (
EventDispatcher,
EventProducer,
)
from ai.backend.common.events.event_types.agent.anycast import (
AgentErrorEvent,
AgentHeartbeatEvent,
AgentInstalledImagesRemoveEvent,
AgentStartedEvent,
AgentTerminatedEvent,
DoAgentResourceCheckEvent,
)
from ai.backend.common.events.event_types.kernel.anycast import (
DoSyncKernelLogsEvent,
KernelCreatingAnycastEvent,
KernelPreparingAnycastEvent,
KernelPullingAnycastEvent,
KernelStartedAnycastEvent,
KernelTerminatedAnycastEvent,
)
from ai.backend.common.events.event_types.kernel.broadcast import (
KernelCreatingBroadcastEvent,
KernelPreparingBroadcastEvent,
KernelPullingBroadcastEvent,
KernelStartedBroadcastEvent,
KernelTerminatedBroadcastEvent,
)
from ai.backend.common.events.event_types.kernel.types import KernelLifecycleEventReason
from ai.backend.common.events.event_types.model_serving.anycast import (
ModelServiceStatusAnycastEvent,
)
from ai.backend.common.events.event_types.model_serving.broadcast import (
ModelServiceStatusBroadcastEvent,
)
from ai.backend.common.events.event_types.session.anycast import (
ExecutionFinishedAnycastEvent,
ExecutionStartedAnycastEvent,
ExecutionTimeoutAnycastEvent,
SessionFailureAnycastEvent,
SessionSuccessAnycastEvent,
)
from ai.backend.common.events.event_types.session.broadcast import (
SessionFailureBroadcastEvent,
SessionSuccessBroadcastEvent,
)
from ai.backend.common.events.event_types.volume.broadcast import (
DoVolumeMountEvent,
DoVolumeUnmountEvent,
VolumeMounted,
VolumeUnmounted,
)
from ai.backend.common.events.types import (
AbstractAnycastEvent,
AbstractBroadcastEvent,
AbstractEvent,
)
from ai.backend.common.exception import ConfigurationError, VolumeMountFailed
from ai.backend.common.json import (
dump_json,
dump_json_str,
load_json,
)
from ai.backend.common.lock import FileLock
from ai.backend.common.log.types import (
ContainerLogData,
ContainerLogType,
)
from ai.backend.common.message_queue.hiredis_queue import HiRedisQueue
from ai.backend.common.message_queue.queue import AbstractMessageQueue
from ai.backend.common.message_queue.redis_queue import RedisMQArgs, RedisQueue
from ai.backend.common.metrics.metric import CommonMetricRegistry
from ai.backend.common.metrics.types import UTILIZATION_METRIC_INTERVAL
from ai.backend.common.plugin.monitor import ErrorPluginContext, StatsPluginContext
from ai.backend.common.runner.types import Runner
from ai.backend.common.service_ports import parse_service_ports
from ai.backend.common.typed_validators import HostPortPair
from ai.backend.common.types import (
MODEL_SERVICE_RUNTIME_PROFILES,
AbuseReportValue,
AgentId,
AutoPullBehavior,
BinarySize,
ClusterInfo,
ClusterSSHPortMapping,
CommitStatus,
ContainerId,
ContainerStatus,
DeviceId,
DeviceName,
HardwareMetadata,
ImageCanonical,
ImageConfig,
ImageRegistry,
KernelCreationConfig,
KernelCreationResult,
KernelId,
ModelServiceStatus,
MountPermission,
MountTypes,
RedisTarget,
ResourceSlot,
RuntimeVariant,
Sentinel,
ServicePort,
ServicePortProtocols,
SessionId,
SessionTypes,
SlotName,
SlotTypes,
VFolderMount,
VFolderUsageMode,
VolumeMountableNodeType,
aobject,
)
from ai.backend.common.utils import (
chown,
mount,
umount,
)
from ai.backend.logging import BraceStyleAdapter
from ai.backend.logging.formatter import pretty
from . import __version__ as VERSION
from .affinity_map import AffinityMap
from .config.unified import AgentUnifiedConfig, ContainerSandboxType
from .errors import (
ContainerCreationFailedError,
ContainerStartupCancelledError,
ContainerStartupFailedError,
ContainerStartupTimeoutError,
ImageArchitectureMismatchError,
ImageCommandRequiredError,
ImagePullTimeoutError,
ModelDefinitionEmptyError,
ModelDefinitionInvalidYAMLError,
ModelDefinitionNotFoundError,
ModelDefinitionValidationError,
ModelFolderNotSpecifiedError,
PortConflictError,
ReservedPortError,
)
from .exception import ContainerCreationError, ResourceError
from .kernel import (
RUN_ID_FOR_BATCH_JOB,
AbstractKernel,
KernelRegistry,
match_distro_data,
)
from .kernel_registry.writer.types import KernelRegistrySaveMetadata
from .observer.host_port import HostPortObserver
from .observer.kernel_presence import KernelPresenceObserver
from .observer.orphan_kernel_cleanup import OrphanKernelCleanupObserver
from .resources import (
AbstractComputePlugin,
ComputerContext,
KernelResourceSpec,
Mount,
allocate,
known_slot_types,
)
from .stats import StatContext, StatModes
from .types import (
Container,
ContainerLifecycleEvent,
KernelLifecycleStatus,
KernelOwnershipData,
LifecycleEvent,
MountInfo,
)
from .utils import generate_local_instance_id, get_arch_name
if TYPE_CHECKING:
from ai.backend.common.auth import PublicKey
log = BraceStyleAdapter(logging.getLogger(__spec__.name))
_sentinel = Sentinel.TOKEN
ACTIVE_STATUS_SET = frozenset([
ContainerStatus.RUNNING,
ContainerStatus.RESTARTING,
ContainerStatus.PAUSED,
])
DEAD_STATUS_SET = frozenset([
ContainerStatus.EXITED,
ContainerStatus.DEAD,
ContainerStatus.REMOVING,
])
COMMIT_STATUS_EXPIRE: Final[int] = 13
EVENT_DISPATCHER_CONSUMER_GROUP: Final = "agent"
STAT_COLLECTION_TIMEOUT: Final[float] = 10 * 60 # 10 minutes
P = ParamSpec("P")
KernelIdContainerPair = tuple[KernelId, Container]
def update_additional_gids(environ: MutableMapping[str, str], gids: Iterable[int]) -> None:
if not gids:
return
if orig_additional_gids := environ.get("ADDITIONAL_GIDS"):
orig_add_gids = {int(gid) for gid in orig_additional_gids.split(",") if gid}
additional_gids = orig_add_gids | set(gids)
else:
additional_gids = set(gids)
environ["ADDITIONAL_GIDS"] = ",".join(map(str, additional_gids))
@dataclass
class ScanImagesResult:
scanned_images: Mapping[ImageCanonical, InstalledImageInfo]
removed_images: Mapping[ImageCanonical, InstalledImageInfo]
@dataclass
class PullTaskInfo:
"""Track image pull operation."""
image: str
@dataclass
class CreateTaskInfo:
"""Track kernel creation operation."""
kernel_id: KernelId
session_id: SessionId
class AgentClass(enum.Enum):
PRIMARY = enum.auto()
AUXILIARY = enum.auto()
class AbstractKernelCreationContext[KernelObjectType: AbstractKernel](aobject):
kspec_version: int
distro: str
ownership_data: KernelOwnershipData
kernel_id: KernelId
session_id: SessionId
agent_id: AgentId
event_producer: EventProducer
kernel_config: KernelCreationConfig
local_config: AgentUnifiedConfig
kernel_features: frozenset[str]
image_ref: ImageRef
internal_data: Mapping[str, Any]
additional_allowed_syscalls: list[str]
restarting: bool
cancellation_handlers: Sequence[Callable[[], Awaitable[None]]] = []
_rx_distro = re.compile(r"\.([a-z-]+\d+\.\d+)\.")
def __init__(
self,
ownership_data: KernelOwnershipData,
event_producer: EventProducer,
kernel_image: ImageRef,
kernel_config: KernelCreationConfig,
distro: str,
local_config: AgentUnifiedConfig,
computers: Mapping[DeviceName, ComputerContext],
restarting: bool = False,
) -> None:
self.image_labels = kernel_config["image"]["labels"]
self.kspec_version = int(self.image_labels.get(LabelName.KERNEL_SPEC, "1"))
self.kernel_features = frozenset(
self.image_labels.get(LabelName.FEATURES, DEFAULT_KERNEL_FEATURE).split()
)
self.ownership_data = ownership_data
self.session_id = ownership_data.session_id
self.kernel_id = ownership_data.kernel_id
self.agent_id = ownership_data.agent_id
self.event_producer = event_producer
self.kernel_config = kernel_config
self.image_ref = kernel_image
self.distro = distro
self.uid = kernel_config["uid"]
self.main_gid = kernel_config["main_gid"]
self.supplementary_gids = set(kernel_config["supplementary_gids"])
self.internal_data = kernel_config["internal_data"] or {}
self.computers = computers
self.restarting = restarting
self.local_config = local_config
self.additional_allowed_syscalls = []
@abstractmethod
async def get_extra_envs(self) -> Mapping[str, str]:
return {}
@abstractmethod
async def prepare_resource_spec(
self,
) -> tuple[KernelResourceSpec, Mapping[str, Any] | None]:
"""
Generates base resource spec lacking non agent backend agnostic information
(e.g. unified device allocation). Do not call this method directly outside
`generate_resource_spec` implementation.
"""
raise NotImplementedError
@abstractmethod
async def prepare_scratch(self) -> None:
pass
@abstractmethod
async def get_intrinsic_mounts(self) -> Sequence[Mount]:
return []
def update_user_bootstrap_script(self, script: str) -> None:
"""
Replace user-defined bootstrap script to an arbitrary one created by agent.
"""
self.kernel_config["bootstrap_script"] = script
@property
@abstractmethod
def repl_ports(self) -> Sequence[int]:
"""
Return the list of intrinsic REPL ports to exclude from public mapping.
"""
raise NotImplementedError
@property
@abstractmethod
def protected_services(self) -> Sequence[str]:
"""
Return the list of protected (intrinsic) service names to exclude from public mapping.
"""
raise NotImplementedError
@abstractmethod
async def apply_network(self, cluster_info: ClusterInfo) -> None:
"""
Apply the given cluster network information to the deployment.
"""
raise NotImplementedError
@abstractmethod
async def prepare_ssh(self, cluster_info: ClusterInfo) -> None:
"""
Prepare container to accept SSH connection.
Install the ssh keypair inside the kernel from cluster_info.
"""
raise NotImplementedError
@abstractmethod
async def process_mounts(self, mounts: Sequence[Mount]) -> None:
raise NotImplementedError
@abstractmethod
async def apply_accelerator_allocation(
self,
computer: AbstractComputePlugin,
device_alloc: Mapping[SlotName, Mapping[DeviceId, Decimal]],
) -> None:
raise NotImplementedError
@abstractmethod
async def generate_accelerator_mounts(
self,
computer: AbstractComputePlugin,
device_alloc: Mapping[SlotName, Mapping[DeviceId, Decimal]],
) -> list[MountInfo]:
raise NotImplementedError
@abstractmethod
def resolve_krunner_filepath(self, filename: str) -> Path:
"""
Return matching krunner path object for given filename.
"""
raise NotImplementedError
@abstractmethod
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 object to mount target krunner file/folder/volume.
"""
raise NotImplementedError
@abstractmethod
async def prepare_container(
self,
resource_spec: KernelResourceSpec,
environ: Mapping[str, str],
service_ports: list[ServicePort],
cluster_info: ClusterInfo,
) -> KernelObjectType:
raise NotImplementedError
@abstractmethod
async def start_container(
self,
kernel_obj: AbstractKernel,
cmdargs: list[str],
resource_opts: Mapping[str, Any] | None,
preopen_ports: list[int],
cluster_info: ClusterInfo,
) -> Mapping[str, Any]:
raise NotImplementedError
@cached(
cache=LRUCache(maxsize=32),
key=lambda self: (
self.image_ref,
self.distro,
),
)
def get_krunner_info(self) -> tuple[str, str, str, str, str]:
distro = self.distro
matched_distro, krunner_volume = match_distro_data(
self.local_config.container.krunner_volumes or {}, distro
)
matched_libc_style = "glibc"
if distro.startswith("alpine"):
matched_libc_style = "musl"
krunner_pyver = "3.6" # fallback
if m := re.search(r"^([a-z-]+)(\d+(\.\d+)*)?$", matched_distro):
matched_distro_pkgname = m.group(1).replace("-", "_")
try:
krunner_pyver = (
Path(
str(
files(f"ai.backend.krunner.{matched_distro_pkgname}").joinpath(
f"krunner-python.{matched_distro}.txt"
)
)
)
.read_text()
.strip()
)
except FileNotFoundError:
pass
log.debug("selected krunner: {}", matched_distro)
log.debug("selected libc style: {}", matched_libc_style)
log.debug("krunner volume: {}", krunner_volume)
log.debug("krunner python: {}", krunner_pyver)
arch = get_arch_name()
return arch, matched_distro, matched_libc_style, krunner_volume, krunner_pyver
async def mount_vfolders(
self,
vfolders: Sequence[VFolderMount],
resource_spec: KernelResourceSpec,
) -> None:
for vfolder in vfolders:
if self.internal_data.get("prevent_vfolder_mounts", False):
if vfolder.name != ".logs":
continue
mount = Mount(
MountTypes.BIND,
Path(vfolder.host_path),
Path(vfolder.kernel_path),
vfolder.mount_perm,
)
resource_spec.mounts.append(mount)
async def mount_krunner(
self,
resource_spec: KernelResourceSpec,
environ: MutableMapping[str, str],
) -> None:
def _mount(
type: MountTypes,
src: str | Path,
dst: str | Path,
) -> None:
resource_spec.mounts.append(
self.get_runner_mount(
type,
src,
dst,
MountPermission.READ_ONLY,
),
)
# Inject Backend.AI kernel runner dependencies.
distro = self.distro
(
arch,
matched_distro,
matched_libc_style,
krunner_volume,
krunner_pyver,
) = self.get_krunner_info()
artifact_path = Path(str(files("ai.backend.agent").joinpath("../runner")))
def find_artifacts(pattern: str) -> Mapping[str, str]:
artifacts = {}
for p in artifact_path.glob(pattern):
m = self._rx_distro.search(p.name)
if m is not None:
artifacts[m.group(1)] = p.name
return artifacts
def mount_versioned_binary(candidate_glob: str, target_path: str) -> None:
candidates = find_artifacts(candidate_glob)
_, candidate = match_distro_data(candidates, distro)
resolved_path = self.resolve_krunner_filepath("runner/" + candidate)
_mount(MountTypes.BIND, resolved_path, target_path)
def mount_static_binary(
filename: str,
target_path: str,
skip_missing: bool = False,
) -> None:
resolved_path = self.resolve_krunner_filepath("runner/" + filename)
if not skip_missing and not resolved_path.exists():
raise FileNotFoundError(resolved_path)
_mount(MountTypes.BIND, resolved_path, target_path)
mount_static_binary(f"su-exec.{arch}.bin", "/opt/kernel/su-exec")
# /opt/kernel is for private executables not exposed in the user's PATH.
# /usr/local/bin is for public executables to be exposed in the user's PATH.
mount_versioned_binary(f"libbaihook.*.{arch}.so", "/opt/kernel/libbaihook.so")
mount_static_binary(f"dropbearmulti.{arch}.bin", "/opt/kernel/dropbearmulti")
mount_static_binary(f"sftp-server.{arch}.bin", "/opt/kernel/sftp-server")
mount_static_binary(f"tmux.{arch}.bin", "/opt/kernel/tmux")
mount_static_binary(f"ttyd_linux.{arch}.bin", "/opt/kernel/ttyd")
mount_static_binary("yank.sh", "/opt/kernel/yank.sh")
mount_static_binary(f"all-smi.{arch}.bin", "/usr/local/bin/all-smi")
mount_static_binary("all-smi.1", "/usr/local/share/man/man1/all-smi.1", skip_missing=True)
mount_static_binary(f"bssh.{arch}.bin", "/usr/local/bin/bssh")
mount_static_binary("bssh.1", "/usr/local/share/man/man1/bssh.1", skip_missing=True)
jail_path: Path | None
if self.local_config.container.sandbox_type == ContainerSandboxType.JAIL:
jail_candidates = find_artifacts(
f"jail.*.{arch}.bin"
) # architecture check is already done when starting agent
_, jail_candidate = match_distro_data(jail_candidates, distro)
jail_path = self.resolve_krunner_filepath("runner/" + jail_candidate)
else:
jail_path = None
dotfile_extractor_path = self.resolve_krunner_filepath("runner/extract_dotfiles.py")
entrypoint_sh_path = self.resolve_krunner_filepath("runner/entrypoint.sh")
fantompass_path = self.resolve_krunner_filepath("runner/fantompass.py")
hash_phrase_path = self.resolve_krunner_filepath("runner/hash_phrase.py")
words_json_path = self.resolve_krunner_filepath("runner/words.json")
if matched_libc_style == "musl":
terminfo_path = self.resolve_krunner_filepath("runner/terminfo.alpine3.8")
_mount(MountTypes.BIND, terminfo_path, "/home/work/.terminfo")
_mount(MountTypes.BIND, dotfile_extractor_path, "/opt/kernel/extract_dotfiles.py")
_mount(MountTypes.BIND, entrypoint_sh_path, "/opt/kernel/entrypoint.sh")
_mount(MountTypes.BIND, fantompass_path, "/opt/kernel/fantompass.py")
_mount(MountTypes.BIND, hash_phrase_path, "/opt/kernel/hash_phrase.py")
_mount(MountTypes.BIND, words_json_path, "/opt/kernel/words.json")
if jail_path is not None:
_mount(MountTypes.BIND, jail_path, "/opt/kernel/jail")
_mount(MountTypes.VOLUME, krunner_volume, "/opt/backend.ai")
pylib_path = f"/opt/backend.ai/lib/python{krunner_pyver}/site-packages/"
kernel_pkg_path = self.resolve_krunner_filepath("kernel")
helpers_pkg_path = self.resolve_krunner_filepath("helpers")
_mount(MountTypes.BIND, kernel_pkg_path, pylib_path + "ai/backend/kernel")
_mount(MountTypes.BIND, helpers_pkg_path, pylib_path + "ai/backend/helpers")
environ["LD_PRELOAD"] = "/opt/kernel/libbaihook.so"
# Inject ComputeDevice-specific hooks
already_injected_hooks: set[Path] = set()
for device_view in resource_spec.device_list:
computer_ctx = self.computers[device_view.device]
await self.apply_accelerator_allocation(
computer_ctx.instance,
{device_view.slot: device_view.device_alloc},
)
accelerator_mounts = await self.generate_accelerator_mounts(
computer_ctx.instance,
{device_view.slot: device_view.device_alloc},
)
for mount_info in accelerator_mounts:
_mount(mount_info.mode, mount_info.src_path, mount_info.dst_path.as_posix())
# `.device_list()` guarantees every listed device (slot) would
# actually attach device to the container
hook_paths = await computer_ctx.instance.get_hooks(distro, arch)
if hook_paths:
log.debug(
"accelerator {} provides hooks: {}",
type(computer_ctx.instance).__name__,
", ".join(map(str, hook_paths)),
)
for hook_path in map(lambda p: Path(p).absolute(), hook_paths):
if hook_path in already_injected_hooks:
continue
container_hook_path = f"/opt/kernel/{hook_path.name}"
_mount(MountTypes.BIND, hook_path, container_hook_path)
environ["LD_PRELOAD"] += ":" + container_hook_path
already_injected_hooks.add(hook_path)
async def inject_additional_device_env_vars(
self, resource_spec: KernelResourceSpec, environ: MutableMapping[str, str]
) -> None:
# Inject ComputeDevice-specific env-variables
additional_gid_set: set[int] = set()
additional_allowed_syscalls_set: set[str] = set()
for dev_type, _ in resource_spec.allocations.items():
computer_ctx = self.computers[dev_type]
additional_gids = computer_ctx.instance.get_additional_gids()
additional_gid_set.update(additional_gids)
additional_allowed_syscalls = computer_ctx.instance.get_additional_allowed_syscalls()
additional_allowed_syscalls_set.update(additional_allowed_syscalls)
self.additional_allowed_syscalls = sorted(additional_allowed_syscalls_set)
update_additional_gids(environ, list(additional_gid_set))
def get_overriding_uid(self) -> int | None:
# TODO(BA-3073): This should be separated out to its own class/module.
return self.uid
def get_overriding_gid(self) -> int | None:
# TODO(BA-3073): This should be separated out to its own class/module.
return self.main_gid
def get_supplementary_gids(self) -> set[int]:
# TODO(BA-3073): This should be separated out to its own class/module.
return self.supplementary_gids
async def generate_resource_spec(self) -> tuple[KernelResourceSpec, Mapping[str, Any] | None]:
"""
Creates complete set of `KernelResourceSpec` based on the results from
`prepare_resource_spec()` result.
"""
base_resource_spec, resource_opts = await self.prepare_resource_spec()
unified_devices: list[tuple[DeviceName, SlotName]] = []
# implicitly attach unified accelerators to every created kernels
for dev_type, computer_ctx in self.computers.items():
for slot_name, slot_type in computer_ctx.instance.slot_types:
if slot_type == SlotTypes.UNIFIED:
log.debug(
"mount_krunner(): Attaching Unified device {} to kernel {}",
slot_name,
self.kernel_id,
)
unified_devices.append((dev_type, slot_name))
base_resource_spec.unified_devices = unified_devices
return base_resource_spec, resource_opts
@attrs.define(auto_attribs=True, slots=True)
class RestartTracker:
request_lock: asyncio.Lock
destroy_event: asyncio.Event
done_event: asyncio.Event
def _observe_stat_task(
stat_scope: StatScope,
) -> Callable[
[Callable[Concatenate[AbstractAgent[Any, Any], P], Coroutine[Any, Any, None]]],
Callable[Concatenate[AbstractAgent[Any, Any], P], Coroutine[Any, Any, None]],
]:
stat_task_observer = StatTaskObserver.instance()
def decorator(
func: Callable[Concatenate[AbstractAgent[Any, Any], P], Coroutine[Any, Any, None]],
) -> Callable[Concatenate[AbstractAgent[Any, Any], P], Coroutine[Any, Any, None]]:
async def wrapper(self: AbstractAgent[Any, Any], *args: P.args, **kwargs: P.kwargs) -> None:
stat_task_observer.observe_stat_task_triggered(agent_id=self.id, stat_scope=stat_scope)
try:
await func(self, *args, **kwargs)
except asyncio.CancelledError:
pass
except OSError as e:
if e.errno == errno.EMFILE:
log.warning("skipping {} due to FD exhaustion", func.__name__)
stat_task_observer.observe_stat_task_failure(
agent_id=self.id, stat_scope=stat_scope, exception=e
)
return
log.exception("unhandled exception in {}", func.__name__)
await self.produce_error_event()
stat_task_observer.observe_stat_task_failure(
agent_id=self.id, stat_scope=stat_scope, exception=e
)
except Exception as e:
log.exception("unhandled exception in {}", func.__name__)
await self.produce_error_event()
stat_task_observer.observe_stat_task_failure(
agent_id=self.id, stat_scope=stat_scope, exception=e
)
else:
stat_task_observer.observe_stat_task_success(
agent_id=self.id, stat_scope=stat_scope
)
return wrapper # type: ignore[return-value]
return decorator
class AbstractAgent[
KernelObjectType: AbstractKernel,
KernelCreationContextType: AbstractKernelCreationContext[Any],
](aobject, metaclass=ABCMeta):
id: AgentId
agent_class: AgentClass
loop: asyncio.AbstractEventLoop
local_config: AgentUnifiedConfig
etcd: AgentEtcdClientView
local_instance_id: str
kernel_registry: MutableMapping[KernelId, AbstractKernel]
slots: Mapping[SlotName, Decimal]
computers: Mapping[DeviceName, ComputerContext]
images: Mapping[ImageCanonical, InstalledImageInfo]
port_pool: set[int]
restarting_kernels: MutableMapping[KernelId, RestartTracker]
timer_tasks: MutableSequence[asyncio.Task[Any]]
container_lifecycle_queue: asyncio.Queue[ContainerLifecycleEvent | Sentinel]
agent_public_key: PublicKey | None
stat_ctx: StatContext
stat_sync_sockpath: Path
stat_sync_task: asyncio.Task[Any]
stats_monitor: StatsPluginContext # unused currently
error_monitor: ErrorPluginContext # unused in favor of produce_error_event()
background_task_manager: BackgroundTaskManager
_pending_creation_tasks: dict[KernelId, set[asyncio.Task[Any]]]
_ongoing_exec_batch_tasks: weakref.WeakSet[asyncio.Task[Any]]
_ongoing_destruction_tasks: weakref.WeakValueDictionary[KernelId, asyncio.Task[Any]]
_metric_registry: CommonMetricRegistry
# Health monitoring tracking
_active_pulls: dict[str, PullTaskInfo] # key: image canonical name
_active_creates: dict[KernelId, CreateTaskInfo]
@contextmanager
def track_pull(self, image: str) -> Generator[bool, None, None]:
"""Context manager to track pull operations."""
# Check if image is already being pulled
if image in self._active_pulls:
# Already pulling, don't start another operation
yield False
return
pull_info = PullTaskInfo(image=image)
self._active_pulls[image] = pull_info
try:
yield True
finally:
self._active_pulls.pop(image, None)
@contextmanager
def track_create(
self, kernel_id: KernelId, session_id: SessionId
) -> Generator[bool, None, None]:
"""Context manager to track kernel creation operations."""
# Check if kernel is already being created
if kernel_id in self._active_creates:
# Already creating, don't start another operation
yield False
return
create_info = CreateTaskInfo(kernel_id=kernel_id, session_id=session_id)
self._active_creates[kernel_id] = create_info
try:
yield True
finally:
self._active_creates.pop(kernel_id, None)
def __init__(
self,
etcd: AgentEtcdClientView,
local_config: AgentUnifiedConfig,
*,
stats_monitor: StatsPluginContext,
error_monitor: ErrorPluginContext,
skip_initial_scan: bool = False,
agent_public_key: PublicKey | None,
kernel_registry: KernelRegistry,
computers: Mapping[DeviceName, ComputerContext],
slots: Mapping[SlotName, Decimal],
agent_class: AgentClass,
) -> None:
self._skip_initial_scan = skip_initial_scan
self.loop = current_loop()
self.etcd = etcd
self.local_config = local_config
self.id = AgentId(local_config.agent.defaulted_id)
self.local_instance_id = generate_local_instance_id(__file__)
self.agent_class = agent_class
self.agent_public_key = agent_public_key
self.kernel_registry = kernel_registry.agent_mapping(self.id)
self.computers = computers
self.slots = slots
self.images = {}
self.restarting_kernels = {}
self.stat_ctx = StatContext(
self,
mode=StatModes(local_config.container.stats_type.value)
if local_config.container.stats_type
else None,
)
self.timer_tasks = []
self.port_pool = set(
range(
local_config.container.port_range[0],
local_config.container.port_range[1] + 1,
)
)
self.stats_monitor = stats_monitor
self.error_monitor = error_monitor
self._pending_creation_tasks = defaultdict(set)
self._ongoing_exec_batch_tasks = weakref.WeakSet()
self._ongoing_destruction_tasks = weakref.WeakValueDictionary()
self._metric_registry = CommonMetricRegistry.instance()
# Initialize health monitoring tracking maps
self._active_pulls = {}
self._active_creates = {}
self._sync_container_lifecycle_observer = SyncContainerLifecycleObserver.instance()
self._clean_kernel_registry_task = asyncio.create_task(self._clean_kernel_registry_loop())
async def __ainit__(self) -> None:
"""
An implementation of AbstractAgent would define its own ``__ainit__()`` method.
It must call this super method in an appropriate order, only once.
"""
self.resource_lock = asyncio.Lock()
self.registry_lock = asyncio.Lock()
self.container_lifecycle_queue = asyncio.Queue()
if self.local_config.redis is None:
raise ConfigurationError({
"AbstractAgent.__ainit__": "Redis runtime configuration is not set."
})
redis_profile_target = self.local_config.redis.to_redis_profile_target()
stream_redis_target = redis_profile_target.profile_target(RedisRole.STREAM)
mq = await self._make_message_queue(stream_redis_target)
self.event_producer = EventProducer(
mq,
source=self.id,
log_events=self.local_config.debug.log_events,
)
self.event_dispatcher = EventDispatcher(
mq,
log_events=self.local_config.debug.log_events,
event_observer=self._metric_registry.event,
)
self.valkey_container_log_client = await ValkeyContainerLogClient.create(
redis_profile_target.profile_target(RedisRole.CONTAINER_LOG).to_valkey_target(),
human_readable_name="agent.container_log",
db_id=REDIS_CONTAINER_LOG,
)
self.valkey_stream_client = await ValkeyStreamClient.create(
redis_profile_target.profile_target(RedisRole.STREAM).to_valkey_target(),
human_readable_name="event_producer.stream",
db_id=REDIS_STREAM_DB,
)
self.valkey_stat_client = await ValkeyStatClient.create(
redis_profile_target.profile_target(RedisRole.STATISTICS).to_valkey_target(),
human_readable_name="agent.stat",
db_id=REDIS_STATISTICS_DB,
)
self.valkey_bgtask_client = await ValkeyBgtaskClient.create(
redis_profile_target.profile_target(RedisRole.BGTASK).to_valkey_target(),
human_readable_name="agent.bgtask",
db_id=REDIS_BGTASK_DB,
)
self.valkey_image_client = await ValkeyImageClient.create(
redis_profile_target.profile_target(RedisRole.IMAGE).to_valkey_target(),
human_readable_name="agent.image",
db_id=REDIS_IMAGE_DB,
)
self.valkey_schedule_client = await ValkeyScheduleClient.create(