service_collection.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from .service import Service
  2. def sort_service_dicts(services):
  3. # Sort in dependency order
  4. def cmp(x, y):
  5. x_deps_y = y['name'] in x.get('links', [])
  6. y_deps_x = x['name'] in y.get('links', [])
  7. if x_deps_y and not y_deps_x:
  8. return 1
  9. elif y_deps_x and not x_deps_y:
  10. return -1
  11. return 0
  12. return sorted(services, cmp=cmp)
  13. class ServiceCollection(list):
  14. @classmethod
  15. def from_dicts(cls, client, service_dicts):
  16. """
  17. Construct a ServiceCollection from a list of dicts representing services.
  18. """
  19. collection = ServiceCollection()
  20. for service_dict in sort_service_dicts(service_dicts):
  21. # Reference links by object
  22. links = []
  23. if 'links' in service_dict:
  24. for name in service_dict.get('links', []):
  25. links.append(collection.get(name))
  26. del service_dict['links']
  27. collection.append(Service(client=client, links=links, **service_dict))
  28. return collection
  29. @classmethod
  30. def from_config(cls, client, config):
  31. dicts = []
  32. for name, service in config.items():
  33. service['name'] = name
  34. dicts.append(service)
  35. return cls.from_dicts(client, dicts)
  36. def get(self, name):
  37. for service in self:
  38. if service.name == name:
  39. return service
  40. def start(self):
  41. for container in self:
  42. container.start()
  43. def stop(self):
  44. for container in self:
  45. container.stop()