main.py 20 KB

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