main.py 19 KB

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