/little_cloud/little_cloud/storage.py

https://github.com/koder-ua/megarepo
Python | 98 lines | 74 code | 23 blank | 1 comment | 19 complexity | facc6529a09d0d80ec2ae359378a26ed MD5 | raw file
  1. import glob
  2. class NetStorageMixIn(object):
  3. def allMacks(self):
  4. #this should be moved away from
  5. return flatten(hwip.keys() for _, hwip in self.get_all())
  6. def allIPs(self):
  7. return flatten(hwip.values() for _, hwip in self.get_all())
  8. def findFreeMac(self):
  9. used_macs = self.allMacks()
  10. for mac in get_next_mac():
  11. if mac not in used_macs:
  12. return mac
  13. try:
  14. import couchdb
  15. class CouchDBStorage(NetStorageMixIn):
  16. doc_tp = 'vm_name_to_iphw_map'
  17. vm_fun = 'function(doc) {\n'
  18. vm_fun += ' if (doc.tp == "%s"){\n' % (doc_tp,)
  19. vm_fun += ' if ( doc.vm_name == "%s" ) {\n'
  20. vm_fun += ' emit(doc._id, doc);\n'
  21. vm_fun += ' }\n'
  22. vm_fun += ' }\n'
  23. vm_fun += '}\n'
  24. all_fun = 'function(doc) {\n'
  25. all_fun += ' if (doc.tp == "%s"){\n' % (doc_tp,)
  26. all_fun += ' emit(doc._id, doc);\n'
  27. all_fun += ' }\n'
  28. all_fun += '}\n'
  29. def __init__(self, host='localhost', port=5984):
  30. self.conn = couchdb.Server("http://{0}:{1}/".format(host, port))
  31. try:
  32. self.db = self.conn.create('libvirtex')
  33. except couchdb.PreconditionFailed:
  34. self.db = self.conn['libvirtex']
  35. def set_vm(self, vm_name, hwip, uri="qemu:///system"):
  36. try:
  37. doc = self.get_doc(vm_name)
  38. doc['hwip'] = hwip
  39. doc['uri'] = uri
  40. except KeyError:
  41. doc = {'tp' : self.doc_tp,
  42. 'vm_name' : vm_name,
  43. 'hwip' : hwip,
  44. 'uri' : uri}
  45. return self.db.save(doc)
  46. def get_vm_uri(self, vm_name):
  47. doc = self.get_doc(vm_name)
  48. return doc.value.get('uri', 'qemu:///system')
  49. def get_all(self):
  50. for doc in self.db.query(self.all_fun):
  51. yield doc.value['vm_name'], doc.value['hwip']
  52. def get_doc(self, vm_name):
  53. res = list(self.db.query(self.vm_fun % (vm_name,)))
  54. if len(res) == 0:
  55. raise KeyError("No vm with name {0!r} in db".format(vm_name))
  56. if len(res) > 1:
  57. raise RuntimeError("More then one docs for vm %s :(" % \
  58. (vm_name,))
  59. return res[0].value
  60. def get_vm(self, vm_name):
  61. return self.get_doc(vm_name)['hwip']
  62. except ImportError:
  63. CouchDBStorage = None
  64. Storage = CouchDBStorage
  65. if Storage is None:
  66. raise RuntimeError("No valid storage found")
  67. def get_all_vms(template):
  68. s = Storage()
  69. for name, hwip in s.get_all():
  70. if glob.fnmatch.fnmatchcase(name, template):
  71. yield name, hwip
  72. if __name__ == "__main__":
  73. s = Storage()
  74. for name, mapping in sorted(s.get_all()):
  75. print name, ':' , ", ".join("{} => {}".format(k,v) for k,v in mapping.items())