-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathmodels.py
1660 lines (1424 loc) · 59.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from itertools import cycle
from time import sleep
from typing import Any, Dict, List, Tuple, Optional, Set
import datetime
import time
import logging
import threading
import dateutil.parser
from sys import platform
from moto.core import BaseBackend, BackendDict, BaseModel, CloudFormationModel
from moto.iam.models import iam_backends, IAMBackend
from moto.ec2.models import ec2_backends, EC2Backend
from moto.ec2.models.instances import Instance
from moto.ecs.models import ecs_backends, EC2ContainerServiceBackend
from moto.logs.models import logs_backends, LogsBackend
from moto.utilities.tagging_service import TaggingService
from .exceptions import InvalidParameterValueException, ClientException, ValidationError
from .utils import (
make_arn_for_compute_env,
make_arn_for_job_queue,
make_arn_for_task_def,
lowercase_first_key,
)
from moto.ec2.exceptions import InvalidSubnetIdError
from moto.ec2.models.instance_types import INSTANCE_TYPES as EC2_INSTANCE_TYPES
from moto.ec2.models.instance_types import INSTANCE_FAMILIES as EC2_INSTANCE_FAMILIES
from moto.iam.exceptions import IAMNotFoundException
from moto.core.utils import unix_time_millis
from moto.moto_api import state_manager
from moto.moto_api._internal import mock_random
from moto.moto_api._internal.managed_state_model import ManagedState
from moto.utilities.docker_utilities import DockerModel
from moto import settings
logger = logging.getLogger(__name__)
COMPUTE_ENVIRONMENT_NAME_REGEX = re.compile(
r"^[A-Za-z0-9][A-Za-z0-9_-]{1,126}[A-Za-z0-9]$"
)
def datetime2int_milliseconds(date: datetime.datetime) -> int:
"""
AWS returns timestamps in milliseconds
We don't use milliseconds timestamps internally,
this method should be used only in describe() method
"""
return int(date.timestamp() * 1000)
def datetime2int(date: datetime.datetime) -> int:
return int(time.mktime(date.timetuple()))
class ComputeEnvironment(CloudFormationModel):
def __init__(
self,
compute_environment_name: str,
_type: str,
state: str,
compute_resources: Dict[str, Any],
service_role: str,
account_id: str,
region_name: str,
):
self.name = compute_environment_name
self.env_type = _type
self.state = state
self.compute_resources = compute_resources
self.service_role = service_role
self.arn = make_arn_for_compute_env(
account_id, compute_environment_name, region_name
)
self.instances: List[Instance] = []
self.ecs_arn = ""
self.ecs_name = ""
def add_instance(self, instance: Instance) -> None:
self.instances.append(instance)
def set_ecs(self, arn: str, name: str) -> None:
self.ecs_arn = arn
self.ecs_name = name
@property
def physical_resource_id(self) -> str:
return self.arn
@staticmethod
def cloudformation_name_type() -> str:
return "ComputeEnvironmentName"
@staticmethod
def cloudformation_type() -> str:
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html
return "AWS::Batch::ComputeEnvironment"
@classmethod
def create_from_cloudformation_json( # type: ignore[misc]
cls,
resource_name: str,
cloudformation_json: Dict[str, Any],
account_id: str,
region_name: str,
**kwargs: Any,
) -> "ComputeEnvironment":
backend = batch_backends[account_id][region_name]
properties = cloudformation_json["Properties"]
env = backend.create_compute_environment(
resource_name,
properties["Type"],
properties.get("State", "ENABLED"),
lowercase_first_key(properties["ComputeResources"]),
properties["ServiceRole"],
)
arn = env[1]
return backend.get_compute_environment_by_arn(arn)
class JobQueue(CloudFormationModel):
def __init__(
self,
name: str,
priority: str,
state: str,
environments: List[ComputeEnvironment],
env_order_json: List[Dict[str, Any]],
backend: "BatchBackend",
tags: Optional[Dict[str, str]] = None,
):
"""
:param name: Job queue name
:type name: str
:param priority: Job queue priority
:type priority: int
:param state: Either ENABLED or DISABLED
:type state: str
:param environments: Compute Environments
:type environments: list of ComputeEnvironment
:param env_order_json: Compute Environments JSON for use when describing
:type env_order_json: list of dict
"""
self.name = name
self.priority = priority
self.state = state
self.environments = environments
self.env_order_json = env_order_json
self.arn = make_arn_for_job_queue(backend.account_id, name, backend.region_name)
self.status = "VALID"
self.backend = backend
if tags:
backend.tag_resource(self.arn, tags)
self.jobs: List[Job] = []
def describe(self) -> Dict[str, Any]:
return {
"computeEnvironmentOrder": self.env_order_json,
"jobQueueArn": self.arn,
"jobQueueName": self.name,
"priority": self.priority,
"state": self.state,
"status": self.status,
"tags": self.backend.list_tags_for_resource(self.arn),
}
@property
def physical_resource_id(self) -> str:
return self.arn
@staticmethod
def cloudformation_name_type() -> str:
return "JobQueueName"
@staticmethod
def cloudformation_type() -> str:
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html
return "AWS::Batch::JobQueue"
@classmethod
def create_from_cloudformation_json( # type: ignore[misc]
cls,
resource_name: str,
cloudformation_json: Dict[str, Any],
account_id: str,
region_name: str,
**kwargs: Any,
) -> "JobQueue":
backend = batch_backends[account_id][region_name]
properties = cloudformation_json["Properties"]
# Need to deal with difference case from cloudformation compute_resources, e.g. instanceRole vs InstanceRole
# Hacky fix to normalise keys, is making me think I want to start spamming cAsEiNsEnSiTiVe dictionaries
compute_envs = [
lowercase_first_key(dict_item)
for dict_item in properties["ComputeEnvironmentOrder"]
]
queue = backend.create_job_queue(
queue_name=resource_name,
priority=properties["Priority"],
state=properties.get("State", "ENABLED"),
compute_env_order=compute_envs,
)
arn = queue[1]
return backend.get_job_queue_by_arn(arn)
class JobDefinition(CloudFormationModel):
def __init__(
self,
name: str,
parameters: Optional[Dict[str, Any]],
_type: str,
container_properties: Dict[str, Any],
tags: Dict[str, str],
retry_strategy: Dict[str, str],
timeout: Dict[str, int],
backend: "BatchBackend",
platform_capabilities: List[str],
propagate_tags: bool,
revision: Optional[int] = 0,
):
self.name = name
self.retry_strategy = retry_strategy
self.type = _type
self.revision = revision or 0
self._region = backend.region_name
self.container_properties = container_properties
self.status = "ACTIVE"
self.parameters = parameters or {}
self.timeout = timeout
self.backend = backend
self.platform_capabilities = platform_capabilities
self.propagate_tags = propagate_tags
if "resourceRequirements" not in self.container_properties:
self.container_properties["resourceRequirements"] = []
if "secrets" not in self.container_properties:
self.container_properties["secrets"] = []
self._validate()
self.revision += 1
self.arn = make_arn_for_task_def(
self.backend.account_id, self.name, self.revision, self._region
)
tag_list = self._format_tags(tags or {})
# Validate the tags before proceeding.
errmsg = self.backend.tagger.validate_tags(tag_list)
if errmsg:
raise ValidationError(errmsg)
self.backend.tagger.tag_resource(self.arn, tag_list)
def _format_tags(self, tags: Dict[str, str]) -> List[Dict[str, str]]:
return [{"Key": k, "Value": v} for k, v in tags.items()]
def _get_resource_requirement(self, req_type: str, default: Any = None) -> Any:
"""
Get resource requirement from container properties.
Resource requirements like "memory" and "vcpus" are now specified in
"resourceRequirements". This function retrieves a resource requirement
from either container_properties.resourceRequirements (preferred) or
directly from container_properties (deprecated).
:param req_type: The type of resource requirement to retrieve.
:type req_type: ["gpu", "memory", "vcpus"]
:param default: The default value to return if the resource requirement is not found.
:type default: any, default=None
:return: The value of the resource requirement, or None.
:rtype: any
"""
resource_reqs = self.container_properties.get("resourceRequirements", [])
# Filter the resource requirements by the specified type.
# Note that VCPUS are specified in resourceRequirements without the
# trailing "s", so we strip that off in the comparison below.
required_resource = list(
filter(
lambda req: req["type"].lower() == req_type.lower().rstrip("s"),
resource_reqs,
)
)
if required_resource:
if req_type == "vcpus":
return float(required_resource[0]["value"])
elif req_type == "memory":
return int(required_resource[0]["value"])
else:
return required_resource[0]["value"]
else:
return self.container_properties.get(req_type, default)
def _validate(self) -> None:
# For future use when containers arnt the only thing in batch
if self.type not in ("container",):
raise ClientException('type must be one of "container"')
if not isinstance(self.parameters, dict):
raise ClientException("parameters must be a string to string map")
if "image" not in self.container_properties:
raise ClientException("containerProperties must contain image")
memory = self._get_resource_requirement("memory")
if memory is None:
raise ClientException("containerProperties must contain memory")
if memory < 4:
raise ClientException("container memory limit must be greater than 4")
vcpus = self._get_resource_requirement("vcpus")
if vcpus is None:
raise ClientException("containerProperties must contain vcpus")
if vcpus <= 0:
raise ClientException("container vcpus limit must be greater than 0")
def deregister(self) -> None:
self.status = "INACTIVE"
def update(
self,
parameters: Optional[Dict[str, Any]],
_type: str,
container_properties: Dict[str, Any],
retry_strategy: Dict[str, Any],
tags: Dict[str, str],
timeout: Dict[str, int],
) -> "JobDefinition":
if self.status != "INACTIVE":
if parameters is None:
parameters = self.parameters
if _type is None:
_type = self.type
if container_properties is None:
container_properties = self.container_properties
if retry_strategy is None:
retry_strategy = self.retry_strategy
return JobDefinition(
self.name,
parameters,
_type,
container_properties,
revision=self.revision,
retry_strategy=retry_strategy,
tags=tags,
timeout=timeout,
backend=self.backend,
platform_capabilities=self.platform_capabilities,
propagate_tags=self.propagate_tags,
)
def describe(self) -> Dict[str, Any]:
result = {
"jobDefinitionArn": self.arn,
"jobDefinitionName": self.name,
"parameters": self.parameters,
"revision": self.revision,
"status": self.status,
"type": self.type,
"tags": self.backend.tagger.get_tag_dict_for_resource(self.arn),
"platformCapabilities": self.platform_capabilities,
"retryStrategy": self.retry_strategy,
"propagateTags": self.propagate_tags,
}
if self.container_properties is not None:
result["containerProperties"] = self.container_properties
if self.timeout:
result["timeout"] = self.timeout
return result
@property
def physical_resource_id(self) -> str:
return self.arn
@staticmethod
def cloudformation_name_type() -> str:
return "JobDefinitionName"
@staticmethod
def cloudformation_type() -> str:
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html
return "AWS::Batch::JobDefinition"
@classmethod
def create_from_cloudformation_json( # type: ignore[misc]
cls,
resource_name: str,
cloudformation_json: Dict[str, Any],
account_id: str,
region_name: str,
**kwargs: Any,
) -> "JobDefinition":
backend = batch_backends[account_id][region_name]
properties = cloudformation_json["Properties"]
res = backend.register_job_definition(
def_name=resource_name,
parameters=lowercase_first_key(properties.get("Parameters", {})),
_type="container",
tags=lowercase_first_key(properties.get("Tags", {})),
retry_strategy=lowercase_first_key(properties["RetryStrategy"]),
container_properties=lowercase_first_key(properties["ContainerProperties"]),
timeout=lowercase_first_key(properties.get("timeout", {})),
platform_capabilities=None,
propagate_tags=None,
)
arn = res[1]
return backend.get_job_definition_by_arn(arn)
class Job(threading.Thread, BaseModel, DockerModel, ManagedState):
def __init__(
self,
name: str,
job_def: JobDefinition,
job_queue: JobQueue,
log_backend: LogsBackend,
container_overrides: Optional[Dict[str, Any]],
depends_on: Optional[List[Dict[str, str]]],
all_jobs: Dict[str, "Job"],
timeout: Optional[Dict[str, int]],
):
threading.Thread.__init__(self)
DockerModel.__init__(self)
ManagedState.__init__(
self,
"batch::job",
[
("SUBMITTED", "PENDING"),
("PENDING", "RUNNABLE"),
("RUNNABLE", "STARTING"),
("STARTING", "RUNNING"),
],
)
self.job_name = name
self.job_id = str(mock_random.uuid4())
self.job_definition = job_def
self.container_overrides: Dict[str, Any] = container_overrides or {}
self.job_queue = job_queue
self.job_queue.jobs.append(self)
self.job_created_at = datetime.datetime.now()
self.job_started_at = datetime.datetime(1970, 1, 1)
self.job_stopped_at = datetime.datetime(1970, 1, 1)
self.job_stopped = False
self.job_stopped_reason: Optional[str] = None
self.depends_on = depends_on
self.timeout = timeout
self.all_jobs = all_jobs
self.stop = False
self.exit_code: Optional[int] = None
self.daemon = True
self.name = "MOTO-BATCH-" + self.job_id
self._log_backend = log_backend
self.log_stream_name: Optional[str] = None
self.attempts: List[Dict[str, Any]] = []
self.latest_attempt: Optional[Dict[str, Any]] = None
def describe_short(self) -> Dict[str, Any]:
result = {
"jobId": self.job_id,
"jobName": self.job_name,
"createdAt": datetime2int_milliseconds(self.job_created_at),
"status": self.status,
"jobDefinition": self.job_definition.arn,
}
if self.job_stopped_reason is not None:
result["statusReason"] = self.job_stopped_reason
if result["status"] not in ["SUBMITTED", "PENDING", "RUNNABLE", "STARTING"]:
result["startedAt"] = datetime2int_milliseconds(self.job_started_at)
if self.job_stopped:
result["stoppedAt"] = datetime2int_milliseconds(self.job_stopped_at)
if self.exit_code is not None:
result["container"] = {"exitCode": self.exit_code}
return result
def describe(self) -> Dict[str, Any]:
result = self.describe_short()
result["jobQueue"] = self.job_queue.arn
result["dependsOn"] = self.depends_on or []
result["container"] = self._container_details()
if self.job_stopped:
result["stoppedAt"] = datetime2int_milliseconds(self.job_stopped_at)
if self.timeout:
result["timeout"] = self.timeout
result["attempts"] = self.attempts
return result
def _container_details(self) -> Dict[str, Any]:
details = {}
details["command"] = self._get_container_property("command", [])
details["privileged"] = self._get_container_property("privileged", False)
details["readonlyRootFilesystem"] = self._get_container_property(
"readonlyRootFilesystem", False
)
details["ulimits"] = self._get_container_property("ulimits", {})
details["vcpus"] = self._get_container_property("vcpus", 1)
details["memory"] = self._get_container_property("memory", 512)
details["volumes"] = self._get_container_property("volumes", [])
details["environment"] = self._get_container_property("environment", [])
if self.log_stream_name:
details["logStreamName"] = self.log_stream_name
return details
def _get_container_property(self, p: str, default: Any) -> Any:
if p == "environment":
job_env = self.container_overrides.get(p, default)
jd_env = self.job_definition.container_properties.get(p, default)
job_env_dict = {_env["name"]: _env["value"] for _env in job_env}
jd_env_dict = {_env["name"]: _env["value"] for _env in jd_env}
for key in jd_env_dict.keys():
if key not in job_env_dict.keys():
job_env.append({"name": key, "value": jd_env_dict[key]})
job_env.append({"name": "AWS_BATCH_JOB_ID", "value": self.job_id})
return job_env
if p in ["vcpus", "memory"]:
return self.container_overrides.get(
p, self.job_definition._get_resource_requirement(p, default)
)
return self.container_overrides.get(
p, self.job_definition.container_properties.get(p, default)
)
def _get_attempt_duration(self) -> Optional[int]:
if self.timeout:
return self.timeout["attemptDurationSeconds"]
if self.job_definition.timeout:
return self.job_definition.timeout["attemptDurationSeconds"]
return None
def run(self) -> None:
"""
Run the container.
Logic is as follows:
Generate container info (eventually from task definition)
Start container
Loop whilst not asked to stop and the container is running.
Get all logs from container between the last time I checked and now.
Convert logs into cloudwatch format
Put logs into cloudwatch
:return:
"""
try:
import docker
self.advance()
while self.status == "SUBMITTED":
# Wait until we've moved onto state 'PENDING'
sleep(0.5)
# Wait until all dependent jobs have finished
# If any of the dependent jobs have failed, not even start
if self.depends_on and not self._wait_for_dependencies():
return
image = self.job_definition.container_properties.get(
"image", "alpine:latest"
)
privileged = self.job_definition.container_properties.get(
"privileged", False
)
cmd = self._get_container_property(
"command",
'/bin/sh -c "for a in `seq 1 10`; do echo Hello World; sleep 1; done"',
)
environment = {
e["name"]: e["value"]
for e in self._get_container_property("environment", [])
}
volumes = {
v["name"]: v["host"]
for v in self._get_container_property("volumes", [])
}
mounts = [
docker.types.Mount(
m["containerPath"],
volumes[m["sourceVolume"]]["sourcePath"],
type="bind",
read_only=m["readOnly"],
)
for m in self._get_container_property("mountPoints", [])
]
name = "{0}-{1}".format(self.job_name, self.job_id)
self.advance()
while self.status == "PENDING":
# Wait until the state is no longer pending, but 'RUNNABLE'
sleep(0.5)
# TODO setup ecs container instance
self.job_started_at = datetime.datetime.now()
self._start_attempt()
# add host.docker.internal host on linux to emulate Mac + Windows behavior
# for communication with other mock AWS services running on localhost
extra_hosts = (
{"host.docker.internal": "host-gateway"}
if platform == "linux" or platform == "linux2"
else {}
)
environment["MOTO_HOST"] = settings.moto_server_host()
environment["MOTO_PORT"] = settings.moto_server_port()
environment[
"MOTO_HTTP_ENDPOINT"
] = f'{environment["MOTO_HOST"]}:{environment["MOTO_PORT"]}'
run_kwargs = dict()
network_name = settings.moto_network_name()
network_mode = settings.moto_network_mode()
if network_name:
run_kwargs["network"] = network_name
elif network_mode:
run_kwargs["network_mode"] = network_mode
log_config = docker.types.LogConfig(type=docker.types.LogConfig.types.JSON)
self.advance()
while self.status == "RUNNABLE":
# Wait until the state is no longer runnable, but 'STARTING'
sleep(0.5)
self.advance()
while self.status == "STARTING":
# Wait until the state is no longer runnable, but 'RUNNING'
sleep(0.5)
container = self.docker_client.containers.run(
image,
cmd,
detach=True,
name=name,
log_config=log_config,
environment=environment,
mounts=mounts,
privileged=privileged,
extra_hosts=extra_hosts,
**run_kwargs,
)
try:
container.reload()
max_time = None
if self._get_attempt_duration():
attempt_duration = self._get_attempt_duration()
max_time = self.job_started_at + datetime.timedelta(
seconds=attempt_duration # type: ignore[arg-type]
)
while container.status == "running" and not self.stop:
container.reload()
time.sleep(0.5)
if max_time and datetime.datetime.now() > max_time:
raise Exception(
"Job time exceeded the configured attemptDurationSeconds"
)
# Container should be stopped by this point... unless asked to stop
if container.status == "running":
container.kill()
# Log collection
logs_stdout = []
logs_stderr = []
logs_stderr.extend(
container.logs(
stdout=False,
stderr=True,
timestamps=True,
since=datetime2int(self.job_started_at),
)
.decode()
.split("\n")
)
logs_stdout.extend(
container.logs(
stdout=True,
stderr=False,
timestamps=True,
since=datetime2int(self.job_started_at),
)
.decode()
.split("\n")
)
# Process logs
logs_stdout = [x for x in logs_stdout if len(x) > 0]
logs_stderr = [x for x in logs_stderr if len(x) > 0]
logs = []
for line in logs_stdout + logs_stderr:
date, line = line.split(" ", 1)
date_obj = (
dateutil.parser.parse(date)
.astimezone(datetime.timezone.utc)
.replace(tzinfo=None)
)
date = unix_time_millis(date_obj)
logs.append({"timestamp": date, "message": line.strip()})
logs = sorted(logs, key=lambda l: l["timestamp"])
# Send to cloudwatch
log_group = "/aws/batch/job"
stream_name = "{0}/default/{1}".format(
self.job_definition.name, self.job_id
)
self.log_stream_name = stream_name
self._log_backend.ensure_log_group(log_group, None)
self._log_backend.create_log_stream(log_group, stream_name)
self._log_backend.put_log_events(log_group, stream_name, logs)
result = container.wait() or {}
exit_code = result.get("StatusCode", 0)
self.exit_code = exit_code
job_failed = self.stop or exit_code > 0
self._mark_stopped(success=not job_failed)
except Exception as err:
logger.error(
"Failed to run AWS Batch container {0}. Error {1}".format(
self.name, err
)
)
self._mark_stopped(success=False)
container.kill()
finally:
container.remove()
except Exception as err:
logger.error(
"Failed to run AWS Batch container {0}. Error {1}".format(
self.name, err
)
)
self._mark_stopped(success=False)
def _mark_stopped(self, success: bool = True) -> None:
# Ensure that job_stopped/job_stopped_at-attributes are set first
# The describe-method needs them immediately when status is set
self.job_stopped = True
self.job_stopped_at = datetime.datetime.now()
self.status = "SUCCEEDED" if success else "FAILED"
self._stop_attempt()
def _start_attempt(self) -> None:
self.latest_attempt = {
"container": {
"containerInstanceArn": "TBD",
"logStreamName": self.log_stream_name,
"networkInterfaces": [],
"taskArn": self.job_definition.arn,
}
}
self.latest_attempt["startedAt"] = datetime2int_milliseconds(
self.job_started_at
)
self.attempts.append(self.latest_attempt)
def _stop_attempt(self) -> None:
if self.latest_attempt:
self.latest_attempt["container"]["logStreamName"] = self.log_stream_name
self.latest_attempt["stoppedAt"] = datetime2int_milliseconds(
self.job_stopped_at
)
def terminate(self, reason: str) -> None:
if not self.stop:
self.stop = True
self.job_stopped_reason = reason
def _wait_for_dependencies(self) -> bool:
dependent_ids = [dependency["jobId"] for dependency in self.depends_on] # type: ignore[union-attr]
successful_dependencies: Set[str] = set()
while len(successful_dependencies) != len(dependent_ids):
for dependent_id in dependent_ids:
if dependent_id in self.all_jobs:
dependent_job = self.all_jobs[dependent_id]
if dependent_job.status == "SUCCEEDED":
successful_dependencies.add(dependent_id)
if dependent_job.status == "FAILED":
logger.error(
"Terminating job {0} due to failed dependency {1}".format(
self.name, dependent_job.name
)
)
self._mark_stopped(success=False)
return False
time.sleep(1)
if self.stop:
# This job has been cancelled while it was waiting for a dependency
self._mark_stopped(success=False)
return False
return True
class BatchBackend(BaseBackend):
"""
Batch-jobs are executed inside a Docker-container. Everytime the `submit_job`-method is called, a new Docker container is started.
A job is marked as 'Success' when the Docker-container exits without throwing an error.
Use `@mock_batch_simple` instead if you do not want to use a Docker-container.
With this decorator, jobs are simply marked as 'Success' without trying to execute any commands/scripts.
"""
def __init__(self, region_name: str, account_id: str):
super().__init__(region_name, account_id)
self.tagger = TaggingService()
self._compute_environments: Dict[str, ComputeEnvironment] = {}
self._job_queues: Dict[str, JobQueue] = {}
self._job_definitions: Dict[str, JobDefinition] = {}
self._jobs: Dict[str, Job] = {}
state_manager.register_default_transition(
"batch::job", transition={"progression": "manual", "times": 1}
)
@property
def iam_backend(self) -> IAMBackend:
"""
:return: IAM Backend
:rtype: moto.iam.models.IAMBackend
"""
return iam_backends[self.account_id]["global"]
@property
def ec2_backend(self) -> EC2Backend:
"""
:return: EC2 Backend
:rtype: moto.ec2.models.EC2Backend
"""
return ec2_backends[self.account_id][self.region_name]
@property
def ecs_backend(self) -> EC2ContainerServiceBackend:
"""
:return: ECS Backend
:rtype: moto.ecs.models.EC2ContainerServiceBackend
"""
return ecs_backends[self.account_id][self.region_name]
@property
def logs_backend(self) -> LogsBackend:
"""
:return: ECS Backend
:rtype: moto.logs.models.LogsBackend
"""
return logs_backends[self.account_id][self.region_name]
def reset(self) -> None:
for job in self._jobs.values():
if job.status not in ("FAILED", "SUCCEEDED"):
job.stop = True
# Try to join
job.join(0.2)
super().reset()
def get_compute_environment_by_arn(self, arn: str) -> Optional[ComputeEnvironment]:
return self._compute_environments.get(arn)
def get_compute_environment_by_name(
self, name: str
) -> Optional[ComputeEnvironment]:
for comp_env in self._compute_environments.values():
if comp_env.name == name:
return comp_env
return None
def get_compute_environment(self, identifier: str) -> Optional[ComputeEnvironment]:
"""
Get compute environment by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Compute Environment or None
:rtype: ComputeEnvironment or None
"""
return self.get_compute_environment_by_arn(
identifier
) or self.get_compute_environment_by_name(identifier)
def get_job_queue_by_arn(self, arn: str) -> Optional[JobQueue]:
return self._job_queues.get(arn)
def get_job_queue_by_name(self, name: str) -> Optional[JobQueue]:
for comp_env in self._job_queues.values():
if comp_env.name == name:
return comp_env
return None
def get_job_queue(self, identifier: str) -> Optional[JobQueue]:
"""
Get job queue by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job Queue or None
:rtype: JobQueue or None
"""
return self.get_job_queue_by_arn(identifier) or self.get_job_queue_by_name(
identifier
)
def get_job_definition_by_arn(self, arn: str) -> Optional[JobDefinition]:
return self._job_definitions.get(arn)
def get_job_definition_by_name(self, name: str) -> Optional[JobDefinition]:
latest_revision = -1
latest_job = None
for job_def in self._job_definitions.values():
if job_def.name == name and job_def.revision > latest_revision:
latest_job = job_def
latest_revision = job_def.revision
return latest_job
def get_job_definition_by_name_revision(
self, name: str, revision: str
) -> Optional[JobDefinition]:
for job_def in self._job_definitions.values():
if job_def.name == name and job_def.revision == int(revision):
return job_def
return None
def get_job_definition(self, identifier: str) -> Optional[JobDefinition]:
"""
Get job definitions by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: JobDefinition or None
"""
job_def = self.get_job_definition_by_arn(identifier)
if job_def is None:
if ":" in identifier:
job_def = self.get_job_definition_by_name_revision(
*identifier.split(":", 1)
)
else:
job_def = self.get_job_definition_by_name(identifier)
return job_def
def get_job_definitions(self, identifier: str) -> List[JobDefinition]:
"""
Get job definitions by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: list of JobDefinition
"""
result = []
env = self.get_job_definition_by_arn(identifier)
if env is not None:
result.append(env)
else:
for value in self._job_definitions.values():
if value.name == identifier:
result.append(value)
return result
def get_job_by_id(self, identifier: str) -> Optional[Job]:
try:
return self._jobs[identifier]
except KeyError:
return None
def describe_compute_environments(
self, environments: Optional[List[str]] = None