-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathcontroller.py
More file actions
1244 lines (1030 loc) · 46.2 KB
/
controller.py
File metadata and controls
1244 lines (1030 loc) · 46.2 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 ipaddress
import json
import logging
import multiprocessing
import os
import pathlib
import socket
import stat
import subprocess
import uuid
from abc import ABC, abstractmethod
from types import MappingProxyType
from typing import Any
from clp_py_utils.clp_config import (
API_SERVER_COMPONENT_NAME,
AwsAuthType,
BundledService,
CLP_DB_PASS_ENV_VAR_NAME,
CLP_DB_ROOT_PASS_ENV_VAR_NAME,
CLP_DB_ROOT_USER_ENV_VAR_NAME,
CLP_DB_USER_ENV_VAR_NAME,
CLP_QUEUE_PASS_ENV_VAR_NAME,
CLP_QUEUE_USER_ENV_VAR_NAME,
CLP_REDIS_PASS_ENV_VAR_NAME,
ClpConfig,
ClpDbNameType,
ClpDbUserType,
COMPRESSION_JOBS_TABLE_NAME,
COMPRESSION_SCHEDULER_COMPONENT_NAME,
COMPRESSION_WORKER_COMPONENT_NAME,
CONTAINER_INPUT_LOGS_ROOT_DIR,
DatabaseEngine,
DB_COMPONENT_NAME,
DeploymentType,
GARBAGE_COLLECTOR_COMPONENT_NAME,
LOG_INGESTOR_COMPONENT_NAME,
MCP_SERVER_COMPONENT_NAME,
OrchestrationType,
QUERY_JOBS_TABLE_NAME,
QUERY_SCHEDULER_COMPONENT_NAME,
QUERY_WORKER_COMPONENT_NAME,
QueryEngine,
QUEUE_COMPONENT_NAME,
REDIS_COMPONENT_NAME,
REDUCER_COMPONENT_NAME,
RESULTS_CACHE_COMPONENT_NAME,
SPIDER_DB_PASS_ENV_VAR_NAME,
SPIDER_DB_USER_ENV_VAR_NAME,
SPIDER_SCHEDULER_COMPONENT_NAME,
StorageEngine,
StorageType,
WEBUI_COMPONENT_NAME,
)
from clp_py_utils.clp_metadata_db_utils import (
get_archives_table_name,
get_datasets_table_name,
get_files_table_name,
)
from clp_py_utils.core import resolve_host_path_in_container
from clp_package_utils.general import (
check_docker_dependencies,
CONTAINER_CLP_HOME,
DockerComposeProjectNotRunningError,
DockerDependencyError,
dump_shared_container_config,
generate_docker_compose_container_config,
get_clp_home,
is_retention_period_configured,
validate_db_config,
validate_mcp_server_config,
validate_queue_config,
validate_redis_config,
validate_results_cache_config,
validate_webui_config,
)
LOG_FILE_ACCESS_MODE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
DEFAULT_UID_GID = f"{os.getuid()}:{os.getgid()}"
THIRD_PARTY_SERVICE_UID = 999
THIRD_PARTY_SERVICE_GID = 999
THIRD_PARTY_SERVICE_UID_GID = f"{THIRD_PARTY_SERVICE_UID}:{THIRD_PARTY_SERVICE_GID}"
logger = logging.getLogger(__name__)
class EnvVarsDict(dict[str, str | None]):
def __ior__(self, other: "EnvVarsDict") -> "EnvVarsDict":
"""
Overloads the `|=` operator for static type checking on `other`.
"""
super().__ior__(other)
return self
class BaseController(ABC):
"""
Base controller for orchestrating CLP components. Derived classes should implement any
orchestrator-specific logic. This class provides common logic for preparing environment
variables, directories, and configuration files for each component.
"""
def __init__(self, clp_config: ClpConfig) -> None:
self._clp_config = clp_config
self._clp_home = get_clp_home()
self._conf_dir = self._clp_home / "etc"
@abstractmethod
def set_up_env(self) -> None:
"""
Sets up all components to run by preparing environment variables, directories, and
configuration files.
"""
@abstractmethod
def start(self) -> None:
"""
Starts the components.
"""
@abstractmethod
def stop(self) -> None:
"""
Stops the components.
"""
def _set_up_env_for_database_bundling(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for bundling the database component.
:return: Dictionary of environment variables necessary to bundle the component.
"""
component_name = DB_COMPONENT_NAME
if BundledService.DATABASE not in self._clp_config.bundled:
logger.info(
"%s is not included in the 'bundled' configuration, skipping service bundling...",
component_name,
)
# Bundling
return EnvVarsDict({"CLP_DATABASE_ENABLED": "0"})
logger.info("Setting up environment for bundling %s...", component_name)
conf_logging_file = self._conf_dir / "mysql" / "conf.d" / "logging.cnf"
data_dir = self._clp_config.data_directory / component_name
logs_dir = self._clp_config.logs_directory / component_name
validate_db_config(self._clp_config, conf_logging_file, data_dir, logs_dir)
resolved_data_dir = resolve_host_path_in_container(data_dir)
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_data_dir.mkdir(exist_ok=True, parents=True)
resolved_logs_dir.mkdir(exist_ok=True, parents=True)
_chown_paths_if_root(resolved_data_dir, resolved_logs_dir)
env_vars = EnvVarsDict()
# Paths
env_vars |= {
"CLP_DB_CONF_LOGGING_FILE_HOST": str(conf_logging_file),
"CLP_DB_DATA_DIR_HOST": str(data_dir),
"CLP_DB_LOGS_DIR_HOST": str(logs_dir),
}
# Runtime config
env_vars |= {
"CLP_DB_CONTAINER_IMAGE_REF": (
"mysql:8.0.23"
if self._clp_config.database.type == DatabaseEngine.MYSQL
else "mariadb:10-jammy"
),
}
return env_vars
def _set_up_env_for_database(self) -> EnvVarsDict:
"""
Sets up environment variables for the database component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = DB_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"CLP_DB_NAME": self._clp_config.database.names[ClpDbNameType.CLP],
}
if self._clp_config.compression_scheduler.type == OrchestrationType.SPIDER:
env_vars["SPIDER_DB_NAME"] = self._clp_config.database.names[ClpDbNameType.SPIDER]
if BundledService.DATABASE not in self._clp_config.bundled:
env_vars |= {
"CLP_DB_CONNECT_PORT": str(self._clp_config.database.port),
"CLP_EXTRA_HOST_DATABASE_NAME": DB_COMPONENT_NAME,
"CLP_EXTRA_HOST_DATABASE_ADDR": _resolve_external_host(
self._clp_config.database.host
),
}
else:
env_vars |= {
"CLP_DB_HOST": _get_ip_from_hostname(self._clp_config.database.host),
"CLP_DB_PORT": str(self._clp_config.database.port),
}
# Credentials
credentials = self._clp_config.database.credentials
env_vars |= {
CLP_DB_PASS_ENV_VAR_NAME: credentials[ClpDbUserType.CLP].password,
CLP_DB_ROOT_PASS_ENV_VAR_NAME: credentials[ClpDbUserType.ROOT].password,
SPIDER_DB_PASS_ENV_VAR_NAME: credentials[ClpDbUserType.SPIDER].password,
CLP_DB_ROOT_USER_ENV_VAR_NAME: credentials[ClpDbUserType.ROOT].username,
CLP_DB_USER_ENV_VAR_NAME: credentials[ClpDbUserType.CLP].username,
SPIDER_DB_USER_ENV_VAR_NAME: credentials[ClpDbUserType.SPIDER].username,
}
return env_vars
def _set_up_env_for_queue_bundling(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for bundling the queue component.
:return: Dictionary of environment variables necessary to bundle the component.
"""
component_name = QUEUE_COMPONENT_NAME
if self._clp_config.queue is None or BundledService.QUEUE not in self._clp_config.bundled:
logger.info(
"%s is not configured or part of the 'bundled' configuration, skipping "
"service bundling...",
component_name,
)
# Bundling
return EnvVarsDict({"CLP_QUEUE_ENABLED": "0"})
logger.info("Setting up environment for bundling %s...", component_name)
logs_dir = self._clp_config.logs_directory / component_name
validate_queue_config(self._clp_config, logs_dir)
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(exist_ok=True, parents=True)
_chown_paths_if_root(resolved_logs_dir)
env_vars = EnvVarsDict()
# Paths
env_vars |= {
"CLP_QUEUE_LOGS_DIR_HOST": str(logs_dir),
}
return env_vars
def _set_up_env_for_queue(self) -> EnvVarsDict:
"""
Sets up environment variables for the message queue component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = QUEUE_COMPONENT_NAME
if self._clp_config.queue is None:
logger.info(
"%s is not configured, skipping environment setup...",
component_name,
)
return EnvVarsDict()
logger.info(f"Setting up environment for {component_name}...")
env_vars = EnvVarsDict()
# Connection config
if BundledService.QUEUE not in self._clp_config.bundled:
env_vars |= {
"CLP_QUEUE_CONNECT_PORT": str(self._clp_config.queue.port),
"CLP_EXTRA_HOST_QUEUE_NAME": QUEUE_COMPONENT_NAME,
"CLP_EXTRA_HOST_QUEUE_ADDR": _resolve_external_host(self._clp_config.queue.host),
}
else:
env_vars |= {
"CLP_QUEUE_HOST": _get_ip_from_hostname(self._clp_config.queue.host),
"CLP_QUEUE_PORT": str(self._clp_config.queue.port),
}
# Credentials
env_vars |= {
CLP_QUEUE_PASS_ENV_VAR_NAME: self._clp_config.queue.password,
CLP_QUEUE_USER_ENV_VAR_NAME: self._clp_config.queue.username,
}
return env_vars
def _set_up_env_for_redis_bundling(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for bundling the redis component.
:return: Dictionary of environment variables necessary to bundle the component.
"""
component_name = REDIS_COMPONENT_NAME
if self._clp_config.redis is None or BundledService.REDIS not in self._clp_config.bundled:
logger.info(
"%s is not configured or part of the 'bundled' configuration, skipping "
"service bundling...",
component_name,
)
# Bundling
return EnvVarsDict({"CLP_REDIS_ENABLED": "0"})
logger.info("Setting up environment for bundling %s...", component_name)
conf_file = self._conf_dir / "redis" / "redis.conf"
data_dir = self._clp_config.data_directory / component_name
logs_dir = self._clp_config.logs_directory / component_name
validate_redis_config(self._clp_config, conf_file, data_dir, logs_dir)
resolved_data_dir = resolve_host_path_in_container(data_dir)
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_data_dir.mkdir(exist_ok=True, parents=True)
resolved_logs_dir.mkdir(exist_ok=True, parents=True)
_chown_paths_if_root(resolved_data_dir, resolved_logs_dir)
env_vars = EnvVarsDict()
# Backend databases
env_vars |= {
"CLP_REDIS_BACKEND_DB_COMPRESSION": str(
self._clp_config.redis.compression_backend_database
),
"CLP_REDIS_BACKEND_DB_QUERY": str(self._clp_config.redis.query_backend_database),
}
# Paths
env_vars |= {
"CLP_REDIS_CONF_FILE_HOST": str(conf_file),
"CLP_REDIS_DATA_DIR_HOST": str(data_dir),
"CLP_REDIS_LOGS_DIR_HOST": str(logs_dir),
}
return env_vars
def _set_up_env_for_redis(self) -> EnvVarsDict:
"""
Sets up environment variables for the Redis component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = REDIS_COMPONENT_NAME
if self._clp_config.redis is None:
logger.info(
"%s is not configured, skipping environment setup...",
component_name,
)
return EnvVarsDict()
logger.info(f"Setting up environment for {component_name}...")
env_vars = EnvVarsDict()
# Connection config
if BundledService.REDIS not in self._clp_config.bundled:
env_vars |= {
"CLP_REDIS_CONNECT_PORT": str(self._clp_config.redis.port),
"CLP_EXTRA_HOST_REDIS_NAME": REDIS_COMPONENT_NAME,
"CLP_EXTRA_HOST_REDIS_ADDR": _resolve_external_host(self._clp_config.redis.host),
}
else:
env_vars |= {
"CLP_REDIS_HOST": _get_ip_from_hostname(self._clp_config.redis.host),
"CLP_REDIS_PORT": str(self._clp_config.redis.port),
}
# Credentials
env_vars |= {
CLP_REDIS_PASS_ENV_VAR_NAME: self._clp_config.redis.password,
}
return env_vars
def _set_up_env_for_spider_scheduler(self) -> EnvVarsDict:
"""
Sets up environment variables for the Spider scheduler component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = SPIDER_SCHEDULER_COMPONENT_NAME
if self._clp_config.compression_scheduler.type != OrchestrationType.SPIDER:
logger.info(
"%s is not configured, skipping environment setup...",
component_name,
)
return EnvVarsDict()
logger.info(f"Setting up environment for {component_name}...")
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"SPIDER_SCHEDULER_HOST": _get_ip_from_hostname(self._clp_config.spider_scheduler.host),
"SPIDER_SCHEDULER_PORT": str(self._clp_config.spider_scheduler.port),
}
return env_vars
def _set_up_env_for_results_cache_bundling(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for bundling the results cache component.
:return: Dictionary of environment variables necessary to bundle the component.
"""
component_name = RESULTS_CACHE_COMPONENT_NAME
if BundledService.RESULTS_CACHE not in self._clp_config.bundled:
logger.info(
"%s is not included in the 'bundled' configuration, skipping service bundling...",
component_name,
)
# Bundling
return EnvVarsDict({"CLP_RESULTS_CACHE_ENABLED": "0"})
logger.info("Setting up environment for bundling %s...", component_name)
conf_file = self._conf_dir / "mongo" / "mongod.conf"
data_dir = self._clp_config.data_directory / component_name
logs_dir = self._clp_config.logs_directory / component_name
validate_results_cache_config(self._clp_config, conf_file, data_dir, logs_dir)
resolved_data_dir = resolve_host_path_in_container(data_dir)
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_data_dir.mkdir(exist_ok=True, parents=True)
resolved_logs_dir.mkdir(exist_ok=True, parents=True)
_chown_paths_if_root(resolved_data_dir, resolved_logs_dir)
env_vars = EnvVarsDict()
# Collections
env_vars |= {
"CLP_RESULTS_CACHE_STREAM_COLLECTION_NAME": (
self._clp_config.results_cache.stream_collection_name
),
}
# Paths
env_vars |= {
"CLP_RESULTS_CACHE_CONF_FILE_HOST": str(conf_file),
"CLP_RESULTS_CACHE_DATA_DIR_HOST": str(data_dir),
"CLP_RESULTS_CACHE_LOGS_DIR_HOST": str(logs_dir),
}
return env_vars
def _set_up_env_for_results_cache(self) -> EnvVarsDict:
"""
Sets up environment variables for the results cache (MongoDB) component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = RESULTS_CACHE_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"CLP_RESULTS_CACHE_DB_NAME": self._clp_config.results_cache.db_name,
}
if BundledService.RESULTS_CACHE not in self._clp_config.bundled:
env_vars |= {
"CLP_RESULTS_CACHE_CONNECT_PORT": str(self._clp_config.results_cache.port),
"CLP_EXTRA_HOST_RESULTS_CACHE_NAME": RESULTS_CACHE_COMPONENT_NAME,
"CLP_EXTRA_HOST_RESULTS_CACHE_ADDR": _resolve_external_host(
self._clp_config.results_cache.host
),
}
else:
env_vars |= {
"CLP_RESULTS_CACHE_HOST": _get_ip_from_hostname(
self._clp_config.results_cache.host
),
"CLP_RESULTS_CACHE_PORT": str(self._clp_config.results_cache.port),
}
return env_vars
def _set_up_env_for_compression_scheduler(self) -> EnvVarsDict:
"""
Sets up environment variables and files for the compression scheduler component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = COMPRESSION_SCHEDULER_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_COMPRESSION_SCHEDULER_LOGGING_LEVEL": (
self._clp_config.compression_scheduler.logging_level
),
}
return env_vars
def _set_up_env_for_query_scheduler(self) -> EnvVarsDict:
"""
Sets up environment variables and files for the query scheduler component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = QUERY_SCHEDULER_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_QUERY_SCHEDULER_LOGGING_LEVEL": self._clp_config.query_scheduler.logging_level,
}
return env_vars
def _set_up_env_for_compression_worker(self, num_workers: int) -> EnvVarsDict:
"""
Sets up environment variables for the compression worker component.
:param num_workers: Number of worker processes to run.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = COMPRESSION_WORKER_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_COMPRESSION_WORKER_LOGGING_LEVEL": (
self._clp_config.compression_worker.logging_level
),
}
# Resources
env_vars |= {
"CLP_COMPRESSION_WORKER_CONCURRENCY": str(num_workers),
}
return env_vars
def _set_up_env_for_query_worker(self, num_workers: int) -> EnvVarsDict:
"""
Sets up environment variables for the query worker component.
:param num_workers: Number of worker processes to run.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = QUERY_WORKER_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_QUERY_WORKER_LOGGING_LEVEL": self._clp_config.query_worker.logging_level,
}
# Resources
env_vars |= {
"CLP_QUERY_WORKER_CONCURRENCY": str(num_workers),
}
return env_vars
def _set_up_env_for_reducer(self, num_workers: int) -> EnvVarsDict:
"""
Sets up environment variables for the reducer component.
:param num_workers: Number of worker processes to run.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = REDUCER_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_REDUCER_LOGGING_LEVEL": self._clp_config.reducer.logging_level,
}
# Resources
env_vars |= {
"CLP_REDUCER_CONCURRENCY": str(num_workers),
"CLP_REDUCER_UPSERT_INTERVAL": str(self._clp_config.reducer.upsert_interval),
}
return env_vars
def _set_up_env_for_api_server(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for the API server component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = API_SERVER_COMPONENT_NAME
if self._clp_config.api_server is None:
logger.info(f"The API Server is not configured, skipping {component_name} creation...")
return EnvVarsDict({"CLP_API_SERVER_ENABLED": "0"})
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"CLP_API_SERVER_HOST": _get_ip_from_hostname(self._clp_config.api_server.host),
"CLP_API_SERVER_PORT": str(self._clp_config.api_server.port),
}
# Telemetry env vars
instance_id_file = self._clp_config.logs_directory / "instance-id"
resolved_id_file = resolve_host_path_in_container(instance_id_file)
if resolved_id_file.exists():
with resolved_id_file.open("r") as f:
env_vars["CLP_INSTANCE_ID"] = f.readline().strip()
version_file = resolve_host_path_in_container(self._clp_home / "VERSION")
if version_file.exists():
with version_file.open("r") as f:
env_vars["CLP_VERSION"] = f.read().strip()
env_vars["CLP_DEPLOYMENT_METHOD"] = "docker-compose"
# Pass through host OS info (set by start-clp.sh)
for var in (
"CLP_HOST_OS",
"CLP_HOST_OS_VERSION",
"CLP_HOST_ARCH",
"CLP_DISABLE_TELEMETRY",
"CLP_TELEMETRY_DEBUG",
):
val = os.environ.get(var)
if val is not None:
env_vars[var] = val
return env_vars
def _set_up_env_for_log_ingestor(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for the log ingestor component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = LOG_INGESTOR_COMPONENT_NAME
if self._clp_config.log_ingestor is None:
logger.info("%s is not configured, skipping environment setup...", component_name)
return EnvVarsDict({"CLP_LOG_INGESTOR_ENABLED": "0"})
if self._clp_config.logs_input.type != StorageType.S3:
logger.info(
"%s is only applicable for S3 logs input type, skipping environment setup...",
component_name,
)
return EnvVarsDict({"CLP_LOG_INGESTOR_ENABLED": "0"})
logger.info("Setting up environment for %s...", component_name)
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"CLP_LOG_INGESTOR_HOST": _get_ip_from_hostname(self._clp_config.log_ingestor.host),
"CLP_LOG_INGESTOR_PORT": str(self._clp_config.log_ingestor.port),
}
# Logging config
env_vars |= {
"CLP_LOG_INGESTOR_LOGGING_LEVEL": self._clp_config.log_ingestor.logging_level,
}
return env_vars
def _set_up_env_for_webui(self, container_clp_config: ClpConfig) -> EnvVarsDict:
"""
Sets up environment variables and settings for the Web UI component.
:param container_clp_config: CLP configuration inside the containers.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = WEBUI_COMPONENT_NAME
logger.info(f"Setting up environment for {component_name}...")
container_webui_dir = CONTAINER_CLP_HOME / "var" / "www" / "webui"
client_settings_json_path = (
self._clp_home / "var" / "www" / "webui" / "client" / "settings.json"
)
server_settings_json_path = (
self._clp_home / "var" / "www" / "webui" / "server" / "dist" / "settings.json"
)
validate_webui_config(
self._clp_config,
client_settings_json_path,
server_settings_json_path,
)
# Read, update, and write back client's and server's settings.json
clp_db_connection_params = self._clp_config.database.get_clp_connection_params_and_type(
True
)
table_prefix = clp_db_connection_params["table_prefix"]
if StorageEngine.CLP_S == self._clp_config.package.storage_engine:
archives_table_name = ""
files_table_name = ""
else:
archives_table_name = get_archives_table_name(table_prefix, None)
files_table_name = get_files_table_name(table_prefix, None)
client_settings_json_updates = {
"ClpStorageEngine": self._clp_config.package.storage_engine,
"ClpQueryEngine": self._clp_config.package.query_engine,
"LogsInputType": self._clp_config.logs_input.type,
"MaxDatasetsPerQuery": self._clp_config.query_scheduler.max_datasets_per_query,
"MongoDbSearchResultsMetadataCollectionName": (
self._clp_config.webui.results_metadata_collection_name
),
"SqlDbClpArchivesTableName": archives_table_name,
"SqlDbClpDatasetsTableName": get_datasets_table_name(table_prefix),
"SqlDbClpFilesTableName": files_table_name,
"SqlDbClpTablePrefix": table_prefix,
"SqlDbCompressionJobsTableName": COMPRESSION_JOBS_TABLE_NAME,
}
server_settings_json_updates = {
"SqlDbHost": container_clp_config.database.host,
"SqlDbPort": container_clp_config.database.port,
"SqlDbName": self._clp_config.database.names[ClpDbNameType.CLP],
"SqlDbQueryJobsTableName": QUERY_JOBS_TABLE_NAME,
"SqlDbCompressionJobsTableName": COMPRESSION_JOBS_TABLE_NAME,
"MongoDbHost": container_clp_config.results_cache.host,
"MongoDbPort": container_clp_config.results_cache.port,
"MongoDbName": self._clp_config.results_cache.db_name,
"MongoDbSearchResultsMetadataCollectionName": (
self._clp_config.webui.results_metadata_collection_name
),
"MongoDbStreamFilesCollectionName": (
self._clp_config.results_cache.stream_collection_name
),
"ClientDir": str(container_webui_dir / "client"),
"LogViewerDir": str(container_webui_dir / "yscope-log-viewer"),
"StreamTargetUncompressedSize": self._clp_config.stream_output.target_uncompressed_size,
"ArchiveOutputCompressionLevel": self._clp_config.archive_output.compression_level,
"ArchiveOutputTargetArchiveSize": self._clp_config.archive_output.target_archive_size,
"ArchiveOutputTargetDictionariesSize": (
self._clp_config.archive_output.target_dictionaries_size
),
"ArchiveOutputTargetEncodedFileSize": (
self._clp_config.archive_output.target_encoded_file_size
),
"ArchiveOutputTargetSegmentSize": self._clp_config.archive_output.target_segment_size,
"ClpQueryEngine": self._clp_config.package.query_engine,
"ClpStorageEngine": self._clp_config.package.storage_engine,
}
stream_storage = self._clp_config.stream_output.storage
if StorageType.S3 == stream_storage.type:
s3_config = stream_storage.s3_config
server_settings_json_updates["StreamFilesDir"] = None
server_settings_json_updates["StreamFilesS3Region"] = s3_config.region_code
server_settings_json_updates["StreamFilesS3PathPrefix"] = (
f"{s3_config.bucket}/{s3_config.key_prefix}"
)
auth = s3_config.aws_authentication
if AwsAuthType.profile == auth.type:
server_settings_json_updates["StreamFilesS3Profile"] = auth.profile
else:
server_settings_json_updates["StreamFilesS3Profile"] = None
elif StorageType.FS == stream_storage.type:
server_settings_json_updates["StreamFilesDir"] = str(
container_clp_config.stream_output.get_directory()
)
server_settings_json_updates["StreamFilesS3Region"] = None
server_settings_json_updates["StreamFilesS3PathPrefix"] = None
server_settings_json_updates["StreamFilesS3Profile"] = None
query_engine = self._clp_config.package.query_engine
if QueryEngine.PRESTO == query_engine:
server_settings_json_updates["PrestoHost"] = container_clp_config.presto.host
server_settings_json_updates["PrestoPort"] = container_clp_config.presto.port
else:
server_settings_json_updates["PrestoHost"] = None
server_settings_json_updates["PrestoPort"] = None
if StorageType.FS == self._clp_config.logs_input.type:
client_settings_json_updates["LogsInputRootDir"] = str(CONTAINER_INPUT_LOGS_ROOT_DIR)
server_settings_json_updates["LogsInputRootDir"] = str(CONTAINER_INPUT_LOGS_ROOT_DIR)
else:
client_settings_json_updates["LogsInputRootDir"] = None
server_settings_json_updates["LogsInputRootDir"] = None
resolved_client_settings_json_path = resolve_host_path_in_container(
client_settings_json_path
)
client_settings_json = self._read_and_update_settings_json(
resolved_client_settings_json_path, client_settings_json_updates
)
with open(resolved_client_settings_json_path, "w") as client_settings_json_file:
client_settings_json_file.write(json.dumps(client_settings_json))
resolved_server_settings_json_path = resolve_host_path_in_container(
server_settings_json_path
)
server_settings_json = self._read_and_update_settings_json(
resolved_server_settings_json_path, server_settings_json_updates
)
with open(resolved_server_settings_json_path, "w") as settings_json_file:
settings_json_file.write(json.dumps(server_settings_json))
env_vars = EnvVarsDict()
# Connection config
env_vars |= {
"CLP_WEBUI_HOST": _get_ip_from_hostname(self._clp_config.webui.host),
"CLP_WEBUI_PORT": str(self._clp_config.webui.port),
}
# Security config
env_vars |= {
"CLP_WEBUI_RATE_LIMIT": str(self._clp_config.webui.rate_limit),
}
return env_vars
def _set_up_env_for_mcp_server(self) -> EnvVarsDict:
"""
Sets up environment variables and directories for the MCP server component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = MCP_SERVER_COMPONENT_NAME
if self._clp_config.mcp_server is None:
logger.info(f"The MCP Server is not configured, skipping {component_name} creation...")
return EnvVarsDict()
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
validate_mcp_server_config(self._clp_config, logs_dir)
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Service enablement
env_vars |= {
"CLP_MCP_SERVER_ENABLED": "1",
}
# Connection config
env_vars |= {
"CLP_MCP_HOST": _get_ip_from_hostname(self._clp_config.mcp_server.host),
"CLP_MCP_PORT": str(self._clp_config.mcp_server.port),
}
# Logging config
env_vars |= {
"CLP_MCP_LOGGING_LEVEL": self._clp_config.mcp_server.logging_level,
}
return env_vars
def _set_up_env_for_garbage_collector(self) -> EnvVarsDict:
"""
Sets up environment variables for the garbage collector component.
:return: Dictionary of environment variables necessary to launch the component.
"""
component_name = GARBAGE_COLLECTOR_COMPONENT_NAME
if not is_retention_period_configured(self._clp_config):
logger.info(
f"Retention period is not configured, skipping {component_name} creation..."
)
return EnvVarsDict(
{
"CLP_GARBAGE_COLLECTOR_ENABLED": "0",
}
)
logger.info(f"Setting up environment for {component_name}...")
logs_dir = self._clp_config.logs_directory / component_name
resolved_logs_dir = resolve_host_path_in_container(logs_dir)
resolved_logs_dir.mkdir(parents=True, exist_ok=True)
env_vars = EnvVarsDict()
# Logging config
env_vars |= {
"CLP_GARBAGE_COLLECTOR_LOGGING_LEVEL": self._clp_config.garbage_collector.logging_level
}
return env_vars
def _read_and_update_settings_json(
self, settings_file_path: pathlib.Path, updates: dict[str, Any]
) -> dict[str, Any]:
"""
Reads and updates a settings JSON file.
:param settings_file_path:
:param updates:
"""
with open(settings_file_path, "r") as settings_json_file:
settings_object = json.loads(settings_json_file.read())
self._update_settings_object("", settings_object, updates)
return settings_object
def _update_settings_object(
self,
parent_key_prefix: str,
settings: dict[str, Any],
updates: dict[str, Any],
) -> None:
"""
Recursively updates the given settings object with the values from `updates`.
:param parent_key_prefix: The prefix for keys at this level in the settings dictionary.
:param settings: The settings to update.
:param updates: The updates.
:raise ValueError: If a key in `updates` doesn't exist in `settings`.
"""
for key, value in updates.items():
if key not in settings:
error_msg = (
f"{parent_key_prefix}{key} is not a valid configuration key for the webui."
)
raise ValueError(error_msg)
if isinstance(value, dict):
self._update_settings_object(f"{parent_key_prefix}{key}.", settings[key], value)
else:
settings[key] = value
_DEPLOYMENT_TYPE_TO_COMPOSE_FILE: MappingProxyType[DeploymentType, str] = MappingProxyType(
{
DeploymentType.BASE: "docker-compose-base.yaml",
DeploymentType.FULL: "docker-compose.yaml",
DeploymentType.SPIDER_BASE: "docker-compose-spider-base.yaml",
DeploymentType.SPIDER_FULL: "docker-compose-spider.yaml",
}
)
class DockerComposeController(BaseController):
"""
Controller for orchestrating CLP components using Docker Compose.
"""
def __init__(
self, clp_config: ClpConfig, instance_id: str, restart_policy: str = "on-failure:3"
) -> None:
"""Initializes the DockerComposeController."""
self._project_name = f"clp-package-{instance_id}"
self._restart_policy = restart_policy
super().__init__(clp_config)
def set_up_env(self) -> None:
"""
Sets up environment variables and directories for all components and writes them to the
`.env` file.