1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
|
# SPDX-FileCopyrightText: 2025 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import Any, Mapping, Optional, Sequence
from gvm.errors import RequiredArgument
from gvm.protocols.core import Request
from gvm.protocols.gmp.requests._entity_id import EntityID
from gvm.utils import to_bool
from gvm.xml import XmlCommand
class Agents:
@staticmethod
def _add_element(element, name: str, value: Any) -> None:
"""
Helper to add a sub-element with a value if the value is not None.
Args:
element: The XML parent element to which the new element is added.
name: Name of the sub-element to create.
value: Value to set as the text of the sub-element. If None, the
element will not be created.
"""
if value is not None:
element.add_element(name, str(value))
@classmethod
def _validate_agent_config(
cls, config: Mapping[str, Any], *, caller: str
) -> None:
"""Ensure all required fields exist, are well-shaped, and non-empty."""
def valid_map(d: Any, key: str, path: str) -> Mapping[str, Any]:
if not isinstance(d, Mapping):
raise RequiredArgument(
function=caller, argument=f"config.{path.rstrip('.')}"
)
v = d.get(key)
if not isinstance(v, Mapping):
raise RequiredArgument(
function=caller, argument=f"config.{path}{key}"
)
return v
def valid_value(d: Mapping[str, Any], key: str, path: str) -> Any:
v = d.get(key)
if v is None or (isinstance(v, str) and v.strip() == ""):
raise RequiredArgument(
function=caller, argument=f"config.{path}{key}"
)
return v
# agent_control.retry
ac = valid_map(config, "agent_control", "")
retry = valid_map(ac, "retry", "agent_control.")
valid_value(retry, "attempts", "agent_control.retry.")
valid_value(retry, "delay_in_seconds", "agent_control.retry.")
valid_value(retry, "max_jitter_in_seconds", "agent_control.retry.")
# agent_script_executor
se = valid_map(config, "agent_script_executor", "")
valid_value(se, "bulk_size", "agent_script_executor.")
valid_value(se, "bulk_throttle_time_in_ms", "agent_script_executor.")
valid_value(se, "indexer_dir_depth", "agent_script_executor.")
sched = se.get("scheduler_cron_time")
if isinstance(sched, Sequence) and not isinstance(sched, (str, bytes)):
items = [str(x) for x in sched]
else:
items = []
if not items or any(not str(x).strip() for x in items):
raise RequiredArgument(
function=caller,
argument="config.agent_script_executor.scheduler_cron_time",
)
# heartbeat
hb = valid_map(config, "heartbeat", "")
valid_value(hb, "interval_in_seconds", "heartbeat.")
valid_value(hb, "miss_until_inactive", "heartbeat.")
@classmethod
def _append_agent_config(cls, parent, config: Mapping[str, Any]) -> None:
"""
Append an agent configuration block to the given XML parent element.
Expected config structure::
{
"agent_control": {
"retry": {
"attempts": 6,
"delay_in_seconds": 60,
"max_jitter_in_seconds": 10
}
},
"agent_script_executor": {
"bulk_size": 2,
"bulk_throttle_time_in_ms": 300,
"indexer_dir_depth": 100,
"scheduler_cron_time": ["0 */12 * * *"]
},
"heartbeat": {
"interval_in_seconds": 300,
"miss_until_inactive": 1
}
}
Args:
parent: The XML parent element to which the `<config>` element
should be appended.
config: Mapping containing the agent configuration fields to
serialize.
"""
xml_config = parent.add_element("config")
# agent_control.retry
ac = config["agent_control"]
retry = ac["retry"]
xml_ac = xml_config.add_element("agent_control")
xml_retry = xml_ac.add_element("retry")
cls._add_element(xml_retry, "attempts", retry.get("attempts"))
cls._add_element(
xml_retry, "delay_in_seconds", retry.get("delay_in_seconds")
)
cls._add_element(
xml_retry,
"max_jitter_in_seconds",
retry.get("max_jitter_in_seconds"),
)
# agent_script_executor
se = config["agent_script_executor"]
xml_se = xml_config.add_element("agent_script_executor")
cls._add_element(xml_se, "bulk_size", se.get("bulk_size"))
cls._add_element(
xml_se,
"bulk_throttle_time_in_ms",
se.get("bulk_throttle_time_in_ms"),
)
cls._add_element(
xml_se, "indexer_dir_depth", se.get("indexer_dir_depth")
)
sched = se.get("scheduler_cron_time")
xml_sched = xml_se.add_element("scheduler_cron_time")
for item in sched:
xml_sched.add_element("item", str(item))
# heartbeat
hb = config["heartbeat"]
xml_hb = xml_config.add_element("heartbeat")
cls._add_element(
xml_hb, "interval_in_seconds", hb.get("interval_in_seconds")
)
cls._add_element(
xml_hb, "miss_until_inactive", hb.get("miss_until_inactive")
)
@classmethod
def get_agents(
cls,
*,
filter_string: Optional[str] = None,
filter_id: Optional[EntityID] = None,
details: Optional[bool] = None,
) -> Request:
"""Request a list of agents.
Args:
filter_string: Filter term to use for the query.
filter_id: UUID of an existing filter to use for the query.
details: Whether to include detailed agent info.
"""
cmd = XmlCommand("get_agents")
cmd.add_filter(filter_string, filter_id)
if details is not None:
cmd.set_attribute("details", to_bool(details))
return cmd
@classmethod
def modify_agents(
cls,
agent_ids: list[EntityID],
*,
authorized: Optional[bool] = None,
config: Optional[Mapping[str, Any]] = None,
comment: Optional[str] = None,
) -> Request:
"""
Modify multiple agents.
Args:
agent_ids: List of agent UUIDs to modify.
authorized: Whether the agent is authorized.
config: Nested config, e.g.:
{
"agent_control": {
"retry": {
"attempts": 6,
"delay_in_seconds": 60,
"max_jitter_in_seconds": 10,
}
},
"agent_script_executor": {
"bulk_size": 2,
"bulk_throttle_time_in_ms": 300,
"indexer_dir_depth": 100,
"scheduler_cron_time": ["0 */12 * * *"], # str or list[str]
},
"heartbeat": {
"interval_in_seconds": 300,
"miss_until_inactive": 1,
},
}
comment: Optional comment for the change.
"""
if not agent_ids:
raise RequiredArgument(
function=cls.modify_agents.__name__, argument="agent_ids"
)
cmd = XmlCommand("modify_agent")
xml_agents = cmd.add_element("agents")
for agent_id in agent_ids:
xml_agents.add_element("agent", attrs={"id": agent_id})
if authorized is not None:
cmd.add_element("authorized", to_bool(authorized))
if config is not None:
cls._validate_agent_config(
config, caller=cls.modify_agents.__name__
)
cls._append_agent_config(cmd, config)
if comment:
cmd.add_element("comment", comment)
return cmd
@classmethod
def delete_agents(cls, agent_ids: list[EntityID]) -> Request:
"""Delete multiple agents
Args:
agent_ids: List of agent UUIDs to delete
"""
if not agent_ids:
raise RequiredArgument(
function=cls.delete_agents.__name__, argument="agent_ids"
)
cmd = XmlCommand("delete_agent")
xml_agents = cmd.add_element("agents")
for agent_id in agent_ids:
xml_agents.add_element("agent", attrs={"id": agent_id})
return cmd
@classmethod
def modify_agent_control_scan_config(
cls,
agent_control_id: EntityID,
config: Mapping[str, Any],
) -> Request:
"""
Modify agent control scan config.
Args:
agent_control_id: The agent control UUID.
config: Nested config, e.g.:
{
"agent_control": {
"retry": {
"attempts": 6,
"delay_in_seconds": 60,
"max_jitter_in_seconds": 10,
}
},
"agent_script_executor": {
"bulk_size": 2,
"bulk_throttle_time_in_ms": 300,
"indexer_dir_depth": 100,
"scheduler_cron_time": ["0 */12 * * *"], # str or list[str]
},
"heartbeat": {
"interval_in_seconds": 300,
"miss_until_inactive": 1,
},
}
"""
if not agent_control_id:
raise RequiredArgument(
function=cls.modify_agent_control_scan_config.__name__,
argument="agent_control_id",
)
if not config:
raise RequiredArgument(
function=cls.modify_agent_control_scan_config.__name__,
argument="config",
)
cls._validate_agent_config(
config, caller=cls.modify_agent_control_scan_config.__name__
)
cmd = XmlCommand(
"modify_agent_control_scan_config",
)
cmd.set_attribute("agent_control_id", str(agent_control_id))
cls._append_agent_config(cmd, config)
return cmd
|