consul.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/python
  2. import sys
  3. import json
  4. import urllib2
  5. import socket
  6. # Set your token here
  7. token = ''
  8. if len(sys.argv) == 1:
  9. print("Usage: {} <discovery|status|nodeStatus> [serviceID]".format(sys.argv[0]))
  10. sys.exit(1)
  11. headers = {'X-Consul-Token': token} if token else {}
  12. nodeName = socket.gethostname()
  13. url = 'http://127.0.0.1:8500/v1/health/node/{0}'.format(nodeName)
  14. def getNodeServices():
  15. req = urllib2.Request(url, headers=headers)
  16. r = urllib2.urlopen(req)
  17. if r.getcode() != 200:
  18. print(r.getcode(), r.read())
  19. sys.exit(1)
  20. content = r.read()
  21. services = json.loads(content)
  22. return services
  23. def serviceDiscovery():
  24. discovery_list = {}
  25. discovery_list['data'] = []
  26. services = getNodeServices()
  27. for service in services:
  28. if service['CheckID'] != 'serfHealth':
  29. zbx_item = {"{#SERVICEID}": service['ServiceID']}
  30. discovery_list['data'].append(zbx_item)
  31. print(json.dumps(discovery_list, indent=4, sort_keys=True))
  32. def nodeStatus():
  33. nodes = getNodeServices()
  34. try:
  35. status = 1 if nodes[0]['Status'] == 'passing' else 0
  36. except Exception:
  37. status = 0
  38. print(status)
  39. def getStatus(ServiceID):
  40. services = getNodeServices()
  41. status = 0
  42. for service in services:
  43. if service['ServiceID'] == ServiceID:
  44. if service['Status'] == 'passing':
  45. status = 1
  46. else:
  47. status = 0
  48. print(status)
  49. action = sys.argv[1].lower()
  50. if action == 'discovery':
  51. serviceDiscovery()
  52. elif action == 'status':
  53. serviceID = sys.argv[2]
  54. getStatus(serviceID)
  55. elif action == 'nodestatus':
  56. nodeStatus()