legacy.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import logging
  2. import re
  3. from .container import get_container_name, Container
  4. log = logging.getLogger(__name__)
  5. # TODO: remove this section when migrate_project_to_labels is removed
  6. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  7. def check_for_legacy_containers(
  8. client,
  9. project,
  10. services,
  11. stopped=False,
  12. one_off=False):
  13. """Check if there are containers named using the old naming convention
  14. and warn the user that those containers may need to be migrated to
  15. using labels, so that compose can find them.
  16. """
  17. names = get_legacy_container_names(
  18. client,
  19. project,
  20. services,
  21. stopped=stopped,
  22. one_off=one_off)
  23. for name in names:
  24. log.warn(
  25. "Compose found a found a container named %s without any "
  26. "labels. As of compose 1.3.0 containers are identified with "
  27. "labels instead of naming convention. If you'd like compose "
  28. "to use this container, please run "
  29. "`docker-compose migrate-to-labels`" % (name,))
  30. def add_labels(project, container, name):
  31. project_name, service_name, one_off, number = NAME_RE.match(name).groups()
  32. if project_name != project.name or service_name not in project.service_names:
  33. return
  34. service = project.get_service(service_name)
  35. service.recreate_container(container)
  36. def migrate_project_to_labels(project):
  37. log.info("Running migration to labels for project %s", project.name)
  38. client = project.client
  39. for container in client.containers(all=True):
  40. name = get_container_name(container)
  41. if not is_valid_name(name):
  42. continue
  43. add_labels(project, Container.from_ps(client, container), name)
  44. def get_legacy_container_names(
  45. client,
  46. project,
  47. services,
  48. stopped=False,
  49. one_off=False):
  50. for container in client.containers(all=stopped):
  51. name = get_container_name(container)
  52. for service in services:
  53. if has_container(project, service, name, one_off=one_off):
  54. yield name
  55. def has_container(project, service, name, one_off=False):
  56. if not name or not is_valid_name(name, one_off):
  57. return False
  58. container_project, container_service, _container_number = parse_name(name)
  59. return container_project == project and container_service == service
  60. def is_valid_name(name, one_off=False):
  61. match = NAME_RE.match(name)
  62. if match is None:
  63. return False
  64. if one_off:
  65. return match.group(3) == 'run_'
  66. else:
  67. return match.group(3) is None
  68. def parse_name(name):
  69. match = NAME_RE.match(name)
  70. (project, service_name, _, suffix) = match.groups()
  71. return (project, service_name, int(suffix))