-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcontainers.py
More file actions
1766 lines (1453 loc) · 66.7 KB
/
containers.py
File metadata and controls
1766 lines (1453 loc) · 66.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
import os
import platform
import re
import stat
import sys
import json
from typing import cast
from http import HTTPStatus
from pathlib import Path
import time
from threading import RLock, Thread
import docker
from docker.errors import APIError
from docker.models.containers import Container, ExecResult
from docker.models.networks import Network
import pytest
import requests
from utils._context.component_version import ComponentVersion, Version
from utils._context.docker import get_docker_client
from utils._context.ports import ContainerPorts
from utils.proxy.tuf import get_tuf_root_json
from utils.proxy.ports import ProxyPorts
from utils.proxy.mocked_response import (
RemoveMetaStructsSupport,
MockedTracerResponse,
MockedBackendResponse,
SetSpanEventFlags,
SetClientDropP0s,
SetObfuscationVersion,
AddRemoteConfigEndpoint,
StaticJsonMockedTracerResponse,
)
from utils.proxy.rc_response_builder import (
build_rc_configurations_protobuf,
build_org_data_protobuf,
build_org_status_protobuf,
)
from utils._logger import logger
from utils._weblog import weblog
from utils import interfaces
from utils.k8s_lib_injection.k8s_weblog import K8sWeblog
from utils.interfaces._library.core import LibraryInterfaceValidator
from utils.interfaces import StdoutLogsInterface, LibraryStdoutInterface
# fake key of length 32
_FAKE_DD_API_KEY = "0123456789abcdef0123456789abcdef"
_DEFAULT_NETWORK_NAME = "system-tests_default"
_NETWORK_NAME = "bridge" if "GITLAB_CI" in os.environ else _DEFAULT_NETWORK_NAME
def create_network() -> Network:
for network in get_docker_client().networks.list(names=[_NETWORK_NAME]):
logger.debug(f"Network {_NETWORK_NAME} still exists")
return network
logger.debug(f"Create network {_NETWORK_NAME}")
return get_docker_client().networks.create(_NETWORK_NAME, check_duplicate=True)
_VOLUME_INJECTOR_NAME = "volume-inject"
def create_inject_volume():
logger.debug(f"Create volume {_VOLUME_INJECTOR_NAME}")
get_docker_client().volumes.create(_VOLUME_INJECTOR_NAME)
class TestedContainer:
_container: Container = None
_starting_lock: RLock
host_log_folder: str
# https://docker-py.readthedocs.io/en/stable/containers.html
def __init__(
self,
name: str = "",
image_name: str = "",
*,
allow_old_container: bool = False,
binary_file_name: str | None = None,
cap_add: list[str] | None = None,
command: str | list[str] | None = None,
environment: dict[str, str | None] | None = None,
healthcheck: dict | None = None,
local_image_only: bool = False,
ports: dict | None = None,
security_opt: list[str] | None = None,
stdout_interface: StdoutLogsInterface | None = None,
user: str | None = None,
volumes: dict | None = None,
working_dir: str | None = None,
pid_mode: str | None = None,
) -> None:
assert name
assert image_name
self.name = name
self.host_project_dir = os.environ.get("SYSTEM_TESTS_HOST_PROJECT_DIR", str(Path.cwd()))
self.allow_old_container = allow_old_container
self.image = ImageInfo(
self._get_image_name(binary_file_name, default_name=image_name), local_image_only=local_image_only
)
self.healthcheck = healthcheck
# healthy values:
# None: container did not tried to start yet, or hasn't be started for another reason
# False: container is not healthy
# True: container is healthy
self.healthy: bool | None = None
self.environment = environment or {}
self.volumes = volumes or {}
self.ports = ports or {}
self.depends_on: list[TestedContainer] = []
self._starting_thread: Thread | None = None
self.stdout_interface = stdout_interface
self.working_dir = working_dir
self.command = command
self.user = user
self.cap_add = cap_add
self.security_opt = security_opt
self.ulimits: list | None = None
self.privileged = False
self.pid_mode = pid_mode
def _get_image_name(self, binary_file_name: str | None, default_name: str) -> str:
# if the container provide binary_file_name, then a file named binaries/{binary_file_name}
# may exists and contains the name of the image to use for this container
if binary_file_name is None:
return default_name
try:
with open(f"binaries/{binary_file_name}", encoding="utf-8") as f:
return f.read().strip()
except FileNotFoundError:
return default_name
def enable_core_dumps(self) -> None:
"""Modify container options to enable the possibility of core dumps"""
self.cap_add = self.cap_add if self.cap_add is not None else []
if "SYS_PTRACE" not in self.cap_add:
self.cap_add.append("SYS_PTRACE")
if "SYS_ADMIN" not in self.cap_add:
self.cap_add.append("SYS_ADMIN")
self.privileged = True
self.ulimits = [docker.types.Ulimit(name="core", soft=-1, hard=-1)]
def get_image_list(self, library: str, weblog: str) -> list[str]: # noqa: ARG002
"""Returns the image list that will be loaded to be able to run/build the container"""
return [self.image.name]
def configure(self, *, host_log_folder: str, replay: bool):
self.host_log_folder = host_log_folder
if not replay:
self.stop_previous_container()
self._starting_lock = RLock()
Path(self.log_folder_path).mkdir(mode=0o777, exist_ok=True, parents=True)
Path(f"{self.log_folder_path}/logs").mkdir(mode=0o777, exist_ok=True, parents=True)
self.image.load()
self.image.save_image_info(self.log_folder_path)
else:
self.image.load_from_logs(self.log_folder_path)
if self.stdout_interface:
self.stdout_interface.configure(host_log_folder, replay=replay)
logger.info(f"Using {self.image.name} for container {self.name}")
@property
def container_name(self):
return f"system-tests-{self.name}"
@property
def log_folder_path(self):
return f"{self.host_project_dir}/{self.host_log_folder}/docker/{self.name}"
def get_existing_container(self) -> Container:
for container in get_docker_client().containers.list(all=True, filters={"name": self.container_name}):
if container.name == self.container_name:
logger.debug(f"Container {self.container_name} found")
return container
return None
def stop_previous_container(self):
if self.allow_old_container:
return
if old_container := self.get_existing_container():
logger.debug(f"Kill old container {self.container_name}")
old_container.remove(force=True)
def start(self, network: Network) -> Container:
"""Start the actual underlying Docker container directly"""
if self._container:
# container is already started, some scenarios actively starts some containers
# before calling async_start()
return
if old_container := self.get_existing_container():
if self.allow_old_container:
self._container = old_container
logger.debug(f"Use old container {self.container_name}")
old_container.restart()
return
raise ValueError("Old container still exists")
self._fix_host_pwd_in_volumes()
logger.info(f"Start container {self.container_name}")
self._container = get_docker_client().containers.run(
image=self.image.name,
name=self.container_name,
hostname=self.name,
environment=self.environment,
# auto_remove=True,
detach=True,
network=network.name,
volumes=self.volumes,
ports=self.ports,
working_dir=self.working_dir,
command=self.command,
user=self.user,
cap_add=self.cap_add,
security_opt=self.security_opt,
privileged=self.privileged,
ulimits=self.ulimits,
pid_mode=self.pid_mode,
)
self.healthy = self.wait_for_health()
if self.healthy:
self.warmup()
self._container.reload()
# with open(f"{self.log_folder_path}/container.json", "w", encoding="utf-8") as f:
# json.dump(self._container.attrs, f, indent=2)
def async_start(self, network: Network) -> Thread:
"""Start the container and its dependencies in a thread with circular dependency detection"""
self.check_circular_dependencies([])
return self.async_start_recursive(network)
def network_ipv6(self, network: Network) -> str:
self._container.reload()
return self._container.attrs["NetworkSettings"]["Networks"][network.name]["GlobalIPv6Address"]
def network_ip(self, network: Network) -> str:
self._container.reload()
return self._container.attrs["NetworkSettings"]["Networks"][network.name]["IPAddress"]
def check_circular_dependencies(self, seen: list):
"""Check if the container has a circular dependency"""
if self in seen:
dependencies = " -> ".join([s.name for s in seen] + [self.name])
raise RuntimeError(f"Circular dependency detected between containers: {dependencies}")
seen.append(self)
for dependency in self.depends_on:
dependency.check_circular_dependencies(list(seen))
def async_start_recursive(self, network: Network):
"""Recursive version of async_start for circular dependency detection"""
with self._starting_lock:
if self._starting_thread is None:
self._starting_thread = Thread(
target=self._start_with_dependencies, name=f"start_{self.name}", kwargs={"network": network}
)
self._starting_thread.start()
return self._starting_thread
def _start_with_dependencies(self, network: Network):
"""Start all dependencies of a container and then start the container"""
threads = [dependency.async_start_recursive(network) for dependency in self.depends_on]
for thread in threads:
thread.join()
for dependency in self.depends_on:
if not dependency.healthy:
return
# this function is executed in a thread
# the main thread will take care of the exception
try:
self.start(network)
except Exception as e:
logger.exception(f"Error while starting {self.name}: {e}")
self.healthy = False
def warmup(self):
"""If some stuff must be done after healthcheck"""
def post_start(self):
"""If some stuff must be done after the container is started"""
@property
def healthcheck_log_file(self):
return f"{self.log_folder_path}/healthcheck.log"
def wait_for_health(self) -> bool:
if self.healthcheck:
exit_code, output = self.execute_command(**self.healthcheck)
with open(self.healthcheck_log_file, "w", encoding="utf-8") as f:
f.write(output)
if exit_code != 0:
logger.stdout(f"Healthcheck failed for {self.name}:\n{output}")
return False
logger.info(f"Healthcheck successful for {self.name}")
return True
def exec_run(self, cmd: str, *, demux: bool = False) -> ExecResult:
return self._container.exec_run(cmd, demux=demux)
def get_archive(self, path: str):
"""Return a tar archive of a path inside the container (wraps Docker SDK get_archive)."""
return self._container.get_archive(path)
def execute_command(
self, test: str, retries: int = 10, interval: float = 1_000_000_000, start_period: float = 0
) -> tuple[int, str]:
"""Execute a command inside a container. Useful for healthcheck and warmups.
test is a command to be executed, interval, timeout and start_period are in us (microseconds)
This function does not raise any exception, it returns a tuple with the exit code and the output
The exit code is 0 (success) or any other integer (failure)
Note that timeout is not supported by the docker SDK
"""
cmd = test
if not isinstance(cmd, str):
assert cmd[0] == "CMD-SHELL", "Only CMD-SHELL is supported"
cmd = cmd[1]
interval = interval / 1_000_000_000
start_period = start_period / 1_000_000_000
if start_period:
time.sleep(start_period)
logger.info(f"Executing command {cmd} for {self.name}")
result = None
for i in range(retries + 1):
try:
result = self._container.exec_run(cmd)
logger.debug(f"Try #{i} for {self.name}: {result}")
if result.exit_code == 0:
break
except APIError as e:
logger.exception(f"Try #{i} failed")
return 1, f"Command {cmd} failed for {self._container.name}: {e.explanation}"
except Exception as e:
logger.debug(f"Try #{i}: {e}")
self._container.reload()
if self._container.status != "running":
return 1, f"Container {self._container.name} is not running"
time.sleep(interval)
if not result:
return 1, f"Command {cmd} can't be executed for {self._container.name}"
return result.exit_code, result.output.decode("utf-8")
def _fix_host_pwd_in_volumes(self):
# on docker compose, volume host path can starts with a "."
# it means the current path on host machine. It's not supported in bare docker
# replicate this behavior here
host_pwd = self.host_project_dir
result = {}
for host_path, container_path in self.volumes.items():
if host_path.startswith("./"):
corrected_host_path = f"{host_pwd}{host_path[1:]}"
result[corrected_host_path] = container_path
else:
result[host_path] = container_path
self.volumes = result
def stop(self):
self._starting_thread = None
logger.debug(f"Stopping container {self.name}")
if self._container:
self._container.reload()
if self._container.status != "running":
self.healthy = False
pytest.exit(f"Container {self.name} is not running ({self._container.status}), please check logs", 1)
self._container.stop()
if not self.healthy:
pytest.exit(f"Container {self.name} is not healthy, please check logs", 1)
def collect_logs(self):
TAIL_LIMIT = 50 # noqa: N806
SEP = "=" * 30 # noqa: N806
data = (
("stdout", self._container.logs(stdout=True, stderr=False)),
("stderr", self._container.logs(stdout=False, stderr=True)),
)
for output_name, raw_output in data:
filename = f"{self.log_folder_path}/{output_name}.log"
with open(filename, "wb") as f:
f.write(raw_output)
if not self.healthy:
decoded_output = raw_output.decode("utf-8")
logger.stdout(f"\n{SEP} {self.name} {output_name.upper()} last {TAIL_LIMIT} lines {SEP}")
logger.stdout(f"-> See {filename} for full logs")
logger.stdout("")
# print last <tail> lines in stdout
logger.stdout("\n".join(decoded_output.splitlines()[-TAIL_LIMIT:]))
logger.stdout("")
def remove(self):
logger.debug(f"Removing container {self.name}")
if self._container:
try:
# collect logs before removing
self.collect_logs()
self._container.remove(force=True)
except APIError as e:
# Sometimes, the container does not exists.
# We can safely ignore this, because if it's another issue
# it will be killed at startup
logger.info(f"Fail to remove container {self.name} ({e})")
if self.stdout_interface is not None:
self.stdout_interface.load_data()
def _set_aws_auth_environment(self):
# Set default AWS values
if "AWS_REGION" not in self.environment:
self.environment["AWS_REGION"] = "us-east-1"
self.environment["AWS_DEFAULT_REGION"] = "us-east-1"
if "AWS_SECRET_ACCESS_KEY" not in self.environment:
self.environment["AWS_SECRET_ACCESS_KEY"] = "not-secret" # noqa: S105
if "AWS_ACCESS_KEY_ID" not in self.environment:
self.environment["AWS_ACCESS_KEY_ID"] = "not-secret"
class SqlDbTestedContainer(TestedContainer):
def __init__(
self,
name: str,
*,
image_name: str,
db_user: str,
environment: dict[str, str | None] | None = None,
allow_old_container: bool = False,
healthcheck: dict | None = None,
stdout_interface: StdoutLogsInterface | None = None,
command: str | None = None,
ports: dict | None = None,
user: str | None = None,
volumes: dict | None = None,
cap_add: list[str] | None = None,
db_password: str | None = None,
db_instance: str | None = None,
db_host: str | None = None,
dd_integration_service: str | None = None,
) -> None:
super().__init__(
image_name=image_name,
name=name,
environment=environment,
stdout_interface=stdout_interface,
healthcheck=healthcheck,
allow_old_container=allow_old_container,
ports=ports,
command=command,
user=user,
volumes=volumes,
cap_add=cap_add,
)
self.dd_integration_service = dd_integration_service
self.db_user = db_user
self.db_password = db_password
self.db_host = db_host
self.db_instance = db_instance
class ImageInfo:
"""data on docker image. data comes from `docker inspect`"""
def __init__(self, image_name: str, *, local_image_only: bool):
# local_image_only: boolean
# True if the image is only available locally and can't be loaded from any hub
self.env: dict[str, str] | None = None
self.labels: dict[str, str] = {}
self.name = image_name
self.local_image_only = local_image_only
def _pull_with_retries(self, max_retries: int = 4, delay: int = 4):
"""Pull a docker image with retries on transient errors (500s, timeouts, etc.)."""
for attempt in range(max_retries):
try:
kwargs: dict[str, str] = {}
if sys.platform == "darwin" and platform.machine() == "arm64":
kwargs["platform"] = "linux/amd64"
return get_docker_client().images.pull(self.name, **kwargs)
except (docker.errors.APIError, requests.exceptions.ConnectionError) as e:
if attempt < max_retries - 1:
logger.stdout(f"Failed to pull {self.name} (attempt {attempt + 1}/{max_retries}): {e}")
time.sleep(delay)
delay *= 2
else:
raise
return None # unreachable, but satisfies linter
def load(self):
try:
self._image = get_docker_client().images.get(self.name)
except docker.errors.ImageNotFound:
if self.local_image_only:
pytest.exit(f"Image {self.name} not found locally, please build it", 1)
logger.stdout(f"Pulling {self.name}")
self._image = self._pull_with_retries()
self._init_from_attrs(self._image.attrs)
def load_from_logs(self, dir_path: str):
with open(f"{dir_path}/image.json", encoding="utf-8") as f:
attrs = json.load(f)
self._init_from_attrs(attrs)
def _init_from_attrs(self, attrs: dict):
self.env = {}
if attrs["Config"].get("Env"):
for var in attrs["Config"]["Env"]:
key, value = var.split("=", 1)
if value:
self.env[key] = value
if "Labels" in attrs["Config"]:
self.labels = attrs["Config"]["Labels"]
def save_image_info(self, dir_path: str):
with open(f"{dir_path}/image.json", encoding="utf-8", mode="w") as f:
json.dump(self._image.attrs, f, indent=2)
class ProxyContainer(TestedContainer):
def __init__(
self,
*,
rc_api_enabled: bool,
rc_backend_enabled: bool = False,
meta_structs_disabled: bool,
span_events: bool,
client_drop_p0s: bool | None = None,
obfuscation_version: int | None = None,
enable_ipv6: bool,
mocked_backend: bool = True,
) -> None:
"""Parameters:
span_events: Whether the agent supports the native serialization of span events
rc_backend_enabled: Whether to act as backend for core agent (instead of mocking tracer RC)
"""
if rc_api_enabled and not mocked_backend:
raise ValueError("rc_backend_enabled requires mocked_backend")
# Adjust healthcheck for IPv6 scenarios
host_target = "::1" if enable_ipv6 else "localhost"
socket_family = "socket.AF_INET6" if enable_ipv6 else "socket.AF_INET"
super().__init__(
image_name="datadog/system-tests:proxy-v1",
name="proxy",
environment={
"DD_SITE": os.environ.get("DD_SITE"),
"DD_API_KEY": os.environ.get("DD_API_KEY", _FAKE_DD_API_KEY),
"DD_APP_KEY": os.environ.get("DD_APP_KEY"),
"SYSTEM_TESTS_IPV6": str(enable_ipv6),
"SYSTEM_TESTS_MOCKED_BACKEND": str(mocked_backend),
},
working_dir="/app",
volumes={
"./utils/proxy": {"bind": "/app/proxy", "mode": "ro"},
},
ports={f"{ProxyPorts.proxy_commands}/tcp": ("127.0.0.1", ProxyPorts.proxy_commands)},
command="python -m proxy.core",
healthcheck={
"test": f"python -c \"import socket; s=socket.socket({socket_family}); s.settimeout(2); s.connect(('{host_target}', {ProxyPorts.weblog})); s.close()\"", # noqa: E501
"retries": 30,
},
)
self.internal_mocked_tracer_responses: list[MockedTracerResponse] = [SetSpanEventFlags(span_events=span_events)]
if meta_structs_disabled:
self.internal_mocked_tracer_responses.append(RemoveMetaStructsSupport())
if client_drop_p0s is not None:
self.internal_mocked_tracer_responses.append(SetClientDropP0s(client_drop_p0s=client_drop_p0s))
if obfuscation_version is not None:
self.internal_mocked_tracer_responses.append(SetObfuscationVersion(obfuscation_version=obfuscation_version))
if rc_api_enabled:
# add the remote config endpoint on available agent endpoints
self.internal_mocked_tracer_responses.append(AddRemoteConfigEndpoint())
# Only add static tracer-facing RC mock if NOT in backend mode
# In backend mode, tracer requests pass through to agent
if not rc_backend_enabled:
self.internal_mocked_tracer_responses.append(
StaticJsonMockedTracerResponse(path="/v0.7/config", mocked_json={})
)
# Backend mocked responses (create responses from scratch)
self.internal_mocked_backend_responses: list[MockedBackendResponse] = []
if rc_backend_enabled:
# Set up internal backend mocks for backend endpoints
self.internal_mocked_backend_responses = [
MockedBackendResponse(
path="/api/v0.1/org",
content=build_org_data_protobuf(),
content_type="application/x-protobuf",
),
MockedBackendResponse(
path="/api/v0.1/status",
content=build_org_status_protobuf(),
content_type="application/x-protobuf",
),
MockedBackendResponse(
path="/api/v0.2/echo-test",
content=b"ok",
content_type="text/plain",
),
MockedBackendResponse(
path="/api/v0.1/configurations",
content=build_rc_configurations_protobuf(None),
content_type="application/x-protobuf",
),
]
self.mocked_backend = mocked_backend
def configure(self, *, host_log_folder: str, replay: bool):
super().configure(host_log_folder=host_log_folder, replay=replay)
# Write tracer mocked responses JSON
tracer_mocks_path = f"{self.log_folder_path}/{MockedTracerResponse.internal_filename}"
with Path(tracer_mocks_path).open(encoding="utf-8", mode="w") as f:
json.dump([resp.to_json() for resp in self.internal_mocked_tracer_responses], f, indent=2)
# Write backend mocked responses JSON
backend_mocks_path = f"{self.log_folder_path}/{MockedBackendResponse.internal_filename}"
with Path(backend_mocks_path).open(encoding="utf-8", mode="w") as f:
json.dump([resp.to_json() for resp in self.internal_mocked_backend_responses], f, indent=2)
# in any info printed in stdout, log filename should be the same as the host.
# In the host, they are accessible in ./logs_<scenario_name>
# In proxy container, since only the container code is mounted in /app/proxy, and the working dir is /app,
# we need to mount the log folder in /app/logs_<scenario_name>, and give this name to the proxy.
# With that, the proxy will save all files as "./logs_<scenario_name>/...", which can be readed directly
# in the host from the root of system-tests
self.environment["SYSTEM_TESTS_LOG_FOLDER"] = f"./{host_log_folder}"
self.volumes[f"./{host_log_folder}/interfaces/"] = {"bind": f"/app/{host_log_folder}/interfaces", "mode": "rw"}
# mount mocked responses valid for the entire scenario
self.volumes[tracer_mocks_path] = {"bind": f"/app/logs/{MockedTracerResponse.internal_filename}", "mode": "ro"}
self.volumes[backend_mocks_path] = {
"bind": f"/app/logs/{MockedBackendResponse.internal_filename}",
"mode": "ro",
}
class LambdaProxyContainer(TestedContainer):
def __init__(
self,
*,
lambda_weblog_host: str,
lambda_weblog_port: str,
) -> None:
self.host_port = weblog.port
self.container_port = "7777"
super().__init__(
image_name="datadog/system-tests:lambda-proxy-v1",
name="lambda-proxy",
environment={
"RIE_HOST": lambda_weblog_host,
"RIE_PORT": lambda_weblog_port,
},
volumes={"./utils/build/docker/lambda_proxy": {"bind": "/app", "mode": "ro"}},
ports={
f"{self.host_port}/tcp": self.container_port,
},
healthcheck={
"test": f"curl --fail --silent --show-error --max-time 2 localhost:{self.container_port}/healthcheck",
"retries": 60,
},
)
def post_start(self):
super().post_start()
logger.stdout(f"Proxied event type: {self.environment.get('LAMBDA_EVENT_TYPE')}")
class AgentContainer(TestedContainer):
apm_receiver_port: int = 8127
dogstatsd_port: int = 8125
agent_version: Version
def __init__(
self,
*,
use_proxy: bool = True,
rc_backend_enabled: bool = False,
environment: dict[str, str | None] | None = None,
) -> None:
environment = environment or {}
environment.update(
{
"DD_ENV": "system-tests",
"DD_HOSTNAME": "test",
"DD_SITE": self.dd_site,
"DD_APM_RECEIVER_PORT": str(self.apm_receiver_port),
"DD_DOGSTATSD_PORT": str(self.dogstatsd_port),
"DD_API_KEY": os.environ.get("DD_API_KEY", _FAKE_DD_API_KEY),
}
)
if use_proxy:
environment["DD_PROXY_HTTPS"] = f"http://proxy:{ProxyPorts.agent}"
environment["DD_PROXY_HTTP"] = f"http://proxy:{ProxyPorts.agent}"
# Configure backend mode via environment variables
# Agent uses HTTP_PROXY to reach backend, TUF roots validate RC responses
# We set RC_DD_URL to a fake hostname - HTTP_PROXY will intercept it on the agent port
if rc_backend_enabled:
tuf_root_json = get_tuf_root_json()
environment["DD_REMOTE_CONFIGURATION_ENABLED"] = "true"
environment["DD_REMOTE_CONFIGURATION_REFRESH_INTERVAL"] = "5s"
environment["DD_REMOTE_CONFIGURATION_NO_TLS"] = "true"
environment["DD_REMOTE_CONFIGURATION_CONFIG_ROOT"] = tuf_root_json
environment["DD_REMOTE_CONFIGURATION_DIRECTOR_ROOT"] = tuf_root_json
super().__init__(
name="agent",
image_name="datadog/agent:latest",
binary_file_name="agent-image",
environment=environment,
healthcheck={
"test": f"curl --fail --silent --show-error --max-time 2 http://localhost:{self.apm_receiver_port}/info",
"retries": 60,
},
stdout_interface=interfaces.agent_stdout,
volumes={
# this certificate comes from utils/proxy/.mitmproxy/mitmproxy-ca-cert.cer
"./utils/build/docker/agent/ca-certificates.crt": {
"bind": "/etc/ssl/certs/ca-certificates.crt",
"mode": "ro",
},
"./utils/build/docker/agent/datadog.yaml": {"bind": "/etc/datadog-agent/datadog.yaml", "mode": "ro"},
},
)
def post_start(self):
with open(self.healthcheck_log_file, encoding="utf-8") as f:
data = json.load(f)
self.agent_version = ComponentVersion("agent", data["version"]).version
logger.stdout(f"Agent: {self.agent_version}")
logger.stdout(f"Backend: {self.dd_site}")
@property
def dd_site(self):
return os.environ.get("DD_SITE", "datad0g.com")
class BuddyContainer(TestedContainer):
def __init__(
self,
name: str,
image_name: str,
host_port: int,
trace_agent_port: int,
environment: dict[str, str | None],
) -> None:
super().__init__(
name=name,
image_name=image_name,
healthcheck={"test": "curl --fail --silent --show-error --max-time 2 localhost:7777", "retries": 60},
ports={"7777/tcp": host_port},
environment={
**environment,
"DD_SERVICE": name,
"DD_ENV": "system-tests",
"DD_VERSION": "1.0.0",
# "DD_TRACE_DEBUG": "true",
"DD_AGENT_HOST": "proxy",
"DD_TRACE_AGENT_PORT": str(trace_agent_port),
"SYSTEM_TESTS_AWS_URL": "http://localstack-main:4566",
},
)
self._set_aws_auth_environment()
@property
def interface(self) -> LibraryInterfaceValidator:
result = getattr(interfaces, self.name)
assert result is not None, "Interface is not set"
return result
class WeblogContainer(TestedContainer):
appsec_rules_file: str | None
stdout_interface: LibraryStdoutInterface
def __init__(
self,
*,
environment: dict[str, str | None] | None = None,
tracer_sampling_rate: float | None = None,
appsec_enabled: bool = True,
iast_enabled: bool = True,
runtime_metrics_enabled: bool = False,
additional_trace_header_tags: tuple[str, ...] = (),
use_proxy: bool = True,
volumes: dict | None = None,
) -> None:
self.host_port = weblog.port
self.container_port = 7777
self.host_grpc_port = weblog.grpc_port
self.container_grpc_port = 7778
volumes = {} if volumes is None else volumes
base_environment: dict[str, str | None] = {
# Datadog setup
"DD_SERVICE": "weblog",
"DD_VERSION": "1.0.0",
"DD_TAGS": "key1:val1,key2:val2",
"DD_ENV": "system-tests",
"DD_TRACE_LOG_DIRECTORY": "/var/log/system-tests",
# for remote configuration tests
"DD_RC_TUF_ROOT": get_tuf_root_json(),
}
# Basic env set for all scenarios
base_environment["DD_TELEMETRY_METRICS_ENABLED"] = "true"
base_environment["DD_TELEMETRY_HEARTBEAT_INTERVAL"] = self.telemetry_heartbeat_interval
# Python lib has different env var until we enable Telemetry Metrics by default
base_environment["_DD_TELEMETRY_METRICS_ENABLED"] = "true"
base_environment["DD_TELEMETRY_METRICS_INTERVAL_SECONDS"] = self.telemetry_heartbeat_interval
if runtime_metrics_enabled:
base_environment["DD_RUNTIME_METRICS_ENABLED"] = "true"
if appsec_enabled:
base_environment["DD_APPSEC_ENABLED"] = "true"
base_environment["DD_APPSEC_WAF_TIMEOUT"] = "10000000" # 10 seconds
base_environment["DD_APPSEC_TRACE_RATE_LIMIT"] = "10000"
if iast_enabled:
base_environment["DD_IAST_ENABLED"] = "true"
# Python lib has Code Security debug env var
base_environment["_DD_IAST_DEBUG"] = "true"
base_environment["DD_IAST_REQUEST_SAMPLING"] = "100"
base_environment["DD_IAST_MAX_CONCURRENT_REQUESTS"] = "10"
base_environment["DD_IAST_DEDUPLICATION_ENABLED"] = "false"
base_environment["DD_IAST_VULNERABILITIES_PER_REQUEST"] = "10"
base_environment["DD_IAST_MAX_CONTEXT_OPERATIONS"] = "10"
if tracer_sampling_rate:
base_environment["DD_TRACE_SAMPLE_RATE"] = str(tracer_sampling_rate)
base_environment["DD_TRACE_SAMPLING_RULES"] = json.dumps([{"sample_rate": tracer_sampling_rate}])
if use_proxy:
# set the tracer to send data to runner (it will forward them to the agent)
base_environment["DD_AGENT_HOST"] = "proxy"
base_environment["DD_TRACE_AGENT_PORT"] = self.trace_agent_port
else:
base_environment["DD_AGENT_HOST"] = "agent"
base_environment["DD_TRACE_AGENT_PORT"] = str(AgentContainer.apm_receiver_port)
# overwrite values with those set in the scenario
environment = base_environment | (environment or {})
super().__init__(
image_name="system_tests/weblog",
name="weblog",
environment=environment,
volumes=volumes,
# ddprof's perf event open is blocked by default by docker's seccomp profile
# This is worse than the line above though prevents mmap bugs locally
security_opt=["seccomp=unconfined"],
healthcheck={
"test": f"curl --fail --silent --show-error --max-time 2 localhost:{self.container_port}/healthcheck",
"retries": 60,
},
ports={
f"{self.host_port}/tcp": self.container_port,
f"{self.host_grpc_port}/tcp": self.container_grpc_port,
},
stdout_interface=interfaces.library_stdout,
local_image_only=True,
command="./app.sh",
)
self.tracer_sampling_rate = tracer_sampling_rate
self.additional_trace_header_tags = additional_trace_header_tags
self.weblog_variant = ""
self._library: ComponentVersion | None = None
@property
def trace_agent_port(self):
return ProxyPorts.weblog
@staticmethod
def _get_image_list_from_dockerfile(dockerfile: str) -> list[str]:
result = []
pattern = re.compile(r"FROM\s+(?P<image_name>[^ ]+)")
with open(dockerfile, encoding="utf-8") as f:
for line in f:
if match := pattern.match(line):
result.append(match.group("image_name"))
return result
def get_image_list(self, library: str | None, weblog: str | None) -> list[str]:
"""Returns images needed to build the weblog"""
# If an image is saved as a file in binaries, we don't need any image
filename = f"binaries/{library}-{weblog}-weblog.tar.gz"
if Path(filename).is_file():
return []
# else, parse the Dockerfile and extract all images reference in a FROM section"""
result: list[str] = []
if not library or not weblog:
return result
args = {}
pattern = re.compile(r"^FROM\s+(?P<image_name>[^\s]+)")
arg_pattern = re.compile(r"^ARG\s+(?P<arg_name>[^\s]+)\s*=\s*(?P<arg_value>[^\s]+)")
with open(f"utils/build/docker/{library}/{weblog}.Dockerfile", encoding="utf-8") as f:
for line in f:
if match := arg_pattern.match(line):
args[match.group("arg_name")] = match.group("arg_value")
if match := pattern.match(line):
image_name = match.group("image_name")
for name, value in args.items():
image_name = image_name.replace(f"${name}", value)