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/utils/helper.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Helper class provides some basic helper functions to not mess up the code in other
|
|
3
|
+
classes.
|
|
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 json
|
|
12
|
+
import uuid
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import utils.version
|
|
18
|
+
from utils.logger import SystemdLogger
|
|
19
|
+
from typing import Dict, Any
|
|
20
|
+
from types import FrameType
|
|
21
|
+
|
|
22
|
+
logger = SystemdLogger()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Helper:
|
|
26
|
+
"""
|
|
27
|
+
The Helper class provides some basic helper functions to not mess up the code in other
|
|
28
|
+
classes.
|
|
29
|
+
|
|
30
|
+
Methods:
|
|
31
|
+
__init__():
|
|
32
|
+
Initializes the general Helper class.
|
|
33
|
+
|
|
34
|
+
get_uuid_string() -> str:
|
|
35
|
+
Generates a random uuid and returns it as a string.
|
|
36
|
+
|
|
37
|
+
log_node_metrics(proxlb_data: Dict[str, Any], init: bool = True) -> None:
|
|
38
|
+
Logs the memory, CPU, and disk usage metrics of nodes in the provided proxlb_data dictionary.
|
|
39
|
+
|
|
40
|
+
get_version(print_version: bool = False) -> None:
|
|
41
|
+
Returns the current version of ProxLB and optionally prints it to stdout.
|
|
42
|
+
|
|
43
|
+
get_daemon_mode(proxlb_config: Dict[str, Any]) -> None:
|
|
44
|
+
Checks if the daemon mode is active and handles the scheduling accordingly.
|
|
45
|
+
"""
|
|
46
|
+
proxlb_reload = False
|
|
47
|
+
|
|
48
|
+
def __init__(self):
|
|
49
|
+
"""
|
|
50
|
+
Initializes the general Helper clas.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def get_uuid_string() -> str:
|
|
55
|
+
"""
|
|
56
|
+
Generates a random uuid and returns it as a string.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
None
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Str: Returns a random uuid as a string.
|
|
63
|
+
"""
|
|
64
|
+
logger.debug("Starting: get_uuid_string.")
|
|
65
|
+
generated_uuid = uuid.uuid4()
|
|
66
|
+
logger.debug("Finished: get_uuid_string.")
|
|
67
|
+
return str(generated_uuid)
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def log_node_metrics(proxlb_data: Dict[str, Any], init: bool = True) -> None:
|
|
71
|
+
"""
|
|
72
|
+
Logs the memory, CPU, and disk usage metrics of nodes in the provided proxlb_data dictionary.
|
|
73
|
+
|
|
74
|
+
This method processes the usage metrics of nodes and logs them. It also updates the
|
|
75
|
+
'statistics' field in the 'meta' section of the proxlb_data dictionary with the
|
|
76
|
+
memory, CPU, and disk usage metrics before and after a certain operation.
|
|
77
|
+
|
|
78
|
+
proxlb_data (Dict[str, Any]): A dictionary containing node metrics and metadata.
|
|
79
|
+
init (bool): A flag indicating whether to initialize the 'before' statistics
|
|
80
|
+
(True) or update the 'after' statistics (False). Default is True.
|
|
81
|
+
"""
|
|
82
|
+
logger.debug("Starting: log_node_metrics.")
|
|
83
|
+
nodes_usage_memory = " | ".join([f"{key}: {value['memory_used_percent']:.2f}%" for key, value in proxlb_data["nodes"].items()])
|
|
84
|
+
nodes_assigned_memory = " | ".join([f"{key}: {value['memory_assigned_percent']:.2f}%" for key, value in proxlb_data["nodes"].items()])
|
|
85
|
+
nodes_usage_cpu = " | ".join([f"{key}: {value['cpu_used_percent']:.2f}%" for key, value in proxlb_data["nodes"].items()])
|
|
86
|
+
nodes_usage_disk = " | ".join([f"{key}: {value['disk_used_percent']:.2f}%" for key, value in proxlb_data["nodes"].items()])
|
|
87
|
+
|
|
88
|
+
if init:
|
|
89
|
+
proxlb_data["meta"]["statistics"] = {"before": {"memory": nodes_usage_memory, "cpu": nodes_usage_cpu, "disk": nodes_usage_disk}, "after": {"memory": "", "cpu": "", "disk": ""}}
|
|
90
|
+
else:
|
|
91
|
+
proxlb_data["meta"]["statistics"]["after"] = {"memory": nodes_usage_memory, "cpu": nodes_usage_cpu, "disk": nodes_usage_disk}
|
|
92
|
+
|
|
93
|
+
logger.debug(f"Nodes usage memory: {nodes_usage_memory}")
|
|
94
|
+
logger.debug(f"Nodes usage memory assigned: {nodes_assigned_memory}")
|
|
95
|
+
logger.debug(f"Nodes usage cpu: {nodes_usage_cpu}")
|
|
96
|
+
logger.debug(f"Nodes usage disk: {nodes_usage_disk}")
|
|
97
|
+
logger.debug("Finished: log_node_metrics.")
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def get_version(print_version: bool = False) -> None:
|
|
101
|
+
"""
|
|
102
|
+
Returns the current version of ProxLB and optionally prints it to stdout.
|
|
103
|
+
|
|
104
|
+
Parameters:
|
|
105
|
+
print_version (bool): If True, prints the version information to stdout and exits the program.
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
None
|
|
109
|
+
"""
|
|
110
|
+
if print_version:
|
|
111
|
+
print(f"{utils.version.__app_name__} version: {utils.version.__version__}\n(C) 2025 by {utils.version.__author__}\n{utils.version.__url__}")
|
|
112
|
+
sys.exit(0)
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def get_daemon_mode(proxlb_config: Dict[str, Any]) -> None:
|
|
116
|
+
"""
|
|
117
|
+
Checks if the daemon mode is active and handles the scheduling accordingly.
|
|
118
|
+
|
|
119
|
+
Parameters:
|
|
120
|
+
proxlb_config (Dict[str, Any]): A dictionary containing the ProxLB configuration.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
None
|
|
124
|
+
"""
|
|
125
|
+
logger.debug("Starting: get_daemon_mode.")
|
|
126
|
+
if proxlb_config.get("service", {}).get("daemon", True):
|
|
127
|
+
|
|
128
|
+
# Validate schedule format which changed in v1.1.1
|
|
129
|
+
if type(proxlb_config["service"].get("schedule", None)) != dict:
|
|
130
|
+
logger.error("Invalid format for schedule. Please use 'hours' or 'minutes'.")
|
|
131
|
+
sys.exit(1)
|
|
132
|
+
|
|
133
|
+
# Convert hours to seconds
|
|
134
|
+
if proxlb_config["service"]["schedule"].get("format", "hours") == "hours":
|
|
135
|
+
sleep_seconds = proxlb_config.get("service", {}).get("schedule", {}).get("interval", 12) * 3600
|
|
136
|
+
# Convert minutes to seconds
|
|
137
|
+
elif proxlb_config["service"]["schedule"].get("format", "hours") == "minutes":
|
|
138
|
+
sleep_seconds = proxlb_config.get("service", {}).get("schedule", {}).get("interval", 720) * 60
|
|
139
|
+
else:
|
|
140
|
+
logger.error("Invalid format for schedule. Please use 'hours' or 'minutes'.")
|
|
141
|
+
sys.exit(1)
|
|
142
|
+
|
|
143
|
+
logger.info(f"Daemon mode active: Next run in: {proxlb_config.get('service', {}).get('schedule', {}).get('interval', 12)} {proxlb_config['service']['schedule'].get('format', 'hours')}.")
|
|
144
|
+
time.sleep(sleep_seconds)
|
|
145
|
+
|
|
146
|
+
else:
|
|
147
|
+
logger.debug("Successfully executed ProxLB. Daemon mode not active - stopping.")
|
|
148
|
+
print("Daemon mode not active - stopping.")
|
|
149
|
+
sys.exit(0)
|
|
150
|
+
|
|
151
|
+
logger.debug("Finished: get_daemon_mode.")
|
|
152
|
+
|
|
153
|
+
@staticmethod
|
|
154
|
+
def get_service_delay(proxlb_config: Dict[str, Any]) -> None:
|
|
155
|
+
"""
|
|
156
|
+
Checks if a start up delay for the service is defined and waits to proceed until
|
|
157
|
+
the time is up.
|
|
158
|
+
|
|
159
|
+
Parameters:
|
|
160
|
+
proxlb_config (Dict[str, Any]): A dictionary containing the ProxLB configuration.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
None
|
|
164
|
+
"""
|
|
165
|
+
logger.debug("Starting: get_service_delay.")
|
|
166
|
+
if proxlb_config.get("service", {}).get("delay", {}).get("enable", False):
|
|
167
|
+
|
|
168
|
+
# Convert hours to seconds
|
|
169
|
+
if proxlb_config["service"]["delay"].get("format", "hours") == "hours":
|
|
170
|
+
sleep_seconds = proxlb_config.get("service", {}).get("delay", {}).get("time", 1) * 3600
|
|
171
|
+
# Convert minutes to seconds
|
|
172
|
+
elif proxlb_config["service"]["delay"].get("format", "hours") == "minutes":
|
|
173
|
+
sleep_seconds = proxlb_config.get("service", {}).get("delay", {}).get("time", 60) * 60
|
|
174
|
+
else:
|
|
175
|
+
logger.error("Invalid format for service delay. Please use 'hours' or 'minutes'.")
|
|
176
|
+
sys.exit(1)
|
|
177
|
+
|
|
178
|
+
logger.info(f"Service delay active: First run in: {proxlb_config.get('service', {}).get('delay', {}).get('time', 1)} {proxlb_config['service']['delay'].get('format', 'hours')}.")
|
|
179
|
+
time.sleep(sleep_seconds)
|
|
180
|
+
|
|
181
|
+
else:
|
|
182
|
+
logger.debug("Service delay not active. Proceeding without delay.")
|
|
183
|
+
|
|
184
|
+
logger.debug("Finished: get_service_delay.")
|
|
185
|
+
|
|
186
|
+
@staticmethod
|
|
187
|
+
def print_json(proxlb_config: Dict[str, Any], print_json: bool = False) -> None:
|
|
188
|
+
"""
|
|
189
|
+
Prints the calculated balancing matrix as a JSON output to stdout.
|
|
190
|
+
|
|
191
|
+
Parameters:
|
|
192
|
+
proxlb_config (Dict[str, Any]): A dictionary containing the ProxLB configuration.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
None
|
|
196
|
+
"""
|
|
197
|
+
logger.debug("Starting: print_json.")
|
|
198
|
+
if print_json:
|
|
199
|
+
# Create a filtered list by stripping the 'meta' key from the proxlb_config dictionary
|
|
200
|
+
# to make sure that no credentials are leaked.
|
|
201
|
+
filtered_data = {k: v for k, v in proxlb_config.items() if k != "meta"}
|
|
202
|
+
print(json.dumps(filtered_data, indent=4))
|
|
203
|
+
|
|
204
|
+
logger.debug("Finished: print_json.")
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def handler_sighup(signum: int, frame: FrameType) -> None:
|
|
208
|
+
"""
|
|
209
|
+
Signal handler for SIGHUP.
|
|
210
|
+
|
|
211
|
+
This method is triggered when the process receives a SIGHUP signal.
|
|
212
|
+
It sets the `proxlb_reload` class variable to True to indicate that
|
|
213
|
+
configuration should be reloaded in the main loop.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
signum (int): The signal number (expected to be signal.SIGHUP).
|
|
217
|
+
frame (frame object): Current stack frame (unused but required by signal handler signature).
|
|
218
|
+
"""
|
|
219
|
+
logger.debug("Starting: handle_sighup.")
|
|
220
|
+
logger.debug("Got SIGHUP signal. Reloading...")
|
|
221
|
+
Helper.proxlb_reload = True
|
|
222
|
+
logger.debug("Finished: handle_sighup.")
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def handler_sigint(signum: int, frame: FrameType) -> None:
|
|
226
|
+
"""
|
|
227
|
+
Signal handler for SIGINT. (triggered by CTRL+C).
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
signum (int): The signal number (e.g., SIGINT).
|
|
231
|
+
frame (FrameType): The current stack frame when the signal was received.
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
None
|
|
235
|
+
"""
|
|
236
|
+
exit_message = "ProxLB has been successfully terminated by user."
|
|
237
|
+
logger.debug(exit_message)
|
|
238
|
+
print(f"\n {exit_message}")
|
|
239
|
+
sys.exit(0)
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def get_host_port_from_string(host_object):
|
|
243
|
+
"""
|
|
244
|
+
Parses a string containing a host (IPv4, IPv6, or hostname) and an optional port, and returns a tuple of (host, port).
|
|
245
|
+
|
|
246
|
+
Supported formats:
|
|
247
|
+
- Hostname or IPv4 without port: "example.com" or "192.168.0.1"
|
|
248
|
+
- Hostname or IPv4 with port: "example.com:8006" or "192.168.0.1:8006"
|
|
249
|
+
- IPv6 in brackets with optional port: "[fc00::1]" or "[fc00::1]:8006"
|
|
250
|
+
- IPv6 without brackets, port is assumed after last colon: "fc00::1:8006"
|
|
251
|
+
|
|
252
|
+
If no port is specified, port 8006 is used as the default.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
host_object (str): A string representing a host with or without a port.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
tuple: A tuple (host: str, port: int)
|
|
259
|
+
"""
|
|
260
|
+
logger.debug("Starting: get_host_port_from_string.")
|
|
261
|
+
|
|
262
|
+
# IPv6 (with or without port, written in brackets)
|
|
263
|
+
match = re.match(r'^\[(.+)\](?::(\d+))?$', host_object)
|
|
264
|
+
if match:
|
|
265
|
+
host = match.group(1)
|
|
266
|
+
port = int(match.group(2)) if match.group(2) else 8006
|
|
267
|
+
return host, port
|
|
268
|
+
|
|
269
|
+
# Count colons to identify IPv6 addresses without brackets
|
|
270
|
+
colon_count = host_object.count(':')
|
|
271
|
+
|
|
272
|
+
# IPv4 or hostname without port
|
|
273
|
+
if colon_count == 0:
|
|
274
|
+
return host_object, 8006
|
|
275
|
+
|
|
276
|
+
# IPv4 or hostname with port
|
|
277
|
+
elif colon_count == 1:
|
|
278
|
+
host, port = host_object.split(':')
|
|
279
|
+
return host, int(port)
|
|
280
|
+
|
|
281
|
+
# IPv6 (with or without port, assume last colon is port)
|
|
282
|
+
else:
|
|
283
|
+
parts = host_object.rsplit(':', 1)
|
|
284
|
+
try:
|
|
285
|
+
port = int(parts[1])
|
|
286
|
+
return parts[0], port
|
|
287
|
+
except ValueError:
|
|
288
|
+
return host_object, 8006
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def validate_node_presence(node: str, nodes: Dict[str, Any]) -> bool:
|
|
292
|
+
"""
|
|
293
|
+
Validates whether a given node exists in the provided cluster nodes dictionary.
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
node (str): The name of the node to validate.
|
|
297
|
+
nodes (Dict[str, Any]): A dictionary containing cluster information.
|
|
298
|
+
Must include a "nodes" key mapping to a dict of available nodes.
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
bool: True if the node exists in the cluster, False otherwise.
|
|
302
|
+
"""
|
|
303
|
+
logger.debug("Starting: validate_node_presence.")
|
|
304
|
+
|
|
305
|
+
if node in nodes["nodes"].keys():
|
|
306
|
+
logger.info(f"Node {node} found in cluster. Applying pinning.")
|
|
307
|
+
logger.debug("Finished: validate_node_presence.")
|
|
308
|
+
return True
|
|
309
|
+
else:
|
|
310
|
+
logger.warning(f"Node {node} not found in cluster. Not applying pinning!")
|
|
311
|
+
logger.debug("Finished: validate_node_presence.")
|
|
312
|
+
return False
|
|
313
|
+
|
|
314
|
+
@staticmethod
|
|
315
|
+
def tcp_connect_test(addr_family: int, host: str, port: int, timeout: int) -> tuple[bool, int | None]:
|
|
316
|
+
"""
|
|
317
|
+
Attempt a TCP connection to the specified host and port to test the reachability.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
addr_family (int): Address family for the socket (e.g., socket.AF_INET for IPv4, socket.AF_INET6 for IPv6).
|
|
321
|
+
host (str): The hostname or IP address to connect to.
|
|
322
|
+
port (int): The port number to connect to.
|
|
323
|
+
timeout (int): Connection timeout in seconds.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
tuple[bool, int | None]: A tuple containing:
|
|
327
|
+
- bool: True if the connection was successful, False otherwise.
|
|
328
|
+
- int | None: None if the connection was successful, otherwise the errno code indicating the reason for failure.
|
|
329
|
+
"""
|
|
330
|
+
test_socket = socket.socket(addr_family, socket.SOCK_STREAM)
|
|
331
|
+
test_socket.settimeout(timeout)
|
|
332
|
+
|
|
333
|
+
try:
|
|
334
|
+
rc = test_socket.connect_ex((host, port))
|
|
335
|
+
return (rc == 0, rc if rc != 0 else None)
|
|
336
|
+
finally:
|
|
337
|
+
test_socket.close()
|
proxlb/utils/logger.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The SystemdLogger class provides a singleton logger that integrates with systemd's journal if available.
|
|
3
|
+
It dynamically evaluates the environment and adjusts the logger accordingly.
|
|
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 logging
|
|
12
|
+
import sys
|
|
13
|
+
try:
|
|
14
|
+
from systemd.journal import JournalHandler
|
|
15
|
+
SYSTEMD_PRESENT = True
|
|
16
|
+
except ImportError:
|
|
17
|
+
SYSTEMD_PRESENT = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SystemdLogger:
|
|
21
|
+
"""
|
|
22
|
+
The SystemdLogger class provides a singleton logger that integrates with systemd's journal if available.
|
|
23
|
+
It dynamically evaluates the environment and adjusts the logger accordingly.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
instance (SystemdLogger): Singleton instance of the SystemdLogger class.
|
|
27
|
+
|
|
28
|
+
Methods:
|
|
29
|
+
__new__(cls, name: str = "ProxLB", level: str = logging.INFO) -> 'SystemdLogger':
|
|
30
|
+
Creates a new instance of the SystemdLogger class or returns the existing instance.
|
|
31
|
+
|
|
32
|
+
initialize_logger(self, name: str, level: str) -> None:
|
|
33
|
+
Initializes the logger with the given name and log level. Adds a JournalHandler if systemd is present.
|
|
34
|
+
|
|
35
|
+
set_log_level(self, level: str) -> None:
|
|
36
|
+
Sets the log level for the logger and all its handlers.
|
|
37
|
+
|
|
38
|
+
debug(self, msg: str) -> str:
|
|
39
|
+
Logs a message with level DEBUG.
|
|
40
|
+
|
|
41
|
+
info(self, msg: str) -> str:
|
|
42
|
+
Logs a message with level INFO.
|
|
43
|
+
|
|
44
|
+
warning(self, msg: str) -> str:
|
|
45
|
+
Logs a message with level WARNING.
|
|
46
|
+
|
|
47
|
+
error(self, msg: str) -> str:
|
|
48
|
+
Logs a message with level ERROR.
|
|
49
|
+
|
|
50
|
+
critical(self, msg: str) -> str:
|
|
51
|
+
Logs a message with level CRITICAL.
|
|
52
|
+
"""
|
|
53
|
+
# Create a singleton instance variable
|
|
54
|
+
instance = None
|
|
55
|
+
|
|
56
|
+
def __new__(cls, name: str = "ProxLB", level: str = logging.INFO) -> 'SystemdLogger':
|
|
57
|
+
"""
|
|
58
|
+
Creating a new systemd logger class based on a given logging name
|
|
59
|
+
and its logging level/verbosity.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
name (str): The application name that is being used for the logger.
|
|
63
|
+
level (str): The log level defined as a string (e.g.: INFO).
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
SystemdLogger: The systemd logger object.
|
|
67
|
+
"""
|
|
68
|
+
# Check if instance already exists, otherwise create a new one
|
|
69
|
+
if cls.instance is None:
|
|
70
|
+
cls.instance = super(SystemdLogger, cls).__new__(cls)
|
|
71
|
+
cls.instance.initialize_logger(name, level)
|
|
72
|
+
return cls.instance
|
|
73
|
+
|
|
74
|
+
def initialize_logger(self, name: str, level: str) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Initializing the systemd logger class based on a given logging name
|
|
77
|
+
and its logging level/verbosity.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
name (str): The application name that is being used for the logger.
|
|
81
|
+
level (str): The log level defined as a string (e.g.: INFO).
|
|
82
|
+
"""
|
|
83
|
+
self.logger = logging.getLogger(name)
|
|
84
|
+
self.logger.setLevel(level)
|
|
85
|
+
|
|
86
|
+
# Create a logging handler depending on the
|
|
87
|
+
# capabilities of the underlying OS where systemd
|
|
88
|
+
# logging is preferred.
|
|
89
|
+
if SYSTEMD_PRESENT:
|
|
90
|
+
# Add a JournalHandler for systemd integration
|
|
91
|
+
handler = JournalHandler(SYSLOG_IDENTIFIER="ProxLB")
|
|
92
|
+
else:
|
|
93
|
+
# Add a stdout handler as a fallback
|
|
94
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
95
|
+
|
|
96
|
+
handler.setLevel(level)
|
|
97
|
+
# Set a formatter to include the logger's name and log message
|
|
98
|
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
99
|
+
handler.setFormatter(formatter)
|
|
100
|
+
# Add handler to logger
|
|
101
|
+
self.logger.addHandler(handler)
|
|
102
|
+
|
|
103
|
+
def set_log_level(self, level: str) -> None:
|
|
104
|
+
"""
|
|
105
|
+
Modifies and sets the log level on the given log level.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
level (str): The log level defined as a string (e.g.: INFO).
|
|
109
|
+
"""
|
|
110
|
+
self.logger.setLevel(level)
|
|
111
|
+
|
|
112
|
+
for handler in self.logger.handlers:
|
|
113
|
+
handler.setLevel(level)
|
|
114
|
+
|
|
115
|
+
self.logger.debug("Set to debug level")
|
|
116
|
+
|
|
117
|
+
# Handle systemd log levels
|
|
118
|
+
def debug(self, msg: str) -> str:
|
|
119
|
+
"""
|
|
120
|
+
Logger out for messages of type: DEBUG
|
|
121
|
+
"""
|
|
122
|
+
self.logger.debug(msg)
|
|
123
|
+
|
|
124
|
+
def info(self, msg: str) -> str:
|
|
125
|
+
"""
|
|
126
|
+
Logger out for messages of type: INFO
|
|
127
|
+
"""
|
|
128
|
+
self.logger.info(msg)
|
|
129
|
+
|
|
130
|
+
def warning(self, msg: str) -> str:
|
|
131
|
+
"""
|
|
132
|
+
Logger out for messages of type: WARNING
|
|
133
|
+
"""
|
|
134
|
+
self.logger.warning(msg)
|
|
135
|
+
|
|
136
|
+
def error(self, msg: str) -> str:
|
|
137
|
+
"""
|
|
138
|
+
Logger out for messages of type: ERROR
|
|
139
|
+
"""
|
|
140
|
+
self.logger.error(msg)
|
|
141
|
+
|
|
142
|
+
def critical(self, msg: str) -> str:
|
|
143
|
+
"""
|
|
144
|
+
Logger out for messages of type: CRITICAL
|
|
145
|
+
"""
|
|
146
|
+
self.logger.critical(msg)
|