main.py 22 KB

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