You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
3.2 KiB

2 years ago
  1. import click
  2. import requests
  3. import json
  4. from xml.etree import ElementTree
  5. def search_services(base_url, username, password, service):
  6. ifservices = requests.get(base_url + '/api/v2/ifservices',
  7. params={'limit': 0,
  8. '_s': 'serviceType.name==' + service},
  9. headers={'Accept': 'application/xml'},
  10. auth=(username, password))
  11. ifservices.raise_for_status()
  12. ifservices = ElementTree.fromstring(ifservices.content)
  13. for service in ifservices.iter('service'):
  14. ipiface_id = service.find('ipInterfaceId').text
  15. node = requests.get(base_url + '/api/v2/nodes',
  16. params={'limit': 0,
  17. '_s': 'ipInterface.id==' + ipiface_id},
  18. headers={'Accept': 'application/xml'},
  19. auth=(username, password))
  20. node.raise_for_status()
  21. node = ElementTree.fromstring(node.content).find('node')
  22. node_id = node.get('id')
  23. node_label = node.get('label')
  24. ipiface = requests.get(base_url + '/api/v2/nodes/' + node_id + '/ipinterfaces',
  25. params={'limit': 0,
  26. '_s': 'id==' + ipiface_id},
  27. headers={'Accept': 'application/xml'},
  28. auth=(username, password))
  29. ipiface.raise_for_status()
  30. ipiface = ElementTree.fromstring(ipiface.content).find('ipInterface')
  31. ipiface_address = ipiface.find('ipAddress').text
  32. yield node_label, node_id, ipiface_address
  33. @click.command()
  34. @click.option('--base-url', default='http://localhost:8980/opennms')
  35. @click.option('--username', default='admin')
  36. @click.option('--password', default='admin')
  37. @click.option('--service', default='HTTP')
  38. @click.option('--bs-id', default=0)
  39. def main(base_url, username, password, service, bs_id):
  40. # Strip trailing slash from base URL
  41. if base_url.endswith('/'):
  42. base_url = base_url[:-1]
  43. rkeys = ((label, 'uei.opennms.org/nodes/nodeLostService::%s:%s:%s' % (node, addr, service))
  44. for (label, node, addr)
  45. in search_services(base_url, username, password, service))
  46. bs = {'name': service,
  47. 'reduce-function': {'type': 'HighestSeverity'},
  48. 'reduction-key-edges': [{
  49. 'weight': 1,
  50. 'map-function': {'type': 'Identity'},
  51. 'reduction-key': rkey,
  52. } for (label, rkey) in rkeys]}
  53. bs = json.dumps(bs)
  54. r = requests.put(base_url + '/api/v2/business-services/' + str(bs_id),
  55. headers={'Accept': 'application/json',
  56. 'Content-Type': 'application/json'},
  57. auth=(username, password),
  58. data=bs)
  59. r.raise_for_status()
  60. r = requests.post(base_url + '/api/v2/business-services/daemon/reload',
  61. headers={'Accept': 'application/json',
  62. 'Content-Type': 'application/json'},
  63. auth=(username, password))
  64. r.raise_for_status()
  65. if __name__ == '__main__':
  66. main()