Skip to content

Commit 208d3bf

Browse files
committed
feature(patching): Add initial automated node patching support
Fixes: #216
1 parent 8c473b4 commit 208d3bf

File tree

5 files changed

+190
-0
lines changed

5 files changed

+190
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,9 @@ The following options can be set in the configuration file `proxlb.yaml`:
274274
| | balanciness | | 10 | `Int` | The maximum delta of resource usage between node with highest and lowest usage. |
275275
| | method | | memory | `Str` | The balancing method that should be used. [values: `memory` (default), `cpu`, `disk`]|
276276
| | mode | | used | `Str` | The balancing mode that should be used. [values: `used` (default), `assigned`] |
277+
| `patching` | | | | | |
278+
| | enable | | True | `Bool` | Enables the guest balancing.|
279+
| | maximum_nodes | | 1 | `Int` | How many nodes may be patched at the same time during a ProxLB run. |
277280
| `service` | | | | | |
278281
| | daemon | | True | `Bool` | If daemon mode should be activated. |
279282
| | `schedule` | | | `Dict` | Schedule config block for rebalancing. |

config/proxlb_example.yaml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ balancing:
3232
method: memory
3333
mode: used
3434

35+
patching:
36+
enable: True
37+
maximum_nodes: 1
38+
3539
service:
3640
daemon: True
3741
schedule:

proxlb/main.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from models.groups import Groups
2424
from models.calculations import Calculations
2525
from models.balancing import Balancing
26+
from models.patching import Patching
2627
from utils.helper import Helper
2728

2829

@@ -78,6 +79,10 @@ def main():
7879
proxlb_data = {**meta, **nodes, **guests, **groups}
7980
Helper.log_node_metrics(proxlb_data)
8081

82+
# Perform preparing patching actions via Proxmox API
83+
if proxlb_data["meta"]["patching"].get("enable", False):
84+
Patching(proxmox_api, proxlb_data)
85+
8186
# Update the initial node resource assignments
8287
# by the previously created groups.
8388
Calculations.set_node_assignments(proxlb_data)
@@ -95,6 +100,11 @@ def main():
95100
# Validate if the JSON output should be
96101
# printed to stdout
97102
Helper.print_json(proxlb_data, cli_args.json)
103+
104+
# Perform patching actions via Proxmox API
105+
if proxlb_data["meta"]["patching"].get("enable", False):
106+
Patching(proxmox_api, proxlb_data, calculations_done=True)
107+
98108
# Validate daemon mode
99109
Helper.get_daemon_mode(proxlb_config)
100110

proxlb/models/nodes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ def get_nodes(proxmox_api: any, proxlb_config: Dict[str, Any]) -> Dict[str, Any]
6161
nodes["nodes"][node["node"]] = {}
6262
nodes["nodes"][node["node"]]["name"] = node["node"]
6363
nodes["nodes"][node["node"]]["maintenance"] = False
64+
nodes["nodes"][node["node"]]["patching"] = False
6465
nodes["nodes"][node["node"]]["cpu_total"] = node["maxcpu"]
6566
nodes["nodes"][node["node"]]["cpu_assigned"] = 0
6667
nodes["nodes"][node["node"]]["cpu_used"] = node["cpu"] * node["maxcpu"]

proxlb/models/patching.py

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
"""
2+
The Balancing class is responsible for processing workloads on Proxmox clusters.
3+
It processes the previously generated data (held in proxlb_data) and moves guests
4+
and other supported types across Proxmox clusters based on the defined values by an operator.
5+
"""
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+
from utils.logger import SystemdLogger
14+
from typing import Dict, Any
15+
16+
logger = SystemdLogger()
17+
18+
19+
class Patching:
20+
"""
21+
Patching
22+
23+
This class is responsible for orchestrating the patching process of nodes in a Proxmox cluster, based on the provided ProxLB data and using the Proxmox API. It determines which nodes require patching, selects nodes for patching according to configuration, and executes patching actions while ensuring no running guests are present.
24+
25+
Functions:
26+
-----------
27+
__init__(self, proxmox_api: any, proxlb_data: Dict[str, Any], calculations_done: bool = False)
28+
- Initializes the Patching class and triggers either patch preparation or execution based on the calculations_done flag.
29+
- Inputs:
30+
- proxmox_api: Proxmox API client instance.
31+
- proxlb_data: Dictionary containing cluster and node information.
32+
- calculations_done: Boolean flag to determine operation mode.
33+
- Outputs: None
34+
35+
val_nodes_packages(self, proxmox_api: any, proxlb_data: Dict[str, Any]) -> Dict[str, Any]
36+
- Checks each node for available package updates and updates their patching status.
37+
- Inputs:
38+
- proxmox_api: Proxmox API client instance.
39+
- proxlb_data: Dictionary with node and maintenance information.
40+
- Outputs:
41+
- Updated proxlb_data dictionary with patching status for each node.
42+
43+
get_nodes_to_patch(self, proxlb_data: Dict[str, Any]) -> Dict[str, Any]
44+
- Selects nodes to patch in the current run based on configuration and node status.
45+
- Inputs:
46+
- proxlb_data: Dictionary with ProxLB configuration and node information.
47+
- Outputs:
48+
- Updated proxlb_data with selected nodes for patching in this run.
49+
50+
patch_node(self, proxmox_api: any, proxlb_data: Dict[str, Any])
51+
- Executes the patching process for selected nodes, ensuring no running guests are present before proceeding.
52+
- Inputs:
53+
- proxmox_api: Proxmox API client instance.
54+
- proxlb_data: Dictionary with metadata and list of nodes to patch.
55+
- Outputs: None
56+
"""
57+
def __init__(self, proxmox_api: any, proxlb_data: Dict[str, Any], calculations_done: bool = False):
58+
"""
59+
Initializes the Patching class with the provided ProxLB data.
60+
"""
61+
if not calculations_done:
62+
logger.debug("Starting: Patching preparations.")
63+
self.val_nodes_packages(proxmox_api, proxlb_data)
64+
self.get_nodes_to_patch(proxlb_data)
65+
logger.debug("Finished: Patching preparations.")
66+
else:
67+
logger.debug("Starting: Patching executions.")
68+
self.patch_node(proxmox_api, proxlb_data)
69+
logger.debug("Finished: Patching executions.")
70+
71+
def val_nodes_packages(self, proxmox_api: any, proxlb_data: Dict[str, Any]) -> Dict[str, Any]:
72+
"""
73+
Checks each node in the provided ProxLB data for available package updates using the Proxmox API,
74+
and updates the node's patching status accordingly.
75+
76+
Args:
77+
proxmox_api (Any): An instance of the Proxmox API client used to query node package updates.
78+
proxlb_data (Dict[str, Any]): A dictionary containing node information, including maintenance status.
79+
80+
Returns:
81+
Dict[str, Any]: The updated proxlb_data dictionary with patching status set for each node.
82+
"""
83+
logger.debug("Starting: val_nodes_packages.")
84+
85+
for node in proxlb_data['nodes'].keys():
86+
if proxlb_data['nodes'][node]['maintenance'] is False:
87+
node_pkgs = proxmox_api.nodes(node).apt.update.get()
88+
89+
if len(node_pkgs) > 0:
90+
proxlb_data['nodes'][node]['patching'] = True
91+
logger.debug(f"Node {node} has {len(node_pkgs)} packages to update.")
92+
else:
93+
logger.debug(f"Node {node} is up to date and has no packages to update.")
94+
95+
logger.debug("Finished: val_nodes_packages.")
96+
return proxlb_data
97+
98+
def get_nodes_to_patch(self, proxlb_data: Dict[str, Any]):
99+
"""
100+
Determines which nodes should be patched in the current run based on the ProxLB configuration and node status.
101+
102+
Args:
103+
proxlb_data (Dict[str, Any]): A dictionary containing ProxLB configuration, metadata, and node information.
104+
- proxlb_data["meta"]["patching"]["maximum_nodes"]: Maximum number of nodes to patch in this run (default is 1).
105+
- proxlb_data["nodes"]: Dictionary of node objects, each with a "patching" status and "name".
106+
107+
Returns:
108+
Dict[str, Any]: The updated proxlb_data dictionary with:
109+
- proxlb_data["meta"]["patching"]: List of node names selected for patching in this run.
110+
- proxlb_data["nodes"]: Updated node objects with "patching" status set to True for selected nodes.
111+
"""
112+
logger.debug("Starting: get_node_patching.")
113+
114+
nodes_patching_execution = []
115+
nodes_patching_count = proxlb_data["meta"].get("patching", {}).get("maximum_nodes", 1)
116+
nodes_patching = [node for node in proxlb_data["nodes"].values() if node["patching"]]
117+
nodes_patching_sorted = sorted(nodes_patching, key=lambda x: x["name"])
118+
logger.debug(f"{len(nodes_patching)} nodes are pending for patching. Patching up to {nodes_patching_count} nodes in this run.")
119+
120+
if len(nodes_patching_sorted) > 0:
121+
nodes = nodes_patching_sorted[:nodes_patching_count]
122+
for node in nodes:
123+
nodes_patching_execution.append(node["name"])
124+
proxlb_data['nodes'][node['name']]['patching'] = True
125+
logger.info(f"Node {node['name']} is going to be patched.")
126+
logger.info(f"Node {node['name']} is set to maintenance.")
127+
128+
proxlb_data["meta"]["patching"] = nodes_patching_execution
129+
130+
logger.debug("Finished: get_node_patching.")
131+
return proxlb_data
132+
133+
def patch_node(self, proxmox_api: any, proxlb_data:Dict[str, Any]):
134+
"""
135+
Patches Proxmox nodes if no running guests are detected.
136+
137+
This method iterates over the nodes specified in the `proxlb_data` dictionary under the "meta" -> "patching" key.
138+
For each node, it checks for running QEMU (VM) and LXC (container) guests using the provided Proxmox API client.
139+
If any guests are running, patching is skipped for that node and a warning is logged.
140+
If no guests are running, the method proceeds to patch the node (API calls are commented out) and logs the actions.
141+
Rebooting the node after patching is also logged (API call commented out).
142+
143+
Args:
144+
proxmox_api (Any): An instance of the Proxmox API client used to interact with the cluster.
145+
proxlb_data (Dict[str, Any]): A dictionary containing metadata, including the list of nodes to patch under "meta" -> "patching".
146+
147+
Returns:
148+
None
149+
"""
150+
logger.debug("Starting: patch_node.")
151+
152+
for node in proxlb_data["meta"]["patching"]:
153+
node_guests = []
154+
guests_vm = proxmox_api.nodes(node).qemu.get()
155+
guests_ct = proxmox_api.nodes(node).lxc.get()
156+
guests_vm = [vm for vm in guests_vm if vm["status"] == "running"]
157+
guests_ct = [ct for ct in guests_ct if ct["status"] == "running"]
158+
guests_count = len(guests_vm) + len(guests_ct)
159+
160+
# Do not proceed when we still have someho guests running on the node
161+
if guests_vm or guests_ct:
162+
logger.warning(f"Node {node} has {guests_count} running guest(s). Patching will be skipped.")
163+
else:
164+
logger.debug(f"Node {node} has no running guests. Proceeding with patching.")
165+
# Upgrading a node by API requires the patched 'pve-manager' package
166+
# from gyptazy including the new 'upgrade' endpoint.
167+
#proxmox_api.nodes(node).apt.upgrade.post()
168+
logger.debug(f"Node {node} has been patched.")
169+
logger.debug(f"Node {node} is going to reboot.")
170+
#proxmox_api.nodes(node).status.reboot.post()
171+
172+
logger.debug("Finished: patch_node.")

0 commit comments

Comments
 (0)