userver: en/testsuite/databases/kafka/service.py Source File
Loading...
Searching...
No Matches
service.py
1import os
2import pathlib
3
4from testsuite.environment import service, utils
5
6from . import classes
7
8DEFAULT_SERVER_HOST = 'localhost'
9DEFAULT_SERVER_PORT = 9099
10DEFAULT_CONTROLLER_PORT = 9100
11
12PLUGIN_DIR = pathlib.Path(__file__).parent
13SERVICE_SCRIPT_DIR = PLUGIN_DIR.joinpath('scripts/service-kafka')
14
15
16def _stringify_start_topics(start_topics: dict[str, int]) -> str:
17 return ';'.join(
18 [
19 f'{topic}:{partitions_count}'
20 for topic, partitions_count in start_topics.items()
21 ]
22 )
23
24
25def _parse_custom_topics(custom_topics: str) -> dict[str, int]:
26 if not custom_topics:
27 return {}
28
29 result: dict[str, int] = {}
30 for topic_partitions_pair in custom_topics.split(','):
31 topic, partition = topic_partitions_pair.split(':')
32 result[topic] = int(partition)
33
34 return result
35
36
37def try_get_custom_topics() -> dict[str, int]:
38 return _parse_custom_topics(
39 os.environ.get('TESTSUITE_KAFKA_CUSTOM_TOPICS', '')
40 )
41
42
43def create_kafka_service(
44 service_name: str,
45 working_dir: str,
46 settings: classes.ServiceSettings | None = None,
47 env: dict[str, str] | None = None,
48):
49 if settings is None:
50 settings = get_service_settings()
51
52 return service.ScriptService(
53 service_name=service_name,
54 script_path=str(SERVICE_SCRIPT_DIR),
55 working_dir=working_dir,
56 environment={
57 'KAFKA_TMPDIR': working_dir,
58 'KAFKA_SERVER_HOST': settings.server_host,
59 'KAFKA_SERVER_PORT': str(settings.server_port),
60 'KAFKA_CONTROLLER_PORT': str(settings.controller_port),
61 'KAFKA_START_TOPICS': _stringify_start_topics(
62 settings.custom_start_topics or try_get_custom_topics()
63 ),
64 **(env or {}),
65 },
66 check_ports=[settings.server_port, settings.controller_port],
67 start_timeout=utils.getenv_float(
68 key='TESTSUITE_KAFKA_SERVER_START_TIMEOUT',
69 default=10.0,
70 ),
71 )
72
73
74def get_service_settings(
75 custom_start_topics: dict[str, int] = {},
76) -> classes.ServiceSettings:
77 return classes.ServiceSettings(
78 server_host=utils.getenv_str(
79 'TESTSUITE_KAFKA_SERVER_HOST', DEFAULT_SERVER_HOST
80 ),
81 server_port=utils.getenv_int(
82 'TESTSUITE_KAFKA_SERVER_PORT',
83 DEFAULT_SERVER_PORT,
84 ),
85 controller_port=utils.getenv_int(
86 'TESTSUITE_KAFKA_CONTROLLER_PORT',
87 DEFAULT_CONTROLLER_PORT,
88 ),
89 custom_start_topics=custom_start_topics,
90 )