| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# (c) 2017-2018, Antony Alekseyev <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
--- |
| 12 |
module: zabbix_map |
| 13 |
author: |
| 14 |
- "Antony Alekseyev (@Akint)" |
| 15 |
short_description: Create/update/delete Zabbix maps |
| 16 |
description: |
| 17 |
- "This module allows you to create, modify and delete Zabbix map entries, |
| 18 |
using Graphviz binaries and text description written in DOT language. |
| 19 |
Nodes of the graph will become map elements and edges will become links between map elements. |
| 20 |
See U(https://en.wikipedia.org/wiki/DOT_(graph_description_language)) and U(https://www.graphviz.org/) for details. |
| 21 |
Inspired by U(http://blog.zabbix.com/maps-for-the-lazy/)." |
| 22 |
- "The following extra node attributes are supported: |
| 23 |
C(zbx_host) contains name of the host in Zabbix. Use this if desired type of map element is C(host). |
| 24 |
C(zbx_group) contains name of the host group in Zabbix. Use this if desired type of map element is C(host group). |
| 25 |
C(zbx_sysmap) contains name of the map in Zabbix. Use this if desired type of map element is C(map). |
| 26 |
C(zbx_label) contains label of map element. |
| 27 |
C(zbx_image) contains name of the image used to display the element in default state. |
| 28 |
C(zbx_image_disabled) contains name of the image used to display disabled map element. |
| 29 |
C(zbx_image_maintenance) contains name of the image used to display map element in maintenance. |
| 30 |
C(zbx_image_problem) contains name of the image used to display map element with problems. |
| 31 |
C(zbx_url) contains map element URL in C(name:url) format. |
| 32 |
More than one URL could be specified by adding a postfix (e.g., C(zbx_url1), C(zbx_url2))." |
| 33 |
- "The following extra link attributes are supported: |
| 34 |
C(zbx_draw_style) contains link line draw style. Possible values: C(line), C(bold), C(dotted), C(dashed). |
| 35 |
C(zbx_trigger) contains name of the trigger used as a link indicator in C(host_name:trigger_name) format. |
| 36 |
More than one trigger could be specified by adding a postfix (e.g., C(zbx_trigger1), C(zbx_trigger2)). |
| 37 |
C(zbx_trigger_color) contains indicator color specified either as CSS3 name or as a hexadecimal code starting with C(#). |
| 38 |
C(zbx_trigger_draw_style) contains indicator draw style. Possible values are the same as for C(zbx_draw_style)." |
| 39 |
requirements: |
| 40 |
- "python >= 3.9" |
| 41 |
- pydotplus |
| 42 |
- webcolors |
| 43 |
- Pillow |
| 44 |
- Graphviz |
| 45 |
options: |
| 46 |
name: |
| 47 |
description: |
| 48 |
- Name of the map. |
| 49 |
required: true |
| 50 |
aliases: [ "map_name" ] |
| 51 |
type: str |
| 52 |
data: |
| 53 |
description: |
| 54 |
- Graph written in DOT language. |
| 55 |
required: false |
| 56 |
aliases: [ "dot_data" ] |
| 57 |
type: str |
| 58 |
state: |
| 59 |
description: |
| 60 |
- State of the map. |
| 61 |
- On C(present), it will create if map does not exist or update the map if the associated data is different. |
| 62 |
- On C(absent) will remove the map if it exists. |
| 63 |
required: false |
| 64 |
choices: ["present", "absent"] |
| 65 |
default: "present" |
| 66 |
type: str |
| 67 |
width: |
| 68 |
description: |
| 69 |
- Width of the map. |
| 70 |
required: false |
| 71 |
default: 800 |
| 72 |
type: int |
| 73 |
height: |
| 74 |
description: |
| 75 |
- Height of the map. |
| 76 |
required: false |
| 77 |
default: 600 |
| 78 |
type: int |
| 79 |
margin: |
| 80 |
description: |
| 81 |
- Size of white space between map's borders and its elements. |
| 82 |
required: false |
| 83 |
default: 40 |
| 84 |
type: int |
| 85 |
expand_problem: |
| 86 |
description: |
| 87 |
- Whether the problem trigger will be displayed for elements with a single problem. |
| 88 |
required: false |
| 89 |
type: bool |
| 90 |
default: true |
| 91 |
highlight: |
| 92 |
description: |
| 93 |
- Whether icon highlighting is enabled. |
| 94 |
required: false |
| 95 |
type: bool |
| 96 |
default: true |
| 97 |
label_type: |
| 98 |
description: |
| 99 |
- Map element label type. |
| 100 |
required: false |
| 101 |
choices: ["label", "ip", "name", "status", "nothing", "custom"] |
| 102 |
default: "name" |
| 103 |
type: str |
| 104 |
default_image: |
| 105 |
description: |
| 106 |
- Name of the Zabbix image used to display the element if this element doesn't have the C(zbx_image) attribute defined. |
| 107 |
required: false |
| 108 |
aliases: [ "image" ] |
| 109 |
type: str |
| 110 |
|
| 111 |
extends_documentation_fragment: |
| 112 |
- community.zabbix.zabbix |
| 113 |
|
| 114 |
""" |
| 115 |
|
| 116 |
RETURN = r""" # """ |
| 117 |
|
| 118 |
EXAMPLES = r""" |
| 119 |
# If you want to use Username and Password to be authenticated by Zabbix Server |
| 120 |
- name: Set credentials to access Zabbix Server API |
| 121 |
ansible.builtin.set_fact: |
| 122 |
ansible_user: Admin |
| 123 |
ansible_httpapi_pass: zabbix |
| 124 |
|
| 125 |
# If you want to use API token to be authenticated by Zabbix Server |
| 126 |
# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens |
| 127 |
- name: Set API token |
| 128 |
ansible.builtin.set_fact: |
| 129 |
ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 |
| 130 |
|
| 131 |
### |
| 132 |
### Example inventory: |
| 133 |
# [web] |
| 134 |
# web[01:03].example.com ansible_host=127.0.0.1 |
| 135 |
# [db] |
| 136 |
# db.example.com ansible_host=127.0.0.1 |
| 137 |
# [backup] |
| 138 |
# backup.example.com ansible_host=127.0.0.1 |
| 139 |
### |
| 140 |
### Each inventory host is present in Zabbix with a matching name. |
| 141 |
### |
| 142 |
### Contents of "map.j2": |
| 143 |
# digraph G { |
| 144 |
# graph [layout=dot splines=false overlap=scale] |
| 145 |
# INTERNET [zbx_url="Google:https://google.com" zbx_image="Cloud_(96)"] |
| 146 |
# {% for web_host in groups.web %} |
| 147 |
# {% set web_loop = loop %} |
| 148 |
# web{{ '%03d' % web_loop.index }} [zbx_host="{{ web_host }}"] |
| 149 |
# INTERNET -> web{{ '%03d' % web_loop.index }} [zbx_trigger="{{ web_host }}:Zabbix agent on {HOST.NAME} is unreachable for 5 minutes"] |
| 150 |
# {% for db_host in groups.db %} |
| 151 |
# {% set db_loop = loop %} |
| 152 |
# web{{ '%03d' % web_loop.index }} -> db{{ '%03d' % db_loop.index }} |
| 153 |
# {% endfor %} |
| 154 |
# {% endfor %} |
| 155 |
# { rank=same |
| 156 |
# {% for db_host in groups.db %} |
| 157 |
# {% set db_loop = loop %} |
| 158 |
# db{{ '%03d' % db_loop.index }} [zbx_host="{{ db_host }}"] |
| 159 |
# {% for backup_host in groups.backup %} |
| 160 |
# {% set backup_loop = loop %} |
| 161 |
# db{{ '%03d' % db_loop.index }} -> backup{{ '%03d' % backup_loop.index }} [color="blue"] |
| 162 |
# {% endfor %} |
| 163 |
# {% endfor %} |
| 164 |
# {% for backup_host in groups.backup %} |
| 165 |
# {% set backup_loop = loop %} |
| 166 |
# backup{{ '%03d' % backup_loop.index }} [zbx_host="{{ backup_host }}"] |
| 167 |
# {% endfor %} |
| 168 |
# } |
| 169 |
# } |
| 170 |
### |
| 171 |
### Create Zabbix map "Demo Map" made of template "map.j2" |
| 172 |
- name: Create Zabbix map |
| 173 |
# set task level variables as we change ansible_connection plugin here |
| 174 |
vars: |
| 175 |
ansible_network_os: community.zabbix.zabbix |
| 176 |
ansible_connection: httpapi |
| 177 |
ansible_httpapi_port: 443 |
| 178 |
ansible_httpapi_use_ssl: true |
| 179 |
ansible_httpapi_validate_certs: false |
| 180 |
ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu |
| 181 |
ansible_host: zabbix-example-fqdn.org |
| 182 |
community.zabbix.zabbix_map: |
| 183 |
name: Demo map |
| 184 |
state: present |
| 185 |
data: "{{ lookup('template', 'map.j2') }}" |
| 186 |
default_image: Server_(64) |
| 187 |
expand_problem: no |
| 188 |
highlight: no |
| 189 |
label_type: label |
| 190 |
delegate_to: localhost |
| 191 |
run_once: yes |
| 192 |
""" |
| 193 |
|
| 194 |
|
| 195 |
import base64 |
| 196 |
import traceback |
| 197 |
|
| 198 |
from io import BytesIO |
| 199 |
from operator import itemgetter |
| 200 |
|
| 201 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 202 |
|
| 203 |
from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase |
| 204 |
|
| 205 |
import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils |
| 206 |
|
| 207 |
|
| 208 |
try: |
| 209 |
import pydotplus |
| 210 |
HAS_PYDOTPLUS = True |
| 211 |
PYDOT_IMP_ERR = Exception() |
| 212 |
except ImportError: |
| 213 |
PYDOT_IMP_ERR = traceback.format_exc() |
| 214 |
HAS_PYDOTPLUS = False |
| 215 |
|
| 216 |
try: |
| 217 |
import webcolors |
| 218 |
HAS_WEBCOLORS = True |
| 219 |
WEBCOLORS_IMP_ERR = Exception() |
| 220 |
except ImportError: |
| 221 |
WEBCOLORS_IMP_ERR = traceback.format_exc() |
| 222 |
HAS_WEBCOLORS = False |
| 223 |
|
| 224 |
try: |
| 225 |
from PIL import Image |
| 226 |
HAS_PIL = True |
| 227 |
PIL_IMP_ERR = Exception() |
| 228 |
except ImportError: |
| 229 |
PIL_IMP_ERR = traceback.format_exc() |
| 230 |
HAS_PIL = False |
| 231 |
|
| 232 |
|
| 233 |
class Map(ZabbixBase): |
| 234 |
def __init__(self, module, zbx=None, zapi_wrapper=None): |
| 235 |
super(Map, self).__init__(module, zbx, zapi_wrapper) |
| 236 |
self.map_name = module.params["name"] |
| 237 |
self.dot_data = module.params["data"] |
| 238 |
self.width = module.params["width"] |
| 239 |
self.height = module.params["height"] |
| 240 |
self.state = module.params["state"] |
| 241 |
self.default_image = module.params["default_image"] |
| 242 |
self.map_id = self._get_sysmap_id(self.map_name) |
| 243 |
self.margin = module.params["margin"] |
| 244 |
self.expand_problem = module.params["expand_problem"] |
| 245 |
self.highlight = module.params["highlight"] |
| 246 |
self.label_type = module.params["label_type"] |
| 247 |
self.selements_sort_keys = self._get_selements_sort_keys() |
| 248 |
|
| 249 |
def _build_graph(self): |
| 250 |
try: |
| 251 |
graph_without_positions = pydotplus.graph_from_dot_data(self.dot_data) |
| 252 |
dot_data_with_positions = graph_without_positions.create_dot() |
| 253 |
graph_with_positions = pydotplus.graph_from_dot_data(dot_data_with_positions) |
| 254 |
if graph_with_positions: |
| 255 |
return graph_with_positions |
| 256 |
except Exception as e: |
| 257 |
self._module.fail_json(msg="Failed to build graph from DOT data: %s" % e) |
| 258 |
|
| 259 |
def get_map_config(self): |
| 260 |
if not self.dot_data: |
| 261 |
self._module.fail_json(msg="'data' is mandatory with state 'present'") |
| 262 |
graph = self._build_graph() |
| 263 |
nodes = self._get_graph_nodes(graph) |
| 264 |
edges = self._get_graph_edges(graph) |
| 265 |
icon_ids = self._get_icon_ids() |
| 266 |
map_config = { |
| 267 |
"name": self.map_name, |
| 268 |
"label_type": self._get_label_type_id(self.label_type), |
| 269 |
"expandproblem": int(self.expand_problem), |
| 270 |
"highlight": int(self.highlight), |
| 271 |
"width": self.width, |
| 272 |
"height": self.height, |
| 273 |
"selements": self._get_selements(graph, nodes, icon_ids), |
| 274 |
"links": self._get_links(nodes, edges), |
| 275 |
} |
| 276 |
return map_config |
| 277 |
|
| 278 |
def _get_label_type_id(self, label_type): |
| 279 |
label_type_ids = { |
| 280 |
"label": 0, |
| 281 |
"ip": 1, |
| 282 |
"name": 2, |
| 283 |
"status": 3, |
| 284 |
"nothing": 4, |
| 285 |
"custom": 5, |
| 286 |
} |
| 287 |
try: |
| 288 |
label_type_id = label_type_ids[label_type] |
| 289 |
except Exception as e: |
| 290 |
self._module.fail_json(msg="Failed to find id for label type '%s': %s" % (label_type, e)) |
| 291 |
return label_type_id |
| 292 |
|
| 293 |
def _get_images_info(self, data, icon_ids): |
| 294 |
images = [ |
| 295 |
{ |
| 296 |
"dot_tag": "zbx_image", |
| 297 |
"zbx_property": "iconid_off", |
| 298 |
"mandatory": True |
| 299 |
}, |
| 300 |
{ |
| 301 |
"dot_tag": "zbx_image_disabled", |
| 302 |
"zbx_property": "iconid_disabled", |
| 303 |
"mandatory": False |
| 304 |
}, |
| 305 |
{ |
| 306 |
"dot_tag": "zbx_image_maintenance", |
| 307 |
"zbx_property": "iconid_maintenance", |
| 308 |
"mandatory": False |
| 309 |
}, |
| 310 |
{ |
| 311 |
"dot_tag": "zbx_image_problem", |
| 312 |
"zbx_property": "iconid_on", |
| 313 |
"mandatory": False |
| 314 |
} |
| 315 |
] |
| 316 |
images_info = {} |
| 317 |
default_image = self.default_image if self.default_image else sorted(icon_ids.items())[0][0] |
| 318 |
for image in images: |
| 319 |
image_name = data.get(image["dot_tag"], None) |
| 320 |
if not image_name: |
| 321 |
if image["mandatory"]: |
| 322 |
image_name = default_image |
| 323 |
else: |
| 324 |
continue |
| 325 |
image_name = remove_quotes(image_name) |
| 326 |
if image_name in icon_ids: |
| 327 |
images_info[image["zbx_property"]] = icon_ids[image_name] |
| 328 |
if not image["mandatory"]: |
| 329 |
images_info["use_iconmap"] = 0 |
| 330 |
else: |
| 331 |
self._module.fail_json(msg="Failed to find id for image '%s'" % image_name) |
| 332 |
return images_info |
| 333 |
|
| 334 |
def _get_element_type(self, data): |
| 335 |
types = { |
| 336 |
"host": 0, |
| 337 |
"sysmap": 1, |
| 338 |
"trigger": 2, |
| 339 |
"group": 3, |
| 340 |
"image": 4 |
| 341 |
} |
| 342 |
element_type = { |
| 343 |
"elementtype": types["image"], |
| 344 |
} |
| 345 |
for type_name, type_id in sorted(types.items()): |
| 346 |
field_name = "zbx_" + type_name |
| 347 |
if field_name in data: |
| 348 |
method_name = "_get_" + type_name + "_id" |
| 349 |
element_name = remove_quotes(data[field_name]) |
| 350 |
get_element_id = getattr(self, method_name, None) |
| 351 |
if get_element_id: |
| 352 |
elementid = get_element_id(element_name) |
| 353 |
if elementid and int(elementid) > 0: |
| 354 |
element_type.update({ |
| 355 |
"elementtype": type_id, |
| 356 |
"label": element_name |
| 357 |
}) |
| 358 |
element_type.update({ |
| 359 |
"elements": [{ |
| 360 |
type_name + "id": elementid, |
| 361 |
}], |
| 362 |
}) |
| 363 |
break |
| 364 |
else: |
| 365 |
self._module.fail_json(msg="Failed to find id for %s '%s'" % (type_name, element_name)) |
| 366 |
return element_type |
| 367 |
|
| 368 |
# get list of map elements (nodes) |
| 369 |
def _get_selements(self, graph, nodes, icon_ids): |
| 370 |
selements = [] |
| 371 |
icon_sizes = {} |
| 372 |
scales = self._get_scales(graph) |
| 373 |
for selementid, (node, data) in enumerate(nodes.items(), start=1): |
| 374 |
selement = { |
| 375 |
"selementid": selementid |
| 376 |
} |
| 377 |
data["selementid"] = selementid |
| 378 |
|
| 379 |
images_info = self._get_images_info(data, icon_ids) |
| 380 |
selement.update(images_info) |
| 381 |
image_id = images_info["iconid_off"] |
| 382 |
if image_id not in icon_sizes: |
| 383 |
icon_sizes[image_id] = self._get_icon_size(image_id) |
| 384 |
|
| 385 |
pos = self._convert_coordinates(data["pos"], scales, icon_sizes[image_id]) |
| 386 |
selement.update(pos) |
| 387 |
|
| 388 |
selement["label"] = remove_quotes(node) |
| 389 |
element_type = self._get_element_type(data) |
| 390 |
selement.update(element_type) |
| 391 |
|
| 392 |
label = self._get_label(data) |
| 393 |
if label: |
| 394 |
selement["label"] = label |
| 395 |
|
| 396 |
urls = self._get_urls(data) |
| 397 |
if urls: |
| 398 |
selement["urls"] = urls |
| 399 |
|
| 400 |
selements.append(selement) |
| 401 |
return selements |
| 402 |
|
| 403 |
def _get_links(self, nodes, edges): |
| 404 |
links = {} |
| 405 |
for edge in edges: |
| 406 |
link_id = tuple(sorted(edge.obj_dict["points"])) |
| 407 |
node1, node2 = link_id |
| 408 |
data = edge.obj_dict["attributes"] |
| 409 |
|
| 410 |
if "style" in data and data["style"] == "invis": |
| 411 |
continue |
| 412 |
|
| 413 |
if link_id not in links: |
| 414 |
links[link_id] = { |
| 415 |
"selementid1": min(nodes[node1]["selementid"], nodes[node2]["selementid"]), |
| 416 |
"selementid2": max(nodes[node1]["selementid"], nodes[node2]["selementid"]), |
| 417 |
} |
| 418 |
link = links[link_id] |
| 419 |
|
| 420 |
if "color" not in link: |
| 421 |
link["color"] = self._get_color_hex(remove_quotes(data.get("color", "green"))) |
| 422 |
|
| 423 |
if "zbx_draw_style" not in link: |
| 424 |
link["drawtype"] = self._get_link_draw_style_id(remove_quotes(data.get("zbx_draw_style", "line"))) |
| 425 |
|
| 426 |
label = self._get_label(data) |
| 427 |
if label and "label" not in link: |
| 428 |
link["label"] = label |
| 429 |
|
| 430 |
triggers = self._get_triggers(data) |
| 431 |
if triggers: |
| 432 |
if "linktriggers" not in link: |
| 433 |
link["linktriggers"] = [] |
| 434 |
link["linktriggers"] += triggers |
| 435 |
|
| 436 |
return list(links.values()) |
| 437 |
|
| 438 |
def _get_urls(self, data): |
| 439 |
urls = [] |
| 440 |
for url_raw in [remove_quotes(value) for key, value in data.items() if key.startswith("zbx_url")]: |
| 441 |
try: |
| 442 |
name, url = url_raw.split(":", 1) |
| 443 |
except Exception as e: |
| 444 |
self._module.fail_json(msg="Failed to parse zbx_url='%s': %s" % (url_raw, e)) |
| 445 |
urls.append({ |
| 446 |
"name": name, |
| 447 |
"url": url, |
| 448 |
}) |
| 449 |
return urls |
| 450 |
|
| 451 |
def _get_triggers(self, data): |
| 452 |
triggers = [] |
| 453 |
for trigger_definition in [remove_quotes(value) for key, value in data.items() if key.startswith("zbx_trigger")]: |
| 454 |
triggerid = self._get_trigger_id(trigger_definition) |
| 455 |
if triggerid: |
| 456 |
triggers.append({ |
| 457 |
"triggerid": triggerid, |
| 458 |
"color": self._get_color_hex(remove_quotes(data.get("zbx_trigger_color", "red"))), |
| 459 |
"drawtype": self._get_link_draw_style_id(remove_quotes(data.get("zbx_trigger_draw_style", "bold"))), |
| 460 |
}) |
| 461 |
else: |
| 462 |
self._module.fail_json(msg="Failed to find trigger '%s'" % (trigger_definition)) |
| 463 |
return triggers |
| 464 |
|
| 465 |
@staticmethod |
| 466 |
def _get_label(data, default=None): |
| 467 |
if "zbx_label" in data: |
| 468 |
label = remove_quotes(data["zbx_label"]).replace("\\n", "\n") |
| 469 |
elif "label" in data: |
| 470 |
label = remove_quotes(data["label"]) |
| 471 |
else: |
| 472 |
label = default |
| 473 |
return label |
| 474 |
|
| 475 |
def _get_sysmap_id(self, map_name): |
| 476 |
exist_map = self._zapi.map.get({"filter": {"name": map_name}}) |
| 477 |
if exist_map: |
| 478 |
return exist_map[0]["sysmapid"] |
| 479 |
return None |
| 480 |
|
| 481 |
def _get_group_id(self, group_name): |
| 482 |
exist_group = self._zapi.hostgroup.get({"filter": {"name": group_name}}) |
| 483 |
if exist_group: |
| 484 |
return exist_group[0]["groupid"] |
| 485 |
return None |
| 486 |
|
| 487 |
def map_exists(self): |
| 488 |
return bool(self.map_id) |
| 489 |
|
| 490 |
def create_map(self, map_config): |
| 491 |
try: |
| 492 |
if self._module.check_mode: |
| 493 |
self._module.exit_json(changed=True) |
| 494 |
result = self._zapi.map.create(map_config) |
| 495 |
if result: |
| 496 |
return result |
| 497 |
except Exception as e: |
| 498 |
self._module.fail_json(msg="Failed to create map: %s" % e) |
| 499 |
|
| 500 |
def update_map(self, map_config): |
| 501 |
if not self.map_id: |
| 502 |
self._module.fail_json(msg="Failed to update map: map_id is unknown. Try to create_map instead.") |
| 503 |
try: |
| 504 |
if self._module.check_mode: |
| 505 |
self._module.exit_json(changed=True) |
| 506 |
map_config["sysmapid"] = self.map_id |
| 507 |
result = self._zapi.map.update(map_config) |
| 508 |
if result: |
| 509 |
return result |
| 510 |
except Exception as e: |
| 511 |
self._module.fail_json(msg="Failed to update map: %s" % e) |
| 512 |
|
| 513 |
def delete_map(self): |
| 514 |
if not self.map_id: |
| 515 |
self._module.fail_json(msg="Failed to delete map: map_id is unknown.") |
| 516 |
try: |
| 517 |
if self._module.check_mode: |
| 518 |
self._module.exit_json(changed=True) |
| 519 |
self._zapi.map.delete([self.map_id]) |
| 520 |
except Exception as e: |
| 521 |
self._module.fail_json(msg="Failed to delete map, Exception: %s" % e) |
| 522 |
|
| 523 |
def is_exist_map_correct(self, generated_map_config): |
| 524 |
exist_map_configs = self._zapi.map.get({ |
| 525 |
"sysmapids": self.map_id, |
| 526 |
"selectLinks": "extend", |
| 527 |
"selectSelements": "extend" |
| 528 |
}) |
| 529 |
exist_map_config = exist_map_configs[0] |
| 530 |
if not self._is_dicts_equal(generated_map_config, exist_map_config): |
| 531 |
return False |
| 532 |
if not self._is_selements_equal(generated_map_config["selements"], exist_map_config["selements"]): |
| 533 |
return False |
| 534 |
self._update_ids(generated_map_config, exist_map_config) |
| 535 |
if not self._is_links_equal(generated_map_config["links"], exist_map_config["links"]): |
| 536 |
return False |
| 537 |
return True |
| 538 |
|
| 539 |
def _get_selements_sort_keys(self): |
| 540 |
keys_to_sort = ["label"] |
| 541 |
return keys_to_sort |
| 542 |
|
| 543 |
def _is_selements_equal(self, generated_selements, exist_selements): |
| 544 |
if len(generated_selements) != len(exist_selements): |
| 545 |
return False |
| 546 |
generated_selements_sorted = sorted(generated_selements, key=itemgetter(*self.selements_sort_keys)) |
| 547 |
exist_selements_sorted = sorted(exist_selements, key=itemgetter(*self.selements_sort_keys)) |
| 548 |
for (generated_selement, exist_selement) in zip(generated_selements_sorted, exist_selements_sorted): |
| 549 |
if not self._is_elements_equal(generated_selement.get("elements", []), exist_selement.get("elements", [])): |
| 550 |
return False |
| 551 |
if not self._is_dicts_equal(generated_selement, exist_selement, ["selementid"]): |
| 552 |
return False |
| 553 |
if not self._is_urls_equal(generated_selement.get("urls", []), exist_selement.get("urls", [])): |
| 554 |
return False |
| 555 |
return True |
| 556 |
|
| 557 |
def _is_urls_equal(self, generated_urls, exist_urls): |
| 558 |
if len(generated_urls) != len(exist_urls): |
| 559 |
return False |
| 560 |
generated_urls_sorted = sorted(generated_urls, key=itemgetter("name", "url")) |
| 561 |
exist_urls_sorted = sorted(exist_urls, key=itemgetter("name", "url")) |
| 562 |
for (generated_url, exist_url) in zip(generated_urls_sorted, exist_urls_sorted): |
| 563 |
if not self._is_dicts_equal(generated_url, exist_url, ["selementid"]): |
| 564 |
return False |
| 565 |
return True |
| 566 |
|
| 567 |
def _is_elements_equal(self, generated_elements, exist_elements): |
| 568 |
if len(generated_elements) != len(exist_elements): |
| 569 |
return False |
| 570 |
generated_elements_sorted = sorted(generated_elements, key=lambda k: k.values()[0]) |
| 571 |
exist_elements_sorted = sorted(exist_elements, key=lambda k: k.values()[0]) |
| 572 |
for (generated_element, exist_element) in zip(generated_elements_sorted, exist_elements_sorted): |
| 573 |
if not self._is_dicts_equal(generated_element, exist_element, ["selementid"]): |
| 574 |
return False |
| 575 |
return True |
| 576 |
|
| 577 |
# since generated IDs differ from real Zabbix ones, make real IDs match generated ones |
| 578 |
def _update_ids(self, generated_map_config, exist_map_config): |
| 579 |
generated_selements_sorted = sorted(generated_map_config["selements"], key=itemgetter(*self.selements_sort_keys)) |
| 580 |
exist_selements_sorted = sorted(exist_map_config["selements"], key=itemgetter(*self.selements_sort_keys)) |
| 581 |
id_mapping = {} |
| 582 |
for (generated_selement, exist_selement) in zip(generated_selements_sorted, exist_selements_sorted): |
| 583 |
id_mapping[exist_selement["selementid"]] = generated_selement["selementid"] |
| 584 |
for link in exist_map_config["links"]: |
| 585 |
link["selementid1"] = id_mapping[link["selementid1"]] |
| 586 |
link["selementid2"] = id_mapping[link["selementid2"]] |
| 587 |
if link["selementid2"] < link["selementid1"]: |
| 588 |
link["selementid1"], link["selementid2"] = link["selementid2"], link["selementid1"] |
| 589 |
|
| 590 |
def _is_links_equal(self, generated_links, exist_links): |
| 591 |
if len(generated_links) != len(exist_links): |
| 592 |
return False |
| 593 |
generated_links_sorted = sorted(generated_links, key=itemgetter("selementid1", "selementid2", "color", "drawtype")) |
| 594 |
exist_links_sorted = sorted(exist_links, key=itemgetter("selementid1", "selementid2", "color", "drawtype")) |
| 595 |
for (generated_link, exist_link) in zip(generated_links_sorted, exist_links_sorted): |
| 596 |
if not self._is_dicts_equal(generated_link, exist_link, ["selementid1", "selementid2"]): |
| 597 |
return False |
| 598 |
if not self._is_triggers_equal(generated_link.get("linktriggers", []), exist_link.get("linktriggers", [])): |
| 599 |
return False |
| 600 |
return True |
| 601 |
|
| 602 |
def _is_triggers_equal(self, generated_triggers, exist_triggers): |
| 603 |
if len(generated_triggers) != len(exist_triggers): |
| 604 |
return False |
| 605 |
generated_triggers_sorted = sorted(generated_triggers, key=itemgetter("triggerid")) |
| 606 |
exist_triggers_sorted = sorted(exist_triggers, key=itemgetter("triggerid")) |
| 607 |
for (generated_trigger, exist_trigger) in zip(generated_triggers_sorted, exist_triggers_sorted): |
| 608 |
if not self._is_dicts_equal(generated_trigger, exist_trigger): |
| 609 |
return False |
| 610 |
return True |
| 611 |
|
| 612 |
@staticmethod |
| 613 |
def _is_dicts_equal(d1, d2, exclude_keys=None): |
| 614 |
if exclude_keys is None: |
| 615 |
exclude_keys = [] |
| 616 |
for key in d1.keys(): |
| 617 |
if isinstance(d1[key], dict) or isinstance(d1[key], list): |
| 618 |
continue |
| 619 |
if key in exclude_keys: |
| 620 |
continue |
| 621 |
# compare as strings since Zabbix API returns everything as strings |
| 622 |
if key not in d2 or str(d2[key]) != str(d1[key]): |
| 623 |
return False |
| 624 |
return True |
| 625 |
|
| 626 |
def _get_host_id(self, hostname): |
| 627 |
hostid = self._zapi.host.get({"filter": {"host": hostname}}) |
| 628 |
if hostid: |
| 629 |
return str(hostid[0]["hostid"]) |
| 630 |
|
| 631 |
def _get_trigger_id(self, trigger_definition): |
| 632 |
try: |
| 633 |
host, trigger = trigger_definition.split(":", 1) |
| 634 |
except Exception as e: |
| 635 |
self._module.fail_json(msg="Failed to parse zbx_trigger='%s': %s" % (trigger_definition, e)) |
| 636 |
triggerid = self._zapi.trigger.get({ |
| 637 |
"host": host, |
| 638 |
"filter": { |
| 639 |
"description": trigger |
| 640 |
} |
| 641 |
}) |
| 642 |
if triggerid: |
| 643 |
return str(triggerid[0]["triggerid"]) |
| 644 |
|
| 645 |
def _get_icon_ids(self): |
| 646 |
icons_list = self._zapi.image.get({}) |
| 647 |
icon_ids = {} |
| 648 |
for icon in icons_list: |
| 649 |
icon_ids[icon["name"]] = icon["imageid"] |
| 650 |
return icon_ids |
| 651 |
|
| 652 |
def _get_icon_size(self, icon_id): |
| 653 |
icons_list = self._zapi.image.get({ |
| 654 |
"imageids": [ |
| 655 |
icon_id |
| 656 |
], |
| 657 |
"select_image": True |
| 658 |
}) |
| 659 |
if len(icons_list) > 0: |
| 660 |
icon_base64 = icons_list[0]["image"] |
| 661 |
else: |
| 662 |
self._module.fail_json(msg="Failed to find image with id %s" % icon_id) |
| 663 |
image = Image.open(BytesIO(base64.b64decode(icon_base64))) |
| 664 |
icon_width, icon_height = image.size |
| 665 |
return icon_width, icon_height |
| 666 |
|
| 667 |
@staticmethod |
| 668 |
def _get_node_attributes(node): |
| 669 |
attr = {} |
| 670 |
if "attributes" in node.obj_dict: |
| 671 |
attr.update(node.obj_dict["attributes"]) |
| 672 |
pos = node.get_pos() |
| 673 |
if pos is not None: |
| 674 |
pos = remove_quotes(pos) |
| 675 |
xx, yy = pos.split(",") |
| 676 |
attr["pos"] = (float(xx), float(yy)) |
| 677 |
return attr |
| 678 |
|
| 679 |
def _get_graph_nodes(self, parent): |
| 680 |
nodes = {} |
| 681 |
for node in parent.get_nodes(): |
| 682 |
node_name = node.get_name() |
| 683 |
if node_name in ("node", "graph", "edge"): |
| 684 |
continue |
| 685 |
nodes[node_name] = self._get_node_attributes(node) |
| 686 |
for subgraph in parent.get_subgraphs(): |
| 687 |
nodes.update(self._get_graph_nodes(subgraph)) |
| 688 |
return nodes |
| 689 |
|
| 690 |
def _get_graph_edges(self, parent): |
| 691 |
edges = [] |
| 692 |
for edge in parent.get_edges(): |
| 693 |
edges.append(edge) |
| 694 |
for subgraph in parent.get_subgraphs(): |
| 695 |
edges += self._get_graph_edges(subgraph) |
| 696 |
return edges |
| 697 |
|
| 698 |
def _get_scales(self, graph): |
| 699 |
bb = remove_quotes(graph.get_bb()) |
| 700 |
min_x, min_y, max_x, max_y = bb.split(",") |
| 701 |
scale_x = (self.width - self.margin * 2) / (float(max_x) - float(min_x)) if float(max_x) != float(min_x) else 0 |
| 702 |
scale_y = (self.height - self.margin * 2) / (float(max_y) - float(min_y)) if float(max_y) != float(min_y) else 0 |
| 703 |
return { |
| 704 |
"min_x": float(min_x), |
| 705 |
"min_y": float(min_y), |
| 706 |
"max_x": float(max_x), |
| 707 |
"max_y": float(max_y), |
| 708 |
"scale_x": float(scale_x), |
| 709 |
"scale_y": float(scale_y), |
| 710 |
} |
| 711 |
|
| 712 |
# transform Graphviz coordinates to Zabbix's ones |
| 713 |
def _convert_coordinates(self, pos, scales, icon_size): |
| 714 |
return { |
| 715 |
"x": int((pos[0] - scales["min_x"]) * scales["scale_x"] - icon_size[0] / 2 + self.margin), |
| 716 |
"y": int((scales["max_y"] - pos[1] + scales["min_y"]) * scales["scale_y"] - icon_size[1] / 2 + self.margin), |
| 717 |
} |
| 718 |
|
| 719 |
def _get_color_hex(self, color_name): |
| 720 |
if color_name.startswith("#"): |
| 721 |
color_hex = color_name |
| 722 |
else: |
| 723 |
try: |
| 724 |
color_hex = webcolors.name_to_hex(color_name) |
| 725 |
except Exception as e: |
| 726 |
self._module.fail_json(msg="Failed to get RGB hex for color '%s': %s" % (color_name, e)) |
| 727 |
color_hex = color_hex.strip("#").upper() |
| 728 |
return color_hex |
| 729 |
|
| 730 |
def _get_link_draw_style_id(self, draw_style): |
| 731 |
draw_style_ids = { |
| 732 |
"line": 0, |
| 733 |
"bold": 2, |
| 734 |
"dotted": 3, |
| 735 |
"dashed": 4 |
| 736 |
} |
| 737 |
try: |
| 738 |
draw_style_id = draw_style_ids[draw_style] |
| 739 |
except Exception as e: |
| 740 |
self._module.fail_json(msg="Failed to find id for draw type '%s': %s" % (draw_style, e)) |
| 741 |
return draw_style_id |
| 742 |
|
| 743 |
|
| 744 |
# If a string has single or double quotes around it, remove them. |
| 745 |
def remove_quotes(s): |
| 746 |
if (s[0] == s[-1]) and s.startswith(("'", '"')): |
| 747 |
s = s[1:-1] |
| 748 |
return s |
| 749 |
|
| 750 |
|
| 751 |
def main(): |
| 752 |
argument_spec = zabbix_utils.zabbix_common_argument_spec() |
| 753 |
argument_spec.update(dict( |
| 754 |
name=dict(type="str", required=True, aliases=["map_name"]), |
| 755 |
data=dict(type="str", required=False, aliases=["dot_data"]), |
| 756 |
width=dict(type="int", default=800), |
| 757 |
height=dict(type="int", default=600), |
| 758 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 759 |
default_image=dict(type="str", required=False, aliases=["image"]), |
| 760 |
margin=dict(type="int", default=40), |
| 761 |
expand_problem=dict(type="bool", default=True), |
| 762 |
highlight=dict(type="bool", default=True), |
| 763 |
label_type=dict(type="str", default="name", choices=["label", "ip", "name", "status", "nothing", "custom"]), |
| 764 |
)) |
| 765 |
module = AnsibleModule( |
| 766 |
argument_spec=argument_spec, |
| 767 |
supports_check_mode=True |
| 768 |
) |
| 769 |
|
| 770 |
if not HAS_PYDOTPLUS: |
| 771 |
module.fail_json(msg=missing_required_lib("pydotplus", url="https://pypi.org/project/pydotplus/"), exception=PYDOT_IMP_ERR) |
| 772 |
if not HAS_WEBCOLORS: |
| 773 |
module.fail_json(msg=missing_required_lib("webcolors", url="https://pypi.org/project/webcolors/"), exception=WEBCOLORS_IMP_ERR) |
| 774 |
if not HAS_PIL: |
| 775 |
module.fail_json(msg=missing_required_lib("Pillow", url="https://pypi.org/project/Pillow/"), exception=PIL_IMP_ERR) |
| 776 |
|
| 777 |
sysmap = Map(module) |
| 778 |
|
| 779 |
if sysmap.state == "absent": |
| 780 |
if sysmap.map_exists(): |
| 781 |
sysmap.delete_map() |
| 782 |
module.exit_json(changed=True, result="Successfully deleted map: %s" % sysmap.map_name) |
| 783 |
else: |
| 784 |
module.exit_json(changed=False) |
| 785 |
else: |
| 786 |
map_config = sysmap.get_map_config() |
| 787 |
if sysmap.map_exists(): |
| 788 |
if sysmap.is_exist_map_correct(map_config): |
| 789 |
module.exit_json(changed=False) |
| 790 |
else: |
| 791 |
sysmap.update_map(map_config) |
| 792 |
module.exit_json(changed=True, result="Successfully updated map: %s" % sysmap.map_name) |
| 793 |
else: |
| 794 |
sysmap.create_map(map_config) |
| 795 |
module.exit_json(changed=True, result="Successfully created map: %s" % sysmap.map_name) |
| 796 |
|
| 797 |
|
| 798 |
if __name__ == "__main__": |
| 799 |
main() |