main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. from __future__ import print_function
  2. from __future__ import unicode_literals
  3. from inspect import getdoc
  4. from operator import attrgetter
  5. import logging
  6. import re
  7. import signal
  8. import sys
  9. from docker.errors import APIError
  10. import dockerpty
  11. from .. import legacy
  12. from ..const import DEFAULT_TIMEOUT
  13. from ..project import NoSuchService, ConfigurationError
  14. from ..service import BuildError, NeedsBuildError
  15. from ..config import parse_environment
  16. from .command import Command
  17. from .docopt_command import NoSuchCommand
  18. from .errors import UserError
  19. from .formatter import Formatter
  20. from .log_printer import LogPrinter
  21. from .utils import get_version_info, yesno
  22. log = logging.getLogger(__name__)
  23. def main():
  24. setup_logging()
  25. try:
  26. command = TopLevelCommand()
  27. command.sys_dispatch()
  28. except KeyboardInterrupt:
  29. log.error("\nAborting.")
  30. sys.exit(1)
  31. except (UserError, NoSuchService, ConfigurationError, legacy.LegacyError) as e:
  32. log.error(e.msg)
  33. sys.exit(1)
  34. except NoSuchCommand as e:
  35. log.error("No such command: %s", e.command)
  36. log.error("")
  37. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  38. sys.exit(1)
  39. except APIError as e:
  40. log.error(e.explanation)
  41. sys.exit(1)
  42. except BuildError as e:
  43. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  44. sys.exit(1)
  45. except NeedsBuildError as e:
  46. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  47. sys.exit(1)
  48. def setup_logging():
  49. console_handler = logging.StreamHandler(sys.stderr)
  50. console_handler.setFormatter(logging.Formatter())
  51. console_handler.setLevel(logging.INFO)
  52. root_logger = logging.getLogger()
  53. root_logger.addHandler(console_handler)
  54. root_logger.setLevel(logging.DEBUG)
  55. # Disable requests logging
  56. logging.getLogger("requests").propagate = False
  57. # stolen from docopt master
  58. def parse_doc_section(name, source):
  59. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  60. re.IGNORECASE | re.MULTILINE)
  61. return [s.strip() for s in pattern.findall(source)]
  62. class TopLevelCommand(Command):
  63. """Define and run multi-container applications with Docker.
  64. Usage:
  65. docker-compose [options] [COMMAND] [ARGS...]
  66. docker-compose -h|--help
  67. Options:
  68. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  69. -p, --project-name NAME Specify an alternate project name (default: directory name)
  70. --verbose Show more output
  71. -v, --version Print version and exit
  72. Commands:
  73. build Build or rebuild services
  74. help Get help on a command
  75. kill Kill containers
  76. logs View output from containers
  77. port Print the public port for a port binding
  78. ps List containers
  79. pull Pulls service images
  80. restart Restart services
  81. rm Remove stopped containers
  82. run Run a one-off command
  83. scale Set number of containers for a service
  84. start Start services
  85. stop Stop services
  86. up Create and start containers
  87. migrate-to-labels Recreate containers to add labels
  88. """
  89. def docopt_options(self):
  90. options = super(TopLevelCommand, self).docopt_options()
  91. options['version'] = get_version_info()
  92. return options
  93. def build(self, project, options):
  94. """
  95. Build or rebuild services.
  96. Services are built once and then tagged as `project_service`,
  97. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  98. contents of its build directory, you can run `docker-compose build` to rebuild it.
  99. Usage: build [options] [SERVICE...]
  100. Options:
  101. --no-cache Do not use cache when building the image.
  102. """
  103. no_cache = bool(options.get('--no-cache', False))
  104. project.build(service_names=options['SERVICE'], no_cache=no_cache)
  105. def help(self, project, options):
  106. """
  107. Get help on a command.
  108. Usage: help COMMAND
  109. """
  110. handler = self.get_handler(options['COMMAND'])
  111. raise SystemExit(getdoc(handler))
  112. def kill(self, project, options):
  113. """
  114. Force stop service containers.
  115. Usage: kill [options] [SERVICE...]
  116. Options:
  117. -s SIGNAL SIGNAL to send to the container.
  118. Default signal is SIGKILL.
  119. """
  120. signal = options.get('-s', 'SIGKILL')
  121. project.kill(service_names=options['SERVICE'], signal=signal)
  122. def logs(self, project, options):
  123. """
  124. View output from containers.
  125. Usage: logs [options] [SERVICE...]
  126. Options:
  127. --no-color Produce monochrome output.
  128. """
  129. containers = project.containers(service_names=options['SERVICE'], stopped=True)
  130. monochrome = options['--no-color']
  131. print("Attaching to", list_containers(containers))
  132. LogPrinter(containers, attach_params={'logs': True}, monochrome=monochrome).run()
  133. def port(self, project, options):
  134. """
  135. Print the public port for a port binding.
  136. Usage: port [options] SERVICE PRIVATE_PORT
  137. Options:
  138. --protocol=proto tcp or udp [default: tcp]
  139. --index=index index of the container if there are multiple
  140. instances of a service [default: 1]
  141. """
  142. index = int(options.get('--index'))
  143. service = project.get_service(options['SERVICE'])
  144. try:
  145. container = service.get_container(number=index)
  146. except ValueError as e:
  147. raise UserError(str(e))
  148. print(container.get_local_port(
  149. options['PRIVATE_PORT'],
  150. protocol=options.get('--protocol') or 'tcp') or '')
  151. def ps(self, project, options):
  152. """
  153. List containers.
  154. Usage: ps [options] [SERVICE...]
  155. Options:
  156. -q Only display IDs
  157. """
  158. containers = sorted(
  159. project.containers(service_names=options['SERVICE'], stopped=True) +
  160. project.containers(service_names=options['SERVICE'], one_off=True),
  161. key=attrgetter('name'))
  162. if options['-q']:
  163. for container in containers:
  164. print(container.id)
  165. else:
  166. headers = [
  167. 'Name',
  168. 'Command',
  169. 'State',
  170. 'Ports',
  171. ]
  172. rows = []
  173. for container in containers:
  174. command = container.human_readable_command
  175. if len(command) > 30:
  176. command = '%s ...' % command[:26]
  177. rows.append([
  178. container.name,
  179. command,
  180. container.human_readable_state,
  181. container.human_readable_ports,
  182. ])
  183. print(Formatter().table(headers, rows))
  184. def pull(self, project, options):
  185. """
  186. Pulls images for services.
  187. Usage: pull [options] [SERVICE...]
  188. Options:
  189. --allow-insecure-ssl Allow insecure connections to the docker
  190. registry
  191. """
  192. insecure_registry = options['--allow-insecure-ssl']
  193. project.pull(
  194. service_names=options['SERVICE'],
  195. insecure_registry=insecure_registry
  196. )
  197. def rm(self, project, options):
  198. """
  199. Remove stopped service containers.
  200. Usage: rm [options] [SERVICE...]
  201. Options:
  202. -f, --force Don't ask to confirm removal
  203. -v Remove volumes associated with containers
  204. """
  205. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  206. stopped_containers = [c for c in all_containers if not c.is_running]
  207. if len(stopped_containers) > 0:
  208. print("Going to remove", list_containers(stopped_containers))
  209. if options.get('--force') \
  210. or yesno("Are you sure? [yN] ", default=False):
  211. project.remove_stopped(
  212. service_names=options['SERVICE'],
  213. v=options.get('-v', False)
  214. )
  215. else:
  216. print("No stopped containers")
  217. def run(self, project, options):
  218. """
  219. Run a one-off command on a service.
  220. For example:
  221. $ docker-compose run web python manage.py shell
  222. By default, linked services will be started, unless they are already
  223. running. If you do not want to start linked services, use
  224. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  225. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  226. Options:
  227. --allow-insecure-ssl Allow insecure connections to the docker
  228. registry
  229. -d Detached mode: Run container in the background, print
  230. new container name.
  231. --entrypoint CMD Override the entrypoint of the image.
  232. -e KEY=VAL Set an environment variable (can be used multiple times)
  233. -u, --user="" Run as specified username or uid
  234. --no-deps Don't start linked services.
  235. --rm Remove container after run. Ignored in detached mode.
  236. --service-ports Run command with the service's ports enabled and mapped
  237. to the host.
  238. -T Disable pseudo-tty allocation. By default `docker-compose run`
  239. allocates a TTY.
  240. """
  241. service = project.get_service(options['SERVICE'])
  242. insecure_registry = options['--allow-insecure-ssl']
  243. if not options['--no-deps']:
  244. deps = service.get_linked_names()
  245. if len(deps) > 0:
  246. project.up(
  247. service_names=deps,
  248. start_deps=True,
  249. allow_recreate=False,
  250. insecure_registry=insecure_registry,
  251. )
  252. tty = True
  253. if options['-d'] or options['-T'] or not sys.stdin.isatty():
  254. tty = False
  255. if options['COMMAND']:
  256. command = [options['COMMAND']] + options['ARGS']
  257. else:
  258. command = service.options.get('command')
  259. container_options = {
  260. 'command': command,
  261. 'tty': tty,
  262. 'stdin_open': not options['-d'],
  263. 'detach': options['-d'],
  264. }
  265. if options['-e']:
  266. container_options['environment'] = parse_environment(options['-e'])
  267. if options['--entrypoint']:
  268. container_options['entrypoint'] = options.get('--entrypoint')
  269. if options['--rm']:
  270. container_options['restart'] = None
  271. if options['--user']:
  272. container_options['user'] = options.get('--user')
  273. if not options['--service-ports']:
  274. container_options['ports'] = []
  275. try:
  276. container = service.create_container(
  277. quiet=True,
  278. one_off=True,
  279. insecure_registry=insecure_registry,
  280. **container_options
  281. )
  282. except APIError as e:
  283. legacy.check_for_legacy_containers(
  284. project.client,
  285. project.name,
  286. [service.name],
  287. allow_one_off=False,
  288. )
  289. raise e
  290. if options['-d']:
  291. service.start_container(container)
  292. print(container.name)
  293. else:
  294. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  295. exit_code = container.wait()
  296. if options['--rm']:
  297. project.client.remove_container(container.id)
  298. sys.exit(exit_code)
  299. def scale(self, project, options):
  300. """
  301. Set number of containers to run for a service.
  302. Numbers are specified in the form `service=num` as arguments.
  303. For example:
  304. $ docker-compose scale web=2 worker=3
  305. Usage: scale [SERVICE=NUM...]
  306. """
  307. for s in options['SERVICE=NUM']:
  308. if '=' not in s:
  309. raise UserError('Arguments to scale should be in the form service=num')
  310. service_name, num = s.split('=', 1)
  311. try:
  312. num = int(num)
  313. except ValueError:
  314. raise UserError('Number of containers for service "%s" is not a '
  315. 'number' % service_name)
  316. project.get_service(service_name).scale(num)
  317. def start(self, project, options):
  318. """
  319. Start existing containers.
  320. Usage: start [SERVICE...]
  321. """
  322. project.start(service_names=options['SERVICE'])
  323. def stop(self, project, options):
  324. """
  325. Stop running containers without removing them.
  326. They can be started again with `docker-compose start`.
  327. Usage: stop [options] [SERVICE...]
  328. Options:
  329. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  330. (default: 10)
  331. """
  332. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  333. project.stop(service_names=options['SERVICE'], timeout=timeout)
  334. def restart(self, project, options):
  335. """
  336. Restart running containers.
  337. Usage: restart [options] [SERVICE...]
  338. Options:
  339. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  340. (default: 10)
  341. """
  342. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  343. project.restart(service_names=options['SERVICE'], timeout=timeout)
  344. def up(self, project, options):
  345. """
  346. Build, (re)create, start and attach to containers for a service.
  347. By default, `docker-compose up` will aggregate the output of each container, and
  348. when it exits, all containers will be stopped. If you run `docker-compose up -d`,
  349. it'll start the containers in the background and leave them running.
  350. If there are existing containers for a service, `docker-compose up` will stop
  351. and recreate them (preserving mounted volumes with volumes-from),
  352. so that changes in `docker-compose.yml` are picked up. If you do not want existing
  353. containers to be recreated, `docker-compose up --no-recreate` will re-use existing
  354. containers.
  355. Usage: up [options] [SERVICE...]
  356. Options:
  357. --allow-insecure-ssl Allow insecure connections to the docker
  358. registry
  359. -d Detached mode: Run containers in the background,
  360. print new container names.
  361. --no-color Produce monochrome output.
  362. --no-deps Don't start linked services.
  363. --x-smart-recreate Only recreate containers whose configuration or
  364. image needs to be updated. (EXPERIMENTAL)
  365. --no-recreate If containers already exist, don't recreate them.
  366. --no-build Don't build an image, even if it's missing
  367. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  368. when attached or when containers are already
  369. running. (default: 10)
  370. """
  371. insecure_registry = options['--allow-insecure-ssl']
  372. detached = options['-d']
  373. monochrome = options['--no-color']
  374. start_deps = not options['--no-deps']
  375. allow_recreate = not options['--no-recreate']
  376. smart_recreate = options['--x-smart-recreate']
  377. service_names = options['SERVICE']
  378. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  379. project.up(
  380. service_names=service_names,
  381. start_deps=start_deps,
  382. allow_recreate=allow_recreate,
  383. smart_recreate=smart_recreate,
  384. insecure_registry=insecure_registry,
  385. do_build=not options['--no-build'],
  386. timeout=timeout
  387. )
  388. to_attach = [c for s in project.get_services(service_names) for c in s.containers()]
  389. if not detached:
  390. print("Attaching to", list_containers(to_attach))
  391. log_printer = LogPrinter(to_attach, attach_params={"logs": True}, monochrome=monochrome)
  392. try:
  393. log_printer.run()
  394. finally:
  395. def handler(signal, frame):
  396. project.kill(service_names=service_names)
  397. sys.exit(0)
  398. signal.signal(signal.SIGINT, handler)
  399. print("Gracefully stopping... (press Ctrl+C again to force)")
  400. project.stop(service_names=service_names, timeout=timeout)
  401. def migrate_to_labels(self, project, _options):
  402. """
  403. Recreate containers to add labels
  404. If you're coming from Compose 1.2 or earlier, you'll need to remove or
  405. migrate your existing containers after upgrading Compose. This is
  406. because, as of version 1.3, Compose uses Docker labels to keep track
  407. of containers, and so they need to be recreated with labels added.
  408. If Compose detects containers that were created without labels, it
  409. will refuse to run so that you don't end up with two sets of them. If
  410. you want to keep using your existing containers (for example, because
  411. they have data volumes you want to preserve) you can migrate them with
  412. the following command:
  413. docker-compose migrate-to-labels
  414. Alternatively, if you're not worried about keeping them, you can
  415. remove them - Compose will just create new ones.
  416. docker rm -f myapp_web_1 myapp_db_1 ...
  417. Usage: migrate-to-labels
  418. """
  419. legacy.migrate_project_to_labels(project)
  420. def list_containers(containers):
  421. return ", ".join(c.name for c in containers)