client.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import json
  2. import logging
  3. from urllib2 import urlopen, URLError
  4. class BatcaveClient(object):
  5. def __init__(self, url):
  6. assert url.startswith("http://") or url.startswith("https://"), \
  7. "BATCAVE URL must use http(s) protocol"
  8. assert url.endswith("/"), "BATCAVE URL must end with slash."
  9. self.base_url = url
  10. self.logger = logging.getLogger('BATCAVE')
  11. def __load_response(self, url, error_context):
  12. raw_data = None
  13. try:
  14. raw_data = urlopen(self.base_url + url)
  15. except URLError as err:
  16. self.logger.error("Failed to contact BATCAVE for %s: %s",
  17. error_context, err)
  18. return None
  19. try:
  20. return json.load(raw_data)
  21. except ValueError as err:
  22. self.logger.error("Could not parse response for %s: %s",
  23. error_context, err)
  24. return None
  25. def get_nodes(self):
  26. url = 'nodes.json'
  27. return self.__load_response(url, 'nodes')
  28. def get_node(self, nodeid):
  29. """Query the given node's data from the BATCAVE."""
  30. url = 'node/{0}.json'.format(nodeid)
  31. return self.__load_response(url, 'node \'' + nodeid + '\'')
  32. def find_node_by_name(self, name, fuzzymatch=True, single_match_only=True):
  33. """Tries to find a node by given name."""
  34. url = 'find?name=' + name + '&fuzzy=' + ('1' if fuzzymatch else '0')
  35. matches = self.__load_response(url, 'find_name=' + name)
  36. if single_match_only:
  37. if len(matches) == 1:
  38. return matches[0]
  39. else:
  40. return None
  41. return matches
  42. def find_node_by_mac(self, mac, single_match_only=True):
  43. """Tries to find a node by given MAC address."""
  44. url = 'find?mac=' + mac
  45. matches = self.__load_response(url, 'find_mac=' + mac)
  46. if single_match_only:
  47. if len(matches) == 1:
  48. return matches[0]
  49. else:
  50. return None
  51. return matches
  52. def get_nodefield(self, nodeid, field):
  53. """Query the given field for the given nodeid from the BATCAVE."""
  54. url = self.base_url + 'node/{0}/{1}'.format(nodeid, field)
  55. ctx = "node '{0}'->'{1}'".format(nodeid, field)
  56. return self.__load_response(url, ctx)
  57. def get_providers(self):
  58. url = 'providers?format=json'
  59. return self.__load_response(url, 'providers')
  60. def get_status(self):
  61. url = 'status'
  62. return self.__load_response(url, 'status')