l2cfg.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # -*- coding: utf-8 -*-
  2. """Shared helper for the L2 collectors: read the module config, resolve the
  3. selected templates to template ids, and list the hosts that should be collected.
  4. """
  5. import os
  6. import json
  7. DEFAULT_PATHS = [
  8. os.environ.get('L2_CONFIG') or '',
  9. '/opt/zabbix/zabbix-server/web-modules/WecomCenter/assets/l2topology/config.json',
  10. '/usr/share/zabbix/modules/WecomCenter/assets/l2topology/config.json',
  11. os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.json'),
  12. ]
  13. def config():
  14. for p in DEFAULT_PATHS:
  15. if p and os.path.isfile(p):
  16. try:
  17. with open(p, encoding='utf-8') as f:
  18. return json.load(f)
  19. except Exception:
  20. pass
  21. return {}
  22. def template_ids(call):
  23. """Resolve configured template names -> [templateid]. Empty list => no filter."""
  24. cfg = config()
  25. names = [str(n).strip() for n in (cfg.get('templates') or []) if str(n).strip()]
  26. if not names:
  27. return []
  28. try:
  29. tpls = call('template.get', {'output': ['templateid', 'name']})['result']
  30. except Exception:
  31. return []
  32. want = {n.lower() for n in names}
  33. return [t['templateid'] for t in tpls if t.get('name', '').strip().lower() in want]
  34. def hosts(call, output=None, interfaces='extend'):
  35. """host.get restricted to the configured templates (when resolvable)."""
  36. p = {'output': output or ['hostid', 'name'], 'selectInterfaces': interfaces}
  37. tids = template_ids(call)
  38. if tids:
  39. p['templateids'] = tids
  40. return call('host.get', p)['result']