main.py 23 KB

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