lazyprox 0.9.1__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.
Files changed (46) hide show
  1. lazyprox/__init__.py +30 -0
  2. lazyprox/app/__init__.py +3 -0
  3. lazyprox/app/app.py +389 -0
  4. lazyprox/app/styles.tcss +177 -0
  5. lazyprox/common/__init__.py +5 -0
  6. lazyprox/common/config.py +83 -0
  7. lazyprox/common/singleton.py +32 -0
  8. lazyprox/common/utils.py +63 -0
  9. lazyprox/core/__init__.py +1 -0
  10. lazyprox/core/bulk.py +241 -0
  11. lazyprox/core/cluster_state.py +19 -0
  12. lazyprox/core/guest_operations.py +43 -0
  13. lazyprox/core/resource_actions.py +120 -0
  14. lazyprox/data/__init__.py +3 -0
  15. lazyprox/data/proxmox.py +126 -0
  16. lazyprox/screens/__init__.py +19 -0
  17. lazyprox/screens/bulk.py +252 -0
  18. lazyprox/screens/confirmation_screen.py +31 -0
  19. lazyprox/screens/dashboard.py +60 -0
  20. lazyprox/screens/filter.py +20 -0
  21. lazyprox/screens/select_action.py +22 -0
  22. lazyprox/screens/select_destination.py +33 -0
  23. lazyprox/screens/select_server.py +23 -0
  24. lazyprox/screens/waiting.py +8 -0
  25. lazyprox/widgets/__init__.py +13 -0
  26. lazyprox/widgets/base_datatable_widget.py +213 -0
  27. lazyprox/widgets/details_views/__init__.py +23 -0
  28. lazyprox/widgets/details_views/graph_base.py +9 -0
  29. lazyprox/widgets/details_views/graph_widget.py +89 -0
  30. lazyprox/widgets/details_views/lxc_graph.py +136 -0
  31. lazyprox/widgets/details_views/lxc_summary.py +94 -0
  32. lazyprox/widgets/details_views/node_graph.py +137 -0
  33. lazyprox/widgets/details_views/node_summary.py +97 -0
  34. lazyprox/widgets/details_views/node_tasks.py +154 -0
  35. lazyprox/widgets/details_views/qemu_graph.py +135 -0
  36. lazyprox/widgets/details_views/qemu_summary.py +72 -0
  37. lazyprox/widgets/details_views/summary_base.py +24 -0
  38. lazyprox/widgets/details_widget.py +65 -0
  39. lazyprox/widgets/lxc_widget.py +95 -0
  40. lazyprox/widgets/node_widget.py +73 -0
  41. lazyprox/widgets/qemu_widget.py +94 -0
  42. lazyprox-0.9.1.dist-info/METADATA +108 -0
  43. lazyprox-0.9.1.dist-info/RECORD +46 -0
  44. lazyprox-0.9.1.dist-info/WHEEL +4 -0
  45. lazyprox-0.9.1.dist-info/entry_points.txt +3 -0
  46. lazyprox-0.9.1.dist-info/licenses/LICENSE +21 -0
lazyprox/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ import argparse
2
+ import sys
3
+
4
+ from pydantic import ValidationError
5
+
6
+ from lazyprox.app import LazyProx
7
+ from lazyprox.common import Config
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(description="LazyProx Application")
12
+ parser.add_argument("-c", "--config", type=str, required=False, help="Path to the configuration file")
13
+ args = parser.parse_args()
14
+ try:
15
+ Config.load_config(config_file_path=args.config)
16
+ except ValidationError:
17
+ print(
18
+ "Something went wrong when loading config file. Please check your configuration against the documentation.",
19
+ file=sys.stderr,
20
+ )
21
+ sys.exit(1)
22
+ except FileNotFoundError:
23
+ print("Cannot find lazyprox config file.", file=sys.stderr)
24
+ sys.exit(1)
25
+ except Exception as e: # noqa: BLE001
26
+ print(f"Something went wrong: {e}", file=sys.stderr)
27
+ sys.exit(2)
28
+
29
+ app = LazyProx()
30
+ app.run()
@@ -0,0 +1,3 @@
1
+ from .app import LazyProx
2
+
3
+ __all__ = ["LazyProx"]
lazyprox/app/app.py ADDED
@@ -0,0 +1,389 @@
1
+ import subprocess
2
+ from collections.abc import Callable
3
+ from itertools import product
4
+ from typing import Any, ClassVar, Literal
5
+
6
+ from textual import work
7
+ from textual.app import App
8
+ from textual.binding import Binding, BindingType
9
+ from textual.css.query import NoMatches
10
+ from textual.message import Message
11
+ from textual.screen import Screen
12
+ from textual.theme import Theme
13
+ from textual.timer import Timer
14
+ from textual.widgets import DataTable
15
+
16
+ from lazyprox.common import Config
17
+ from lazyprox.core.bulk import dispatch_bulk, first_operation, snapshot_guests
18
+ from lazyprox.core.resource_actions import ResourceActions
19
+ from lazyprox.data import ProxmoxData
20
+ from lazyprox.screens import (
21
+ ActionSelectionScreen,
22
+ BulkScreen,
23
+ ConfirmationScreen,
24
+ DashboardScreen,
25
+ DestinationSelectionScreen,
26
+ FilterScreen,
27
+ ServerSelectionScreen,
28
+ WaitingScreen,
29
+ )
30
+ from lazyprox.widgets import LxcWidget, NodeWidget, QemuWidget
31
+ from lazyprox.widgets.details_views import NodeTasksWidget
32
+
33
+
34
+ class LazyProx(App):
35
+ BINDINGS: ClassVar[list[BindingType]] = [
36
+ Binding("D", "dump_debug", "Dump debug", show=False),
37
+ ("b", "bulk", "Bulk"),
38
+ ("f", "filter", "Filter"),
39
+ ("s", "change_server", "Change server"),
40
+ ("q", "quit", "Quit"),
41
+ ]
42
+
43
+ CSS_PATH = "styles.tcss"
44
+ SCREENS: ClassVar[dict[str, Callable[[], Screen[Any]]]] = {
45
+ "select_server": ServerSelectionScreen,
46
+ "waiting": WaitingScreen,
47
+ "dashboard": DashboardScreen,
48
+ }
49
+
50
+ class _AppMessage(Message):
51
+ def __init__(self, msg: dict | None = None):
52
+ self.msg = msg or {}
53
+ super().__init__()
54
+
55
+ class ProxmoxInitialized(_AppMessage):
56
+ """Sent when app starts or a server is selected."""
57
+
58
+ class NodesUpdated(_AppMessage):
59
+ """Sent when node data is refreshed."""
60
+
61
+ class LxcsUpdated(_AppMessage):
62
+ """Sent when LXC container data is refreshed."""
63
+
64
+ class QemusUpdated(_AppMessage):
65
+ """Sent when QEMU VM data is refreshed."""
66
+
67
+ def __init__(self):
68
+ self.timers: list[Timer] = []
69
+ super().__init__()
70
+ theme_config = (Config.configuration or {}).get("theme")
71
+ if theme_config:
72
+ self.register_theme(Theme(name="lazyprox", **theme_config))
73
+ self.theme = "lazyprox"
74
+
75
+ def _notify_error(self, message: str) -> None:
76
+ self.notify(message=message, title="Something went wrong...", severity="error")
77
+
78
+ def handle_update_message(self, msg: Message) -> None:
79
+ success = msg.msg["success"]
80
+ text = msg.msg["text"]
81
+ if not success:
82
+ self._notify_error(text)
83
+ return
84
+
85
+ widget_for_update: dict[type, type] = {
86
+ self.NodesUpdated: NodeWidget,
87
+ self.LxcsUpdated: LxcWidget,
88
+ self.QemusUpdated: QemuWidget,
89
+ }
90
+
91
+ widget_cls = widget_for_update.get(type(msg))
92
+ if widget_cls is None:
93
+ return
94
+ try:
95
+ widget = self.screen.query_one(widget_cls)
96
+ widget.update_table_data()
97
+ except NoMatches:
98
+ return
99
+
100
+ def stop_timers(self) -> None:
101
+ for timer in self.timers:
102
+ timer.stop()
103
+ self.timers = []
104
+
105
+ async def select_server(self) -> None:
106
+ Config.server_index = await self.push_screen_wait("select_server")
107
+ self.push_screen("waiting")
108
+
109
+ def refresh_basic_nodes_data(self) -> None:
110
+ ProxmoxData.refresh_api_information(ProxmoxData.BASE_NODES)
111
+ nodes = ProxmoxData.p_prox_resources.get(ProxmoxData.BASE_NODES, [])
112
+ for node in nodes:
113
+ node_name: str = node["node"]
114
+ ProxmoxData.refresh_api_information(ProxmoxData.NODE_STATUS.format(node_name=node_name))
115
+ ProxmoxData.refresh_api_information(
116
+ ProxmoxData.NODE_GUEST_DATA.format(node_name=node_name, resource_type="qemu")
117
+ )
118
+ ProxmoxData.refresh_api_information(
119
+ ProxmoxData.NODE_GUEST_DATA.format(node_name=node_name, resource_type="lxc")
120
+ )
121
+
122
+ def refresh_rrd_nodes_data(self) -> None:
123
+ nodes = ProxmoxData.p_prox_resources.get(ProxmoxData.BASE_NODES, [])
124
+ for node in nodes:
125
+ node_name: str = node["node"]
126
+ ProxmoxData.refresh_api_information(ProxmoxData.NODE_RRDDATA.format(node_name=node_name))
127
+
128
+ def refresh_task_nodes_data(self) -> None:
129
+ ProxmoxData.refresh_api_information(ProxmoxData.CLUSTER_TASKS)
130
+
131
+ @work(thread=True)
132
+ def refresh_nodes_data(self, data_type: Literal["basic", "rrddata", "tasks"]) -> None:
133
+ try:
134
+ if data_type == "basic":
135
+ self.refresh_basic_nodes_data()
136
+ if data_type == "rrddata":
137
+ self.refresh_rrd_nodes_data()
138
+ if data_type == "tasks":
139
+ self.refresh_task_nodes_data()
140
+ msg = self.NodesUpdated({"success": True, "text": "Nodes data updated successfully"})
141
+ except Exception as e: # noqa: BLE001
142
+ msg = self.NodesUpdated({"success": False, "text": str(e)})
143
+ finally:
144
+ self.post_message(msg)
145
+
146
+ @work(thread=True)
147
+ def refresh_guests_data(self, data_type: str, guest_type: Literal["qemu", "lxc"]) -> None:
148
+ """Refresh guests data
149
+ Args:
150
+ data_type: API path for the type of data to collect.
151
+ Example:
152
+ nodes/{node_name}/{resource_type}/{vmid}/status/current
153
+ nodes/{node_name}/{resource_type}/{vmid}/rrddata
154
+ guest_type: type of the guest for which data should be collected
155
+ Returns:
156
+ None
157
+ """
158
+ guests = ProxmoxData.get_guests_list(guest_type)
159
+
160
+ msg_cls = {
161
+ "lxc": self.LxcsUpdated,
162
+ "qemu": self.QemusUpdated,
163
+ }[guest_type]
164
+
165
+ try:
166
+ for g in guests:
167
+ ProxmoxData.refresh_api_information(
168
+ data_type.format(node_name=g["node"], resource_type=guest_type, vmid=g["vmid"])
169
+ )
170
+
171
+ msg = msg_cls({"success": True, "text": f"{guest_type.capitalize()} data updated successfully"})
172
+ except Exception as e: # noqa: BLE001
173
+ msg = msg_cls({"success": False, "text": str(e)})
174
+ finally:
175
+ self.post_message(msg)
176
+
177
+ @work(thread=True)
178
+ async def initialize_proxmox(self) -> None:
179
+ """Initialize Proxmox and gets basic and rrd nodes information"""
180
+ # The Proxmox needs to be initialized with new data
181
+ # post_message is thread safe. That operation should not be blocking
182
+ # because the "waiting screen" will not work
183
+ # when finished message is sent with status
184
+ try:
185
+ ProxmoxData.initialize()
186
+ self.refresh_basic_nodes_data()
187
+ self.refresh_rrd_nodes_data()
188
+ self.refresh_task_nodes_data()
189
+ msg = self.ProxmoxInitialized({"success": True, "text": "Proxmox initialized successfully"})
190
+ except Exception as e: # noqa: BLE001
191
+ msg = self.ProxmoxInitialized({"success": False, "text": str(e)})
192
+ finally:
193
+ self.post_message(msg)
194
+
195
+ @work()
196
+ async def on_mount(self) -> None:
197
+ self.stop_timers()
198
+ await self.select_server()
199
+ self.initialize_proxmox()
200
+
201
+ def on_lazy_prox_proxmox_initialized(self, pim: ProxmoxInitialized) -> None:
202
+ """
203
+ Handler for ProxmoxInitialized message, this is called when Proxmox is initialized after server selection or application start
204
+ It will start timers/intervals to refresh data (for nodes and guests) periodically.
205
+ Args:
206
+ pim: message with information about Proxmox initialization status
207
+ Returns:
208
+ None
209
+ """
210
+ self.switch_screen("dashboard")
211
+ success = pim.msg["success"]
212
+ text = pim.msg["text"]
213
+ if not success:
214
+ self._notify_error(text)
215
+ else:
216
+ # now we can start timers to update data in the background
217
+ interval = Config.configuration.get("application").get("refresh_interval")
218
+ rrd_interval = Config.configuration.get("application").get("refresh_interval_rrddata")
219
+ tasks_interval = Config.configuration.get("application").get("refresh_interval_tasks")
220
+ self.timers.append(self.set_interval(interval, lambda: self.refresh_nodes_data("basic")))
221
+ self.timers.append(self.set_interval(rrd_interval, lambda: self.refresh_nodes_data("rrddata")))
222
+
223
+ self.timers.append(self.set_interval(tasks_interval, lambda: self.refresh_nodes_data("tasks")))
224
+
225
+ # before starting intervals for guests lets get asynchronously their data
226
+ # so it will be collected before timers collects data for the first time after interval
227
+ # in other words we are doing it to avoid situation when the application is started and there is no data about guests
228
+ # until the first interval is finished and data is collected for the first time
229
+ # "product" function is used to produce pairs of data type and guest type for which we want to collect data,
230
+ # so we will have pairs like ("status/current", "lxc"), ("rrddata", "lxc"), ("status/current", "qemu"), ("rrddata", "qemu")
231
+ pairs = list(product([ProxmoxData.GUEST_STATUS, ProxmoxData.GUEST_RRDDATA], ["lxc", "qemu"]))
232
+ for data_type, guest_type in pairs:
233
+ # collect data asap
234
+ self.refresh_guests_data(data_type, guest_type)
235
+ # then start intervals to collect data in the background
236
+ self.timers.append(
237
+ self.set_interval(
238
+ interval if data_type == "basic" else rrd_interval,
239
+ lambda t=data_type, g=guest_type: self.refresh_guests_data(t, g),
240
+ )
241
+ )
242
+
243
+ # update widgets if the data is available it will display gathered information
244
+ # in other case the data in widgets will be cleared
245
+ # the node task list is included so its filter is cleared when the server changes as well
246
+ for widget_type in [NodeWidget, LxcWidget, QemuWidget, NodeTasksWidget]:
247
+ try:
248
+ widget = self.screen.query_one(widget_type)
249
+ widget.filter_text = ""
250
+ widget.remove_border_indicator("(F)")
251
+ widget.update_table_data()
252
+ widget.action_scroll_top()
253
+ # set focus on the NodeWidget after Proxmox is initialized
254
+ self.screen.set_focus(widget) if widget_type is NodeWidget else None
255
+ except NoMatches:
256
+ continue
257
+
258
+ def on_lazy_prox_nodes_updated(self, nu: NodesUpdated) -> None:
259
+ self.handle_update_message(nu)
260
+
261
+ def on_lazy_prox_lxcs_updated(self, lu: LxcsUpdated) -> None:
262
+ self.handle_update_message(lu)
263
+
264
+ def on_lazy_prox_qemus_updated(self, qu: QemusUpdated) -> None:
265
+ self.handle_update_message(qu)
266
+
267
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
268
+ self.run_action_flow(event)
269
+
270
+ @work()
271
+ async def run_action_flow(self, event: DataTable.RowSelected) -> None:
272
+ resource_actions = ResourceActions(event)
273
+ list_items = resource_actions.get_actions_list()
274
+ resource_name = resource_actions.get_resource_name()
275
+
276
+ selected_action = await self.push_screen_wait(ActionSelectionScreen(items=list_items))
277
+ if selected_action is None:
278
+ return
279
+
280
+ if selected_action == "SSH":
281
+ with self.suspend():
282
+ # ssh has to block on purpose: the app is suspended and the
283
+ # terminal is handed over to the ssh session until the user exits.
284
+ subprocess.run(["ssh", resource_name], check=False) # noqa: ASYNC221
285
+ self.app.refresh()
286
+ return
287
+
288
+ target = None
289
+ if selected_action == "Migrate":
290
+ target = await self.push_screen_wait(
291
+ DestinationSelectionScreen(resource_name, resource_actions.get_migration_targets())
292
+ )
293
+ if target is None:
294
+ return
295
+
296
+ confirm_message = resource_actions.get_confirm_message(selected_action, target=target)
297
+ confirmed = await self.push_screen_wait(ConfirmationScreen(question=confirm_message))
298
+ if not confirmed:
299
+ return
300
+
301
+ try:
302
+ resource_actions.perform_action(selected_action, target=target)
303
+ message = (
304
+ f"Migration of {resource_name} requested"
305
+ if selected_action == "Migrate"
306
+ else f"{selected_action} on {resource_name} successful"
307
+ )
308
+ self.notify(message=message, title="Action", severity="information")
309
+ except Exception as e: # noqa: BLE001
310
+ self._notify_error(str(e))
311
+
312
+ @work()
313
+ async def action_change_server(self) -> None:
314
+ self.stop_timers()
315
+ await self.select_server()
316
+ self.initialize_proxmox()
317
+
318
+ def action_filter(self):
319
+ # filter screen can only be displayed when dashboard screen is active
320
+ if not isinstance(self.screen, DashboardScreen):
321
+ return
322
+
323
+ focused_widget = self.focused
324
+ if focused_widget is None:
325
+ return
326
+
327
+ def check_filter(text: str | None) -> None:
328
+ # add indicator that data in the DataTable is filtered
329
+ if text:
330
+ focused_widget.add_border_indicator("(F)")
331
+ else:
332
+ focused_widget.remove_border_indicator("(F)")
333
+ focused_widget.filter_text = text
334
+ focused_widget.update_table_data()
335
+
336
+ self.push_screen(FilterScreen(widget=focused_widget), check_filter)
337
+
338
+ def _bulk_highlighted_node(self) -> str | None:
339
+ try:
340
+ node_widget = self.screen.query_one(NodeWidget)
341
+ except NoMatches:
342
+ return None
343
+ if node_widget.row_count == 0 or node_widget.cursor_row < 0:
344
+ return None
345
+ return str(node_widget.get_row_at(node_widget.cursor_row)[0])
346
+
347
+ @work()
348
+ async def action_bulk(self) -> None:
349
+ if not isinstance(self.screen, DashboardScreen):
350
+ return
351
+
352
+ nodes, guests = snapshot_guests()
353
+ if first_operation(guests, nodes) is None:
354
+ self.notify(
355
+ message="No bulk operation is available",
356
+ title="Bulk",
357
+ severity="information",
358
+ )
359
+ return
360
+ highlighted = self._bulk_highlighted_node()
361
+ state = None
362
+ while True:
363
+ submission = await self.push_screen_wait(
364
+ BulkScreen(nodes, guests, highlighted_node=highlighted, state=state)
365
+ )
366
+ if submission is None:
367
+ return
368
+ confirmed = await self.push_screen_wait(ConfirmationScreen(question=submission.message))
369
+ if not confirmed:
370
+ state = submission.as_state()
371
+ continue
372
+ summary = dispatch_bulk(submission.guests, submission.operation, target=submission.target)
373
+ self.notify(
374
+ message=summary.message,
375
+ title="Bulk",
376
+ severity="warning" if summary.failed else "information",
377
+ )
378
+ return
379
+
380
+ def action_dump_debug(self):
381
+ try:
382
+ path = ProxmoxData.dump_resources()
383
+ self.notify(message=str(path), title="Dump file saved", severity="information")
384
+ except Exception as e: # noqa: BLE001
385
+ self._notify_error(str(e))
386
+
387
+ def action_quit(self) -> None:
388
+ self.stop_timers()
389
+ self.app.exit()
@@ -0,0 +1,177 @@
1
+ ServerSelectionScreen {
2
+ align: center middle;
3
+ width: 50;
4
+ }
5
+
6
+ #server_select {
7
+ width: 50;
8
+ }
9
+
10
+ ActionSelectionScreen {
11
+ align: center middle;
12
+ }
13
+
14
+ #action_select {
15
+ width: 50;
16
+ }
17
+
18
+ DestinationSelectionScreen {
19
+ align: center middle;
20
+ }
21
+
22
+ #destination_dialog {
23
+ width: 50;
24
+ height: auto;
25
+ border: round $primary;
26
+ padding: 1;
27
+ }
28
+
29
+ #destination_label {
30
+ width: 100%;
31
+ margin-bottom: 1;
32
+ text-align: center;
33
+ }
34
+
35
+ #destination_select {
36
+ width: 100%;
37
+ }
38
+
39
+ RightColumn {
40
+ width: 7fr;
41
+ height: 99vh;
42
+ border: round $primary;
43
+ }
44
+
45
+ LeftColumn {
46
+ width: 3fr;
47
+ }
48
+
49
+ GraphWidget {
50
+ width: 1fr;
51
+ margin_right: 1;
52
+ margin_left: 1;
53
+
54
+ }
55
+
56
+ .graphs_row {
57
+ height: 1fr;
58
+ margin_bottom: 1;
59
+ }
60
+
61
+ NodeWidget {
62
+ height: 2fr;
63
+ border: round $primary;
64
+ scrollbar-size: 1 1;
65
+ }
66
+
67
+ LxcWidget {
68
+ height: 4fr;
69
+ border: round $primary;
70
+ scrollbar-size: 1 1;
71
+ }
72
+
73
+ QemuWidget {
74
+ height: 4fr;
75
+ border: round $primary;
76
+ scrollbar-size: 1 1;
77
+ }
78
+
79
+ .focused {
80
+ border: round $accent
81
+ }
82
+
83
+ .unfocused {
84
+ border: round $primary
85
+ }
86
+
87
+ FilterScreen {
88
+ align: center middle;
89
+ }
90
+
91
+ #input_filter {
92
+ width: 50;
93
+ }
94
+
95
+ ConfirmationScreen {
96
+ align: center middle;
97
+ }
98
+
99
+ #confirm_dialog {
100
+ width: auto;
101
+ height: 9;
102
+ border: round $primary;
103
+ padding: 1;
104
+ }
105
+
106
+ #confirm_question {
107
+ min-width: 36;
108
+ margin-bottom: 1;
109
+ text-align: center;
110
+ }
111
+
112
+ #confirm_buttons {
113
+ align: center middle;
114
+ width: 100%;
115
+ }
116
+
117
+ #confirm_no {
118
+ margin-right: 1;
119
+ width: auto;
120
+ }
121
+
122
+ #confirm_yes {
123
+ width: auto;
124
+ }
125
+
126
+ .details_left {
127
+ width: 2fr;
128
+ }
129
+ .details_right {
130
+ width: 4fr;
131
+ }
132
+
133
+ BulkScreen {
134
+ align: center middle;
135
+ }
136
+
137
+ #bulk_dialog {
138
+ width: 80;
139
+ height: auto;
140
+ max-height: 90%;
141
+ border: round $primary;
142
+ padding: 1;
143
+ }
144
+
145
+ #bulk_operation {
146
+ width: 100%;
147
+ }
148
+
149
+ #bulk_migrate {
150
+ height: auto;
151
+ width: 100%;
152
+ }
153
+
154
+ #bulk_source {
155
+ width: 1fr;
156
+ margin-right: 1;
157
+ }
158
+
159
+ #bulk_target {
160
+ width: 1fr;
161
+ }
162
+
163
+ #bulk_guests {
164
+ height: 12;
165
+ margin-top: 1;
166
+ }
167
+
168
+ #bulk_buttons {
169
+ align: right middle;
170
+ height: auto;
171
+ margin-top: 1;
172
+ }
173
+
174
+ #bulk_cancel {
175
+ margin-right: 1;
176
+ }
177
+
@@ -0,0 +1,5 @@
1
+ from .config import Config
2
+ from .singleton import singleton
3
+ from .utils import calculate_uptime, format_bytes, format_timestamp, set_focus_border
4
+
5
+ __all__ = ["Config", "calculate_uptime", "format_bytes", "format_timestamp", "set_focus_border", "singleton"]
@@ -0,0 +1,83 @@
1
+ import os
2
+ import tomllib as toml
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+
6
+ from pydantic import AfterValidator, BaseModel
7
+ from textual.color import Color, ColorParseError
8
+
9
+ from .singleton import singleton
10
+
11
+
12
+ def _validate_color(value: str) -> str:
13
+ try:
14
+ Color.parse(value)
15
+ except ColorParseError as e:
16
+ raise ValueError(str(e)) from e
17
+ return value
18
+
19
+
20
+ ColorString = Annotated[str, AfterValidator(_validate_color)]
21
+
22
+
23
+ class ProxmoxServerConfig(BaseModel):
24
+ name: str
25
+ host: str
26
+ user: str
27
+ realm: str
28
+ token_name: str
29
+ token_value: str
30
+ verify_ssl: bool | None = True # default to True
31
+
32
+
33
+ class ApplicationConfig(BaseModel):
34
+ refresh_interval: float | None = 10.0
35
+ refresh_interval_rrddata: float | None = 30.0
36
+ refresh_interval_tasks: float | None = 15.0
37
+ debug_dump_dest: str | None = "lazyprox-dump.json"
38
+ rrddata_timeframe: str | None = "hour" # timeframe for rrd data
39
+ rrddata_cf: str | None = "AVERAGE" # consolidation function
40
+
41
+
42
+ class ThemeConfig(BaseModel):
43
+ primary: ColorString
44
+ secondary: ColorString
45
+ accent: ColorString
46
+ warning: ColorString
47
+ error: ColorString
48
+ success: ColorString
49
+ foreground: ColorString
50
+ background: ColorString
51
+ surface: ColorString
52
+ panel: ColorString
53
+ dark: bool = True
54
+
55
+
56
+ class ConfigDict(BaseModel):
57
+ server: list[ProxmoxServerConfig]
58
+ # use default values if missing
59
+ application: ApplicationConfig | None = ApplicationConfig()
60
+ theme: ThemeConfig | None = None
61
+
62
+
63
+ @singleton
64
+ class _Config:
65
+ configuration: ConfigDict = None
66
+ server_index: int = 0
67
+
68
+ def load_config(self, config_file_path: str | None = None, server_index: int = 0) -> None:
69
+ self.server_index = server_index
70
+
71
+ if not config_file_path:
72
+ # I'm not sure MacOS has this env variable
73
+ cfg_f = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / "lazyprox" / "config.toml"
74
+ else:
75
+ cfg_f = Path(config_file_path)
76
+
77
+ with open(cfg_f, "rb") as f:
78
+ cfg = toml.load(f)
79
+ # validate the configuration file
80
+ self.configuration = ConfigDict(**cfg).model_dump()
81
+
82
+
83
+ Config = _Config()