main.py 18 KB

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