main.py 21 KB

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