main.py 22 KB

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