main.py 21 KB

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