main.py 20 KB

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