project.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 Project(object):
  14. """
  15. A collection of services.
  16. """
  17. def __init__(self, name, services, client):
  18. self.name = name
  19. self.services = services
  20. self.client = client
  21. @classmethod
  22. def from_dicts(cls, name, service_dicts, client):
  23. """
  24. Construct a ServiceCollection from a list of dicts representing services.
  25. """
  26. project = cls(name, [], client)
  27. for service_dict in sort_service_dicts(service_dicts):
  28. # Reference links by object
  29. links = []
  30. if 'links' in service_dict:
  31. for name in service_dict.get('links', []):
  32. links.append(project.get_service(name))
  33. del service_dict['links']
  34. project.services.append(Service(client=client, project=name, links=links, **service_dict))
  35. return project
  36. @classmethod
  37. def from_config(cls, name, config, client):
  38. dicts = []
  39. for name, service in config.items():
  40. service['name'] = name
  41. dicts.append(service)
  42. return cls.from_dicts(name, dicts, client)
  43. def get_service(self, name):
  44. for service in self.services:
  45. if service.name == name:
  46. return service
  47. def start(self):
  48. for service in self.services:
  49. service.start()
  50. def stop(self):
  51. for service in self.services:
  52. service.stop()
  53. def containers(self, *args, **kwargs):
  54. l = []
  55. for service in self.services:
  56. for container in service.containers(*args, **kwargs):
  57. l.append(container)
  58. return l