main.py 19 KB

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