proxlb 1.1.12.dev4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- etc/proxlb/proxlb_example.yaml +90 -0
- etc/systemd/system/proxlb.service +13 -0
- proxlb/__init__.py +0 -0
- proxlb/main.py +120 -0
- proxlb/models/__init__.py +0 -0
- proxlb/models/balancing.py +270 -0
- proxlb/models/calculations.py +889 -0
- proxlb/models/features.py +124 -0
- proxlb/models/groups.py +124 -0
- proxlb/models/guests.py +215 -0
- proxlb/models/ha_rules.py +126 -0
- proxlb/models/nodes.py +312 -0
- proxlb/models/pools.py +148 -0
- proxlb/models/tags.py +283 -0
- proxlb/utils/__init__.py +0 -0
- proxlb/utils/cli_parser.py +90 -0
- proxlb/utils/config_parser.py +96 -0
- proxlb/utils/helper.py +337 -0
- proxlb/utils/logger.py +146 -0
- proxlb/utils/proxmox_api.py +440 -0
- proxlb/utils/version.py +7 -0
- proxlb-1.1.12.dev4.dist-info/METADATA +26 -0
- proxlb-1.1.12.dev4.dist-info/RECORD +26 -0
- proxlb-1.1.12.dev4.dist-info/WHEEL +5 -0
- proxlb-1.1.12.dev4.dist-info/licenses/LICENSE +674 -0
- proxlb-1.1.12.dev4.dist-info/top_level.txt +1 -0
proxlb/models/tags.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Tags class retrieves and processes tags from guests of type VM or CT running
|
|
3
|
+
in a Proxmox cluster. It provides methods to fetch tags from the Proxmox API and
|
|
4
|
+
evaluate them for affinity, anti-affinity, and ignore tags, which are used during
|
|
5
|
+
balancing calculations.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__author__ = "Florian Paul Azim Hoberg <gyptazy>"
|
|
9
|
+
__copyright__ = "Copyright (C) 2025 Florian Paul Azim Hoberg (@gyptazy)"
|
|
10
|
+
__license__ = "GPL-3.0"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
import time
|
|
14
|
+
from typing import List
|
|
15
|
+
from typing import Dict, Any
|
|
16
|
+
from utils.logger import SystemdLogger
|
|
17
|
+
from utils.helper import Helper
|
|
18
|
+
|
|
19
|
+
logger = SystemdLogger()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Tags:
|
|
23
|
+
"""
|
|
24
|
+
The Tags class retrieves and processes tags from guests of type VM or CT running
|
|
25
|
+
in a Proxmox cluster. It provides methods to fetch tags from the Proxmox API and
|
|
26
|
+
evaluate them for affinity, anti-affinity, and ignore tags, which are used during
|
|
27
|
+
balancing calculations.
|
|
28
|
+
|
|
29
|
+
Methods:
|
|
30
|
+
__init__:
|
|
31
|
+
Initializes the Tags class.
|
|
32
|
+
|
|
33
|
+
get_tags_from_guests(proxmox_api: any, node: str, guest_id: int, guest_type: str) -> List[str]:
|
|
34
|
+
Retrieves all tags for a given guest from the Proxmox API.
|
|
35
|
+
|
|
36
|
+
get_affinity_groups(tags: List[str]) -> List[str]:
|
|
37
|
+
Evaluates and returns all affinity tags from the provided list of tags.
|
|
38
|
+
|
|
39
|
+
get_anti_affinity_groups(tags: List[str]) -> List[str]:
|
|
40
|
+
Evaluates and returns all anti-affinity tags from the provided list of tags.
|
|
41
|
+
|
|
42
|
+
get_ignore(tags: List[str]) -> bool:
|
|
43
|
+
Evaluates and returns a boolean indicating whether the guest should be ignored based on the provided list of tags.
|
|
44
|
+
"""
|
|
45
|
+
def __init__(self):
|
|
46
|
+
"""
|
|
47
|
+
Initializes the tags class.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def get_tags_from_guests(proxmox_api: any, node: str, guest_id: int, guest_type: str) -> List[str]:
|
|
52
|
+
"""
|
|
53
|
+
Get tags for a guest from the Proxmox cluster by the API.
|
|
54
|
+
|
|
55
|
+
This method retrieves all tags for a given guest from the Proxmox API which
|
|
56
|
+
is held in the guest_config.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
proxmox_api (any): The Proxmox API client instance.
|
|
60
|
+
node (str): The node name where the given guest is located.
|
|
61
|
+
guest_id (int): The internal Proxmox ID of the guest.
|
|
62
|
+
guest_type (str): The type (vm or ct) of the guest.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
List: A list of all tags assoiciated with the given guest.
|
|
66
|
+
"""
|
|
67
|
+
logger.debug("Starting: get_tags_from_guests.")
|
|
68
|
+
time.sleep(0.1)
|
|
69
|
+
if guest_type == 'vm':
|
|
70
|
+
guest_config = proxmox_api.nodes(node).qemu(guest_id).config.get()
|
|
71
|
+
tags = guest_config.get("tags", [])
|
|
72
|
+
if guest_type == 'ct':
|
|
73
|
+
guest_config = proxmox_api.nodes(node).lxc(guest_id).config.get()
|
|
74
|
+
tags = guest_config.get("tags", [])
|
|
75
|
+
|
|
76
|
+
if isinstance(tags, str):
|
|
77
|
+
tags = tags.split(";")
|
|
78
|
+
|
|
79
|
+
logger.debug("Finished: get_tags_from_guests.")
|
|
80
|
+
return tags
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def get_affinity_groups(tags: List[str], pools: List[str], ha_rules: List[str], proxlb_config: Dict[str, Any]) -> List[str]:
|
|
84
|
+
"""
|
|
85
|
+
Get affinity tags for a guest from the Proxmox cluster by the API.
|
|
86
|
+
|
|
87
|
+
This method retrieves all tags for a given guest or based on a
|
|
88
|
+
membership of a pool and evaluates the affinity groups which are
|
|
89
|
+
required during the balancing calculations.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
tags (List): A list holding all defined tags for a given guest.
|
|
93
|
+
pools (List): A list holding all defined pools for a given guest.
|
|
94
|
+
ha_rules (List): A list holding all defined ha_rules for a given guest.
|
|
95
|
+
proxlb_config (Dict): A dict holding the ProxLB configuration.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
List: A list including all affinity tags for the given guest.
|
|
99
|
+
"""
|
|
100
|
+
logger.debug("Starting: get_affinity_groups.")
|
|
101
|
+
affinity_tags = []
|
|
102
|
+
|
|
103
|
+
# Tag based affinity groups
|
|
104
|
+
if len(tags) > 0:
|
|
105
|
+
for tag in tags:
|
|
106
|
+
if tag.startswith("plb_affinity"):
|
|
107
|
+
logger.debug(f"Adding affinity group for tag {tag}.")
|
|
108
|
+
affinity_tags.append(tag)
|
|
109
|
+
else:
|
|
110
|
+
logger.debug(f"Skipping evaluation of tag: {tag} This is not an affinity tag.")
|
|
111
|
+
|
|
112
|
+
# Pool based affinity groups
|
|
113
|
+
if len(pools) > 0:
|
|
114
|
+
for pool in pools:
|
|
115
|
+
if pool in (proxlb_config['balancing'].get('pools') or {}):
|
|
116
|
+
if proxlb_config['balancing']['pools'][pool].get('type', None) == 'affinity':
|
|
117
|
+
logger.debug(f"Adding affinity group for pool {pool}.")
|
|
118
|
+
affinity_tags.append(pool)
|
|
119
|
+
else:
|
|
120
|
+
logger.debug(f"Skipping evaluation of pool: {pool} This is not an affinity pool.")
|
|
121
|
+
|
|
122
|
+
# HA rule based affinity groups
|
|
123
|
+
if len(ha_rules) > 0:
|
|
124
|
+
for ha_rule in ha_rules:
|
|
125
|
+
if ha_rule.get('type', None) == 'affinity':
|
|
126
|
+
logger.debug(f"Adding affinity group for ha-rule {ha_rule}.")
|
|
127
|
+
affinity_tags.append(ha_rule['rule'])
|
|
128
|
+
|
|
129
|
+
logger.debug("Finished: get_affinity_groups.")
|
|
130
|
+
return affinity_tags
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def get_anti_affinity_groups(tags: List[str], pools: List[str], ha_rules: List[str], proxlb_config: Dict[str, Any]) -> List[str]:
|
|
134
|
+
"""
|
|
135
|
+
Get anti-affinity tags for a guest from the Proxmox cluster by the API.
|
|
136
|
+
|
|
137
|
+
This method retrieves all tags for a given guest or based on a
|
|
138
|
+
membership of a pool and evaluates the anti-affinity groups which
|
|
139
|
+
are required during the balancing calculations.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
tags (List): A list holding all defined tags for a given guest.
|
|
143
|
+
pools (List): A list holding all defined pools for a given guest.
|
|
144
|
+
ha_rules (List): A list holding all defined ha_rules for a given guest.
|
|
145
|
+
proxlb_config (Dict): A dict holding the ProxLB configuration.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
List: A list including all anti-affinity tags for the given guest..
|
|
149
|
+
"""
|
|
150
|
+
logger.debug("Starting: get_anti_affinity_groups.")
|
|
151
|
+
anti_affinity_tags = []
|
|
152
|
+
|
|
153
|
+
# Tag based anti-affinity groups
|
|
154
|
+
if len(tags) > 0:
|
|
155
|
+
for tag in tags:
|
|
156
|
+
if tag.startswith("plb_anti_affinity"):
|
|
157
|
+
logger.debug(f"Adding anti-affinity group for tag {tag}.")
|
|
158
|
+
anti_affinity_tags.append(tag)
|
|
159
|
+
else:
|
|
160
|
+
logger.debug(f"Skipping evaluation of tag: {tag} This is not an anti-affinity tag.")
|
|
161
|
+
|
|
162
|
+
# Pool based anti-affinity groups
|
|
163
|
+
if len(pools) > 0:
|
|
164
|
+
for pool in pools:
|
|
165
|
+
if pool in (proxlb_config['balancing'].get('pools') or {}):
|
|
166
|
+
if proxlb_config['balancing']['pools'][pool].get('type', None) == 'anti-affinity':
|
|
167
|
+
logger.debug(f"Adding anti-affinity group for pool {pool}.")
|
|
168
|
+
anti_affinity_tags.append(pool)
|
|
169
|
+
else:
|
|
170
|
+
logger.debug(f"Skipping evaluation of pool: {pool} This is not an anti-affinity pool.")
|
|
171
|
+
|
|
172
|
+
# HA rule based anti-affinity groups
|
|
173
|
+
if len(ha_rules) > 0:
|
|
174
|
+
for ha_rule in ha_rules:
|
|
175
|
+
if ha_rule.get('type', None) == 'anti-affinity':
|
|
176
|
+
logger.debug(f"Adding anti-affinity group for ha-rule {ha_rule}.")
|
|
177
|
+
anti_affinity_tags.append(ha_rule['rule'])
|
|
178
|
+
|
|
179
|
+
logger.debug("Finished: get_anti_affinity_groups.")
|
|
180
|
+
return anti_affinity_tags
|
|
181
|
+
|
|
182
|
+
@staticmethod
|
|
183
|
+
def get_ignore(tags: List[str]) -> bool:
|
|
184
|
+
"""
|
|
185
|
+
Validate for ignore tags of a guest from the Proxmox cluster by the API.
|
|
186
|
+
|
|
187
|
+
This method retrieves all tags for a given guest and evaluates the
|
|
188
|
+
ignore tag which are required during the balancing calculations.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
tags (List): A list holding all defined tags for a given guest.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
Bool: Returns a bool that indicates whether to ignore a guest or not.
|
|
195
|
+
"""
|
|
196
|
+
logger.debug("Starting: get_ignore.")
|
|
197
|
+
ignore_tag = False
|
|
198
|
+
|
|
199
|
+
if len(tags) > 0:
|
|
200
|
+
logger.debug(f"Found {len(tags)} tags to evaluate.")
|
|
201
|
+
for tag in tags:
|
|
202
|
+
logger.debug(f"Evaluating tag: {tag}.")
|
|
203
|
+
if tag.startswith("plb_ignore"):
|
|
204
|
+
logger.debug(f"Found valid ignore tag: {tag}. Marking guest as ignored.")
|
|
205
|
+
ignore_tag = True
|
|
206
|
+
else:
|
|
207
|
+
logger.debug(f"Tag: {tag} This is not an ignore tag.")
|
|
208
|
+
|
|
209
|
+
logger.debug("Finished: get_ignore.")
|
|
210
|
+
return ignore_tag
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def get_node_relationships(tags: List[str], nodes: Dict[str, Any], pools: List[str], ha_rules: List[str], proxlb_config: Dict[str, Any]) -> str:
|
|
214
|
+
"""
|
|
215
|
+
Get a node relationship tag for a guest from the Proxmox cluster by the API to pin
|
|
216
|
+
a guest to a node or by defined pools from ProxLB configuration.
|
|
217
|
+
|
|
218
|
+
This method retrieves a relationship tag between a guest and a specific
|
|
219
|
+
hypervisor node to pin the guest to a specific node (e.g., for licensing reason).
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
tags (List): A list holding all defined tags for a given guest.
|
|
223
|
+
nodes (Dict): A dictionary holding all available nodes in the cluster.
|
|
224
|
+
pools (List): A list holding all defined pools for a given guest.
|
|
225
|
+
ha_rules (List): A list holding all defined ha_rules for a given guest.
|
|
226
|
+
proxlb_config (Dict): A dict holding the ProxLB configuration.
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
Str: The related hypervisor node name(s).
|
|
230
|
+
"""
|
|
231
|
+
logger.debug("Starting: get_node_relationships.")
|
|
232
|
+
node_relationship_tags = []
|
|
233
|
+
|
|
234
|
+
# Tag based node relationship
|
|
235
|
+
if len(tags) > 0:
|
|
236
|
+
logger.debug("Validating node pinning by tags.")
|
|
237
|
+
for tag in tags:
|
|
238
|
+
if tag.startswith("plb_pin"):
|
|
239
|
+
node_relationship_tag = tag.replace("plb_pin_", "")
|
|
240
|
+
|
|
241
|
+
# Validate if the node to pin is present in the cluster
|
|
242
|
+
if Helper.validate_node_presence(node_relationship_tag, nodes):
|
|
243
|
+
logger.debug(f"Tag {node_relationship_tag} is valid! Defined node exists in the cluster.")
|
|
244
|
+
logger.debug(f"Setting node relationship because of tag {tag} to {node_relationship_tag}.")
|
|
245
|
+
node_relationship_tags.append(node_relationship_tag)
|
|
246
|
+
else:
|
|
247
|
+
logger.warning(f"Tag {node_relationship_tag} is invalid! Defined node does not exist in the cluster. Not applying pinning.")
|
|
248
|
+
|
|
249
|
+
# Pool based node relationship
|
|
250
|
+
if len(pools) > 0:
|
|
251
|
+
logger.debug("Validating node pinning by pools.")
|
|
252
|
+
for pool in pools:
|
|
253
|
+
if pool in (proxlb_config['balancing'].get('pools') or {}):
|
|
254
|
+
|
|
255
|
+
pool_nodes = proxlb_config['balancing']['pools'][pool].get('pin', None)
|
|
256
|
+
for node in pool_nodes if pool_nodes is not None else []:
|
|
257
|
+
|
|
258
|
+
# Validate if the node to pin is present in the cluster
|
|
259
|
+
if Helper.validate_node_presence(node, nodes):
|
|
260
|
+
logger.debug(f"Pool pinning tag {node} is valid! Defined node exists in the cluster.")
|
|
261
|
+
logger.debug(f"Setting node relationship because of pool {pool} to {node}.")
|
|
262
|
+
node_relationship_tags.append(node)
|
|
263
|
+
else:
|
|
264
|
+
logger.warning(f"Pool pinning tag {node} is invalid! Defined node does not exist in the cluster. Not applying pinning.")
|
|
265
|
+
|
|
266
|
+
else:
|
|
267
|
+
logger.debug(f"Skipping pinning for pool {pool}. Pool is not defined in ProxLB configuration.")
|
|
268
|
+
|
|
269
|
+
# HA rule based node relationship
|
|
270
|
+
if len(ha_rules) > 0:
|
|
271
|
+
logger.debug("Validating node pinning by ha-rules.")
|
|
272
|
+
for ha_rule in ha_rules:
|
|
273
|
+
if len(ha_rule.get("nodes", 0)) > 0:
|
|
274
|
+
if ha_rule.get("type", None) == "affinity":
|
|
275
|
+
logger.debug(f"ha-rule {ha_rule['rule']} is of type affinity.")
|
|
276
|
+
for node in ha_rule["nodes"]:
|
|
277
|
+
logger.debug(f"Adding {node} as node relationship because of ha-rule {ha_rule['rule']}.")
|
|
278
|
+
node_relationship_tags.append(node)
|
|
279
|
+
else:
|
|
280
|
+
logger.debug(f"ha-rule {ha_rule['rule']} is of type anti-affinity. Skipping node relationship addition.")
|
|
281
|
+
|
|
282
|
+
logger.debug("Finished: get_node_relationships.")
|
|
283
|
+
return node_relationship_tags
|
proxlb/utils/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The CliParser class handles the parsing of command-line interface (CLI) arguments.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__author__ = "Florian Paul Azim Hoberg <gyptazy>"
|
|
6
|
+
__copyright__ = "Copyright (C) 2025 Florian Paul Azim Hoberg (@gyptazy)"
|
|
7
|
+
__license__ = "GPL-3.0"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import utils.version
|
|
12
|
+
from utils.logger import SystemdLogger
|
|
13
|
+
|
|
14
|
+
logger = SystemdLogger()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CliParser:
|
|
18
|
+
"""
|
|
19
|
+
The CliParser class handles the parsing of command-line interface (CLI) arguments.
|
|
20
|
+
"""
|
|
21
|
+
def __init__(self):
|
|
22
|
+
"""
|
|
23
|
+
Initializes the CliParser class.
|
|
24
|
+
|
|
25
|
+
This method sets up an argument parser for the command-line interface (CLI) with various options:
|
|
26
|
+
- `-c` or `--config`: Specifies the path to the configuration file.
|
|
27
|
+
- `-d` or `--dry-run`: Performs a dry-run without executing any actions.
|
|
28
|
+
- `-j` or `--json`: Returns a JSON of the VM movement.
|
|
29
|
+
- `-b` or `--best-node`: Returns the best next node.
|
|
30
|
+
- `-v` or `--version`: Returns the current ProxLB version.
|
|
31
|
+
|
|
32
|
+
Logs the start and end of the initialization process.
|
|
33
|
+
"""
|
|
34
|
+
logger.debug("Starting: CliParser.")
|
|
35
|
+
|
|
36
|
+
self.parser = argparse.ArgumentParser(
|
|
37
|
+
description=(
|
|
38
|
+
f"{utils.version.__app_name__} ({utils.version.__version__}): "
|
|
39
|
+
f"{utils.version.__app_desc__}"
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
self.parser.add_argument(
|
|
44
|
+
"-c", "--config",
|
|
45
|
+
help="Path to the configuration file",
|
|
46
|
+
type=str,
|
|
47
|
+
required=False
|
|
48
|
+
)
|
|
49
|
+
self.parser.add_argument(
|
|
50
|
+
"-d", "--dry-run",
|
|
51
|
+
help="Perform a dry-run without executing any actions",
|
|
52
|
+
action="store_true",
|
|
53
|
+
required=False
|
|
54
|
+
)
|
|
55
|
+
self.parser.add_argument(
|
|
56
|
+
"-j", "--json",
|
|
57
|
+
help="Return a JSON of the VM movement",
|
|
58
|
+
action="store_true",
|
|
59
|
+
required=False
|
|
60
|
+
)
|
|
61
|
+
self.parser.add_argument(
|
|
62
|
+
"-b", "--best-node",
|
|
63
|
+
help="Returns the best next node",
|
|
64
|
+
action="store_true",
|
|
65
|
+
required=False
|
|
66
|
+
)
|
|
67
|
+
self.parser.add_argument(
|
|
68
|
+
"-v", "--version",
|
|
69
|
+
help="Returns the current ProxLB version",
|
|
70
|
+
action="store_true",
|
|
71
|
+
required=False
|
|
72
|
+
)
|
|
73
|
+
logger.debug("Finished: CliParser.")
|
|
74
|
+
|
|
75
|
+
def parse_args(self) -> argparse.Namespace:
|
|
76
|
+
"""
|
|
77
|
+
Parses and returns the parsed command-line interface (CLI) arguments.
|
|
78
|
+
|
|
79
|
+
This method uses the argparse library to parse the arguments provided
|
|
80
|
+
via the command line. It logs the start and end of the parsing process,
|
|
81
|
+
as well as the parsed arguments for debugging purposes.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
argparse.Namespace: An object containing the parsed CLI arguments.
|
|
85
|
+
"""
|
|
86
|
+
logger.debug("Starting: parse_args.")
|
|
87
|
+
logger.debug(self.parser.parse_args())
|
|
88
|
+
|
|
89
|
+
logger.debug("Finished: parse_args.")
|
|
90
|
+
return self.parser.parse_args()
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The ConfigParser class handles the parsing of configuration file
|
|
3
|
+
from a given YAML file from any location.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__author__ = "Florian Paul Azim Hoberg <gyptazy>"
|
|
7
|
+
__copyright__ = "Copyright (C) 2025 Florian Paul Azim Hoberg (@gyptazy)"
|
|
8
|
+
__license__ = "GPL-3.0"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
try:
|
|
14
|
+
import yaml
|
|
15
|
+
PYYAML_PRESENT = True
|
|
16
|
+
except ImportError:
|
|
17
|
+
PYYAML_PRESENT = False
|
|
18
|
+
from typing import Dict, Any
|
|
19
|
+
from utils.logger import SystemdLogger
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
if not PYYAML_PRESENT:
|
|
23
|
+
print("Error: The required library 'pyyaml' is not installed.")
|
|
24
|
+
sys.exit(1)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
logger = SystemdLogger()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ConfigParser:
|
|
31
|
+
"""
|
|
32
|
+
The ConfigParser class handles the parsing of a configuration file.
|
|
33
|
+
|
|
34
|
+
Methods:
|
|
35
|
+
__init__(config_path: str)
|
|
36
|
+
|
|
37
|
+
test_config_path(config_path: str) -> None
|
|
38
|
+
Checks if the configuration file is present at the given config path.
|
|
39
|
+
|
|
40
|
+
get_config() -> Dict[str, Any]
|
|
41
|
+
Parses and returns the configuration data from the YAML file.
|
|
42
|
+
"""
|
|
43
|
+
def __init__(self, config_path: str):
|
|
44
|
+
"""
|
|
45
|
+
Initializes the configuration file parser and validates the config file.
|
|
46
|
+
"""
|
|
47
|
+
logger.debug("Starting: ConfigParser.")
|
|
48
|
+
self.config_path = self.test_config_path(config_path)
|
|
49
|
+
logger.debug("Finished: ConfigParser.")
|
|
50
|
+
|
|
51
|
+
def test_config_path(self, config_path: str) -> None:
|
|
52
|
+
"""
|
|
53
|
+
Checks if configuration file is present at given config path.
|
|
54
|
+
"""
|
|
55
|
+
logger.debug("Starting: test_config_path.")
|
|
56
|
+
# Test for config file at given location
|
|
57
|
+
if config_path is not None:
|
|
58
|
+
|
|
59
|
+
if os.path.exists(config_path):
|
|
60
|
+
logger.debug(f"The file {config_path} exists.")
|
|
61
|
+
else:
|
|
62
|
+
logger.error(f"The file {config_path} does not exist.")
|
|
63
|
+
sys.exit(1)
|
|
64
|
+
|
|
65
|
+
# Test for config file at default location as a fallback
|
|
66
|
+
if config_path is None:
|
|
67
|
+
default_config_path = "/etc/proxlb/proxlb.yaml"
|
|
68
|
+
|
|
69
|
+
if os.path.exists(default_config_path):
|
|
70
|
+
logger.debug(f"The file {default_config_path} exists.")
|
|
71
|
+
config_path = default_config_path
|
|
72
|
+
else:
|
|
73
|
+
print(f"The config file {default_config_path} does not exist.")
|
|
74
|
+
logger.critical(f"The config file {default_config_path} does not exist.")
|
|
75
|
+
sys.exit(1)
|
|
76
|
+
|
|
77
|
+
logger.debug("Finished: test_config_path.")
|
|
78
|
+
return config_path
|
|
79
|
+
|
|
80
|
+
def get_config(self) -> Dict[str, Any]:
|
|
81
|
+
"""
|
|
82
|
+
Parses and returns CLI arguments.
|
|
83
|
+
"""
|
|
84
|
+
logger.debug("Starting: get_config.")
|
|
85
|
+
logger.info(f"Using config path: {self.config_path}")
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
with open(self.config_path, "r", encoding="utf-8") as config_file:
|
|
89
|
+
config_data = yaml.load(config_file, Loader=yaml.FullLoader)
|
|
90
|
+
return config_data
|
|
91
|
+
except yaml.YAMLError as exception_error:
|
|
92
|
+
print(f"Error loading YAML file: {exception_error}")
|
|
93
|
+
logger.critical(f"Error loading YAML file: {exception_error}")
|
|
94
|
+
sys.exit(1)
|
|
95
|
+
|
|
96
|
+
logger.debug("Finished: get_config.")
|