diff --git a/app/zabbix.py b/app/zabbix.py index 67c8410..30a837e 100644 --- a/app/zabbix.py +++ b/app/zabbix.py @@ -200,35 +200,44 @@ def sync_to_zabbix(players, add_log_fn): log.warning("Template '%s' not found in Zabbix — import zabbix_template.yaml first", ZABBIX_TEMPLATE) existing = {h['host']: h for h in zbx.get_hosts_in_group(groupid)} - created = updated = 0 + created = updated = skipped = 0 for player in players: yid = player['id'] hostname = f"yodeck-{yid}" visible = f"QRS-{player['name'][:4]}MB-{player['name'][4:]}" - if hostname not in existing: - hostid = zbx.create_host(hostname, visible, groupid) - zbx.upsert_host_macro(hostid, '{$YODECK_ID}', str(yid)) - if template_id: - zbx.link_template(hostid, template_id) + try: + if hostname not in existing: + hostid = zbx.create_host(hostname, visible, groupid) + zbx.upsert_host_macro(hostid, '{$YODECK_ID}', str(yid)) + if template_id: + zbx.link_template(hostid, template_id) + else: + zbx.add_player_items(hostid, yid) + created += 1 + log.info("Created Zabbix host: %s (%s)", hostname, visible) else: - zbx.add_player_items(hostid, yid) - created += 1 - log.info("Created Zabbix host: %s (%s)", hostname, visible) - else: - h = existing[hostname] - if h['name'] != visible: - zbx.update_host_name(h['hostid'], visible) - updated += 1 - # Link template and set macro on existing hosts that don't have it yet - if template_id: - linked = {t['templateid'] for t in h.get('parentTemplates', [])} - if template_id not in linked: - zbx.upsert_host_macro(h['hostid'], '{$YODECK_ID}', str(yid)) - zbx.link_template(h['hostid'], template_id) + h = existing[hostname] + changed = False + if h['name'] != visible: + zbx.update_host_name(h['hostid'], visible) + changed = True + if template_id: + linked = {t['templateid'] for t in h.get('parentTemplates', [])} + if template_id not in linked: + zbx.upsert_host_macro(h['hostid'], '{$YODECK_ID}', str(yid)) + zbx.link_template(h['hostid'], template_id) + log.info("Linked template to existing host: %s", hostname) + changed = True + if changed: updated += 1 + except Exception as exc: + log.warning("Skipped host %s: %s", hostname, exc) + skipped += 1 - msg = f"Zabbix sync complete: {created} created, {updated} updated ({len(players)} total)" + msg = (f"Zabbix sync complete: {created} created, {updated} updated" + + (f", {skipped} skipped" if skipped else "") + + f" ({len(players)} total)") add_log_fn('zabbix_sync', msg, {'created': created, 'updated': updated, 'total': len(players)}) log.info(msg)