Debian Codegraph @

ansible_collections/community/proxmox/plugins/module_utils/proxmox_sdn.py

raw
1 #
2 # Copyright (c) 2025, Jana Hoch <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
8 ProxmoxAnsible,
9 ansible_to_proxmox_bool,
10 proxmox_to_ansible_bool,
11 )
12
13
14 class ProxmoxSdnAnsible(ProxmoxAnsible):
15 """Base Class for All Proxmox SDN Classes."""
16
17 def __init__(self, module):
18 super().__init__(module)
19 self.module = module
20 pve_major_version = self.version().version[0]
21 self._is_lock_and_rollback_supported = pve_major_version >= 9 # noqa: PLR2004
22
23 @property
24 def is_lock_and_rollback_supported(self) -> bool:
25 """Whether the Proxmox node supports SDN lock and rollback (PVE 9+)."""
26 return self._is_lock_and_rollback_supported
27
28 def get_global_sdn_lock(self) -> str:
29 """Acquire global SDN lock. Needed for any changes under SDN.
30
31 :return: lock-token
32 """
33 if not self.is_lock_and_rollback_supported:
34 return ""
35
36 try:
37 return self.proxmox_api.cluster().sdn().lock().post()
38 except Exception as e:
39 self.module.fail_json(msg=f"Failed to acquire global sdn lock {e}")
40
41 def apply_sdn_changes_and_release_lock(self, lock: str, release_lock: bool = True) -> None:
42 """Apply all SDN changes done under a lock token.
43
44 :param lock: Global SDN lock token
45 :param release_lock: if True release lock after successfully applying changes
46 """
47 lock_params = {}
48 if self.is_lock_and_rollback_supported:
49 lock_params = {"lock-token": lock, "release-lock": ansible_to_proxmox_bool(release_lock)}
50 try:
51 task_id = self.proxmox_api.cluster().sdn().put(**lock_params)
52 if not self.is_lock_and_rollback_supported:
53 # wait until reload network configuration has finished
54 # otherwise it will fail in proxmox when there are multiple reloads at the same time
55 self.api_task_complete(self.upid_to_node(task_id), task_id, 60)
56 except Exception as e:
57 if self.is_lock_and_rollback_supported:
58 self.rollback_sdn_changes_and_release_lock(lock)
59 self.module.fail_json(msg=f"Failed to apply sdn changes {e}. Rolling back all pending changes.")
60 else:
61 self.module.fail_json(msg=f"Failed to apply sdn changes {e}.")
62
63 def rollback_sdn_changes_and_release_lock(self, lock: str, release_lock: bool = True) -> None:
64 """Rollback all changes done under a lock token.
65
66 :param lock: Global SDN lock token
67 :param release_lock: if True release lock after successfully rolling back changes
68 """
69 lock_params = {"lock-token": lock, "release-lock": ansible_to_proxmox_bool(release_lock)}
70 try:
71 self.proxmox_api.cluster().sdn().rollback().post(**lock_params)
72 except Exception as e:
73 self.module.fail_json(
74 msg=f"Rollback attempt failed - {e}. Manually clear lock by deleting /etc/pve/sdn/.lock"
75 )
76
77 def release_lock(self, lock: str, force: bool = False) -> None:
78 """Release Global SDN lock.
79
80 :param lock: Global SDN lock token
81 :param force: if true, allow releasing lock without providing the token
82 """
83 lock_params = {"lock-token": lock, "force": ansible_to_proxmox_bool(force)}
84 try:
85 self.proxmox_api.cluster().sdn().lock().delete(**lock_params)
86 except Exception as e:
87 self.module.fail_json(
88 msg=f"Failed to release lock - {e}. Manually clear lock by deleting /etc/pve/sdn/.lock"
89 )
90
91 def get_zones(self, zone_type: str = None) -> list[dict]:
92 """Get Proxmox SDN zones.
93
94 :param zone_type: Filter zones based on type.
95 :return: list of all zones and their properties.
96 """
97 try:
98 return self.proxmox_api.cluster().sdn().zones().get(type=zone_type)
99 except Exception as e:
100 self.module.fail_json(msg=f"Failed to retrieve zone information from cluster: {e}")
101
102 def get_aliases(self, firewall_obj):
103 """Get aliases for IP/CIDR at given firewall endpoint level.
104
105 :param firewall_obj: Firewall endpoint as a ProxmoxResource e.g. self.proxmox_api.cluster().firewall
106 If it is None it'll return an empty list
107 :return: List of aliases and corresponding IP/CIDR
108 """
109 if firewall_obj is None:
110 return list()
111 try:
112 return firewall_obj().aliases().get()
113 except Exception as e:
114 self.module.fail_json(msg=f"Failed to retrieve aliases - {e}")
115
116 def get_fw_rules(self, rules_obj, pos=None):
117 """Get firewall rules at given rules endpoint level.
118
119 :param rules_obj: Firewall Rules endpoint as a ProxmoxResource e.g. self.proxmox_api.cluster().firewall().rules
120 :param pos: Rule position if it is None it'll return all rules
121 :return: Firewall rules as a list of dict
122 """
123 if pos is not None:
124 pos = str(pos)
125 try:
126 return rules_obj(pos).get()
127 except Exception as e:
128 self.module.fail_json(msg=f"Failed to retrieve firewall rules: {e}")
129
130 def get_groups(self):
131 """Get firewall security groups.
132
133 :return: list of groups
134 """
135 try:
136 return [x["group"] for x in self.proxmox_api.cluster().firewall().groups().get()]
137 except Exception as e:
138 self.module.fail_json(msg=f"Failed to retrieve firewall security groups: {e}")
139
140 def get_ip_sets(self, firewall_obj):
141 """Get ipsets for firewall.
142
143 :return: dict of ip_set name and cidr
144 """
145 if firewall_obj is None:
146 return list()
147 try:
148 ip_sets = firewall_obj.ipset().get()
149 for ip_set in ip_sets:
150 ip_set_obj = firewall_obj.ipset(ip_set["name"])
151 cidrs = ip_set_obj.get()
152 for cidr in cidrs:
153 cidr["nomatch"] = proxmox_to_ansible_bool(cidr.get("nomatch"))
154 ip_set["cidrs"] = cidrs
155 return ip_sets
156 except Exception as e:
157 self.module.fail_json(msg=f"Failed to retrieve firewall ipsets: {e}")