main.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import contextlib
  5. import functools
  6. import json
  7. import logging
  8. import pipes
  9. import re
  10. import subprocess
  11. import sys
  12. from distutils.spawn import find_executable
  13. from inspect import getdoc
  14. from operator import attrgetter
  15. from . import errors
  16. from . import signals
  17. from .. import __version__
  18. from ..bundle import get_image_digests
  19. from ..bundle import MissingDigests
  20. from ..bundle import serialize_bundle
  21. from ..config import ConfigurationError
  22. from ..config import parse_environment
  23. from ..config import resolve_build_args
  24. from ..config.environment import Environment
  25. from ..config.serialize import serialize_config
  26. from ..config.types import VolumeSpec
  27. from ..const import IS_WINDOWS_PLATFORM
  28. from ..errors import StreamParseError
  29. from ..progress_stream import StreamOutputError
  30. from ..project import NoSuchService
  31. from ..project import OneOffFilter
  32. from ..project import ProjectError
  33. from ..service import BuildAction
  34. from ..service import BuildError
  35. from ..service import ConvergenceStrategy
  36. from ..service import ImageType
  37. from ..service import NeedsBuildError
  38. from ..service import OperationFailedError
  39. from .command import get_config_from_options
  40. from .command import project_from_options
  41. from .docopt_command import DocoptDispatcher
  42. from .docopt_command import get_handler
  43. from .docopt_command import NoSuchCommand
  44. from .errors import UserError
  45. from .formatter import ConsoleWarningFormatter
  46. from .formatter import Formatter
  47. from .log_printer import build_log_presenters
  48. from .log_printer import LogPrinter
  49. from .utils import get_version_info
  50. from .utils import human_readable_file_size
  51. from .utils import yesno
  52. if not IS_WINDOWS_PLATFORM:
  53. from dockerpty.pty import PseudoTerminal, RunOperation, ExecOperation
  54. log = logging.getLogger(__name__)
  55. console_handler = logging.StreamHandler(sys.stderr)
  56. def main():
  57. try:
  58. command = dispatch()
  59. command()
  60. except (KeyboardInterrupt, signals.ShutdownException):
  61. log.error("Aborting.")
  62. sys.exit(1)
  63. except (UserError, NoSuchService, ConfigurationError,
  64. ProjectError, OperationFailedError) as e:
  65. log.error(e.msg)
  66. sys.exit(1)
  67. except BuildError as e:
  68. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  69. sys.exit(1)
  70. except StreamOutputError as e:
  71. log.error(e)
  72. sys.exit(1)
  73. except NeedsBuildError as e:
  74. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  75. sys.exit(1)
  76. except NoSuchCommand as e:
  77. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  78. log.error("No such command: %s\n\n%s", e.command, commands)
  79. sys.exit(1)
  80. except (errors.ConnectionError, StreamParseError):
  81. sys.exit(1)
  82. def dispatch():
  83. setup_logging()
  84. dispatcher = DocoptDispatcher(
  85. TopLevelCommand,
  86. {'options_first': True, 'version': get_version_info('compose')})
  87. options, handler, command_options = dispatcher.parse(sys.argv[1:])
  88. setup_console_handler(console_handler, options.get('--verbose'))
  89. return functools.partial(perform_command, options, handler, command_options)
  90. def perform_command(options, handler, command_options):
  91. if options['COMMAND'] in ('help', 'version'):
  92. # Skip looking up the compose file.
  93. handler(command_options)
  94. return
  95. if options['COMMAND'] in ('config', 'bundle'):
  96. command = TopLevelCommand(None)
  97. handler(command, options, command_options)
  98. return
  99. project = project_from_options('.', options)
  100. command = TopLevelCommand(project)
  101. with errors.handle_connection_errors(project.client):
  102. handler(command, command_options)
  103. def setup_logging():
  104. root_logger = logging.getLogger()
  105. root_logger.addHandler(console_handler)
  106. root_logger.setLevel(logging.DEBUG)
  107. # Disable requests logging
  108. logging.getLogger("requests").propagate = False
  109. def setup_console_handler(handler, verbose):
  110. if handler.stream.isatty():
  111. format_class = ConsoleWarningFormatter
  112. else:
  113. format_class = logging.Formatter
  114. if verbose:
  115. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  116. handler.setLevel(logging.DEBUG)
  117. else:
  118. handler.setFormatter(format_class())
  119. handler.setLevel(logging.INFO)
  120. # stolen from docopt master
  121. def parse_doc_section(name, source):
  122. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  123. re.IGNORECASE | re.MULTILINE)
  124. return [s.strip() for s in pattern.findall(source)]
  125. class TopLevelCommand(object):
  126. """Define and run multi-container applications with Docker.
  127. Usage:
  128. docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  129. docker-compose -h|--help
  130. Options:
  131. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  132. -p, --project-name NAME Specify an alternate project name (default: directory name)
  133. --verbose Show more output
  134. -v, --version Print version and exit
  135. -H, --host HOST Daemon socket to connect to
  136. --tls Use TLS; implied by --tlsverify
  137. --tlscacert CA_PATH Trust certs signed only by this CA
  138. --tlscert CLIENT_CERT_PATH Path to TLS certificate file
  139. --tlskey TLS_KEY_PATH Path to TLS key file
  140. --tlsverify Use TLS and verify the remote
  141. --skip-hostname-check Don't check the daemon's hostname against the name specified
  142. in the client certificate (for example if your docker host
  143. is an IP address)
  144. Commands:
  145. build Build or rebuild services
  146. bundle Generate a Docker bundle from the Compose file
  147. config Validate and view the compose file
  148. create Create services
  149. down Stop and remove containers, networks, images, and volumes
  150. events Receive real time events from containers
  151. exec Execute a command in a running container
  152. help Get help on a command
  153. images List images
  154. kill Kill containers
  155. logs View output from containers
  156. pause Pause services
  157. port Print the public port for a port binding
  158. ps List containers
  159. pull Pull service images
  160. push Push service images
  161. restart Restart services
  162. rm Remove stopped containers
  163. run Run a one-off command
  164. scale Set number of containers for a service
  165. start Start services
  166. stop Stop services
  167. top Display the running processes
  168. unpause Unpause services
  169. up Create and start containers
  170. version Show the Docker-Compose version information
  171. """
  172. def __init__(self, project, project_dir='.'):
  173. self.project = project
  174. self.project_dir = '.'
  175. def build(self, options):
  176. """
  177. Build or rebuild services.
  178. Services are built once and then tagged as `project_service`,
  179. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  180. contents of its build directory, you can run `docker-compose build` to rebuild it.
  181. Usage: build [options] [--build-arg key=val...] [SERVICE...]
  182. Options:
  183. --force-rm Always remove intermediate containers.
  184. --no-cache Do not use cache when building the image.
  185. --pull Always attempt to pull a newer version of the image.
  186. --build-arg key=val Set build-time variables for one service.
  187. """
  188. service_names = options['SERVICE']
  189. build_args = options.get('--build-arg', None)
  190. if build_args:
  191. environment = Environment.from_env_file(self.project_dir)
  192. build_args = resolve_build_args(build_args, environment)
  193. if not service_names and build_args:
  194. raise UserError("Need service name for --build-arg option")
  195. self.project.build(
  196. service_names=service_names,
  197. no_cache=bool(options.get('--no-cache', False)),
  198. pull=bool(options.get('--pull', False)),
  199. force_rm=bool(options.get('--force-rm', False)),
  200. build_args=build_args)
  201. def bundle(self, config_options, options):
  202. """
  203. Generate a Distributed Application Bundle (DAB) from the Compose file.
  204. Images must have digests stored, which requires interaction with a
  205. Docker registry. If digests aren't stored for all images, you can fetch
  206. them with `docker-compose pull` or `docker-compose push`. To push images
  207. automatically when bundling, pass `--push-images`. Only services with
  208. a `build` option specified will have their images pushed.
  209. Usage: bundle [options]
  210. Options:
  211. --push-images Automatically push images for any services
  212. which have a `build` option specified.
  213. -o, --output PATH Path to write the bundle file to.
  214. Defaults to "<project name>.dab".
  215. """
  216. self.project = project_from_options('.', config_options)
  217. compose_config = get_config_from_options(self.project_dir, config_options)
  218. output = options["--output"]
  219. if not output:
  220. output = "{}.dab".format(self.project.name)
  221. with errors.handle_connection_errors(self.project.client):
  222. try:
  223. image_digests = get_image_digests(
  224. self.project,
  225. allow_push=options['--push-images'],
  226. )
  227. except MissingDigests as e:
  228. def list_images(images):
  229. return "\n".join(" {}".format(name) for name in sorted(images))
  230. paras = ["Some images are missing digests."]
  231. if e.needs_push:
  232. command_hint = (
  233. "Use `docker-compose push {}` to push them. "
  234. "You can do this automatically with `docker-compose bundle --push-images`."
  235. .format(" ".join(sorted(e.needs_push)))
  236. )
  237. paras += [
  238. "The following images can be pushed:",
  239. list_images(e.needs_push),
  240. command_hint,
  241. ]
  242. if e.needs_pull:
  243. command_hint = (
  244. "Use `docker-compose pull {}` to pull them. "
  245. .format(" ".join(sorted(e.needs_pull)))
  246. )
  247. paras += [
  248. "The following images need to be pulled:",
  249. list_images(e.needs_pull),
  250. command_hint,
  251. ]
  252. raise UserError("\n\n".join(paras))
  253. with open(output, 'w') as f:
  254. f.write(serialize_bundle(compose_config, image_digests))
  255. log.info("Wrote bundle to {}".format(output))
  256. def config(self, config_options, options):
  257. """
  258. Validate and view the compose file.
  259. Usage: config [options]
  260. Options:
  261. -q, --quiet Only validate the configuration, don't print
  262. anything.
  263. --services Print the service names, one per line.
  264. --volumes Print the volume names, one per line.
  265. """
  266. compose_config = get_config_from_options(self.project_dir, config_options)
  267. if options['--quiet']:
  268. return
  269. if options['--services']:
  270. print('\n'.join(service['name'] for service in compose_config.services))
  271. return
  272. if options['--volumes']:
  273. print('\n'.join(volume for volume in compose_config.volumes))
  274. return
  275. print(serialize_config(compose_config))
  276. def create(self, options):
  277. """
  278. Creates containers for a service.
  279. Usage: create [options] [SERVICE...]
  280. Options:
  281. --force-recreate Recreate containers even if their configuration and
  282. image haven't changed. Incompatible with --no-recreate.
  283. --no-recreate If containers already exist, don't recreate them.
  284. Incompatible with --force-recreate.
  285. --no-build Don't build an image, even if it's missing.
  286. --build Build images before creating containers.
  287. """
  288. service_names = options['SERVICE']
  289. self.project.create(
  290. service_names=service_names,
  291. strategy=convergence_strategy_from_opts(options),
  292. do_build=build_action_from_opts(options),
  293. )
  294. def down(self, options):
  295. """
  296. Stops containers and removes containers, networks, volumes, and images
  297. created by `up`.
  298. By default, the only things removed are:
  299. - Containers for services defined in the Compose file
  300. - Networks defined in the `networks` section of the Compose file
  301. - The default network, if one is used
  302. Networks and volumes defined as `external` are never removed.
  303. Usage: down [options]
  304. Options:
  305. --rmi type Remove images. Type must be one of:
  306. 'all': Remove all images used by any service.
  307. 'local': Remove only images that don't have a custom tag
  308. set by the `image` field.
  309. -v, --volumes Remove named volumes declared in the `volumes` section
  310. of the Compose file and anonymous volumes
  311. attached to containers.
  312. --remove-orphans Remove containers for services not defined in the
  313. Compose file
  314. """
  315. image_type = image_type_from_opt('--rmi', options['--rmi'])
  316. self.project.down(image_type, options['--volumes'], options['--remove-orphans'])
  317. def events(self, options):
  318. """
  319. Receive real time events from containers.
  320. Usage: events [options] [SERVICE...]
  321. Options:
  322. --json Output events as a stream of json objects
  323. """
  324. def format_event(event):
  325. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  326. return ("{time} {type} {action} {id} ({attrs})").format(
  327. attrs=", ".join(sorted(attributes)),
  328. **event)
  329. def json_format_event(event):
  330. event['time'] = event['time'].isoformat()
  331. event.pop('container')
  332. return json.dumps(event)
  333. for event in self.project.events():
  334. formatter = json_format_event if options['--json'] else format_event
  335. print(formatter(event))
  336. sys.stdout.flush()
  337. def exec_command(self, options):
  338. """
  339. Execute a command in a running container
  340. Usage: exec [options] SERVICE COMMAND [ARGS...]
  341. Options:
  342. -d Detached mode: Run command in the background.
  343. --privileged Give extended privileges to the process.
  344. --user USER Run the command as this user.
  345. -T Disable pseudo-tty allocation. By default `docker-compose exec`
  346. allocates a TTY.
  347. --index=index index of the container if there are multiple
  348. instances of a service [default: 1]
  349. """
  350. index = int(options.get('--index'))
  351. service = self.project.get_service(options['SERVICE'])
  352. detach = options['-d']
  353. try:
  354. container = service.get_container(number=index)
  355. except ValueError as e:
  356. raise UserError(str(e))
  357. command = [options['COMMAND']] + options['ARGS']
  358. tty = not options["-T"]
  359. if IS_WINDOWS_PLATFORM and not detach:
  360. args = ["exec"]
  361. if options["-d"]:
  362. args += ["--detach"]
  363. else:
  364. args += ["--interactive"]
  365. if not options["-T"]:
  366. args += ["--tty"]
  367. if options["--privileged"]:
  368. args += ["--privileged"]
  369. if options["--user"]:
  370. args += ["--user", options["--user"]]
  371. args += [container.id]
  372. args += command
  373. sys.exit(call_docker(args))
  374. create_exec_options = {
  375. "privileged": options["--privileged"],
  376. "user": options["--user"],
  377. "tty": tty,
  378. "stdin": tty,
  379. }
  380. exec_id = container.create_exec(command, **create_exec_options)
  381. if detach:
  382. container.start_exec(exec_id, tty=tty)
  383. return
  384. signals.set_signal_handler_to_shutdown()
  385. try:
  386. operation = ExecOperation(
  387. self.project.client,
  388. exec_id,
  389. interactive=tty,
  390. )
  391. pty = PseudoTerminal(self.project.client, operation)
  392. pty.start()
  393. except signals.ShutdownException:
  394. log.info("received shutdown exception: closing")
  395. exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
  396. sys.exit(exit_code)
  397. @classmethod
  398. def help(cls, options):
  399. """
  400. Get help on a command.
  401. Usage: help [COMMAND]
  402. """
  403. if options['COMMAND']:
  404. subject = get_handler(cls, options['COMMAND'])
  405. else:
  406. subject = cls
  407. print(getdoc(subject))
  408. def images(self, options):
  409. """
  410. List images used by the created containers.
  411. Usage: images [options] [SERVICE...]
  412. Options:
  413. -q Only display IDs
  414. """
  415. containers = sorted(
  416. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  417. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  418. key=attrgetter('name'))
  419. if options['-q']:
  420. for image in set(c.image for c in containers):
  421. print(image.split(':')[1])
  422. else:
  423. headers = [
  424. 'Container',
  425. 'Repository',
  426. 'Tag',
  427. 'Image Id',
  428. 'Size'
  429. ]
  430. rows = []
  431. for container in containers:
  432. image_config = container.image_config
  433. repo_tags = image_config['RepoTags'][0].split(':')
  434. image_id = image_config['Id'].split(':')[1][:12]
  435. size = human_readable_file_size(image_config['Size'])
  436. rows.append([
  437. container.name,
  438. repo_tags[0],
  439. repo_tags[1],
  440. image_id,
  441. size
  442. ])
  443. print(Formatter().table(headers, rows))
  444. def kill(self, options):
  445. """
  446. Force stop service containers.
  447. Usage: kill [options] [SERVICE...]
  448. Options:
  449. -s SIGNAL SIGNAL to send to the container.
  450. Default signal is SIGKILL.
  451. """
  452. signal = options.get('-s', 'SIGKILL')
  453. self.project.kill(service_names=options['SERVICE'], signal=signal)
  454. def logs(self, options):
  455. """
  456. View output from containers.
  457. Usage: logs [options] [SERVICE...]
  458. Options:
  459. --no-color Produce monochrome output.
  460. -f, --follow Follow log output.
  461. -t, --timestamps Show timestamps.
  462. --tail="all" Number of lines to show from the end of the logs
  463. for each container.
  464. """
  465. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  466. tail = options['--tail']
  467. if tail is not None:
  468. if tail.isdigit():
  469. tail = int(tail)
  470. elif tail != 'all':
  471. raise UserError("tail flag must be all or a number")
  472. log_args = {
  473. 'follow': options['--follow'],
  474. 'tail': tail,
  475. 'timestamps': options['--timestamps']
  476. }
  477. print("Attaching to", list_containers(containers))
  478. log_printer_from_project(
  479. self.project,
  480. containers,
  481. options['--no-color'],
  482. log_args,
  483. event_stream=self.project.events(service_names=options['SERVICE'])).run()
  484. def pause(self, options):
  485. """
  486. Pause services.
  487. Usage: pause [SERVICE...]
  488. """
  489. containers = self.project.pause(service_names=options['SERVICE'])
  490. exit_if(not containers, 'No containers to pause', 1)
  491. def port(self, options):
  492. """
  493. Print the public port for a port binding.
  494. Usage: port [options] SERVICE PRIVATE_PORT
  495. Options:
  496. --protocol=proto tcp or udp [default: tcp]
  497. --index=index index of the container if there are multiple
  498. instances of a service [default: 1]
  499. """
  500. index = int(options.get('--index'))
  501. service = self.project.get_service(options['SERVICE'])
  502. try:
  503. container = service.get_container(number=index)
  504. except ValueError as e:
  505. raise UserError(str(e))
  506. print(container.get_local_port(
  507. options['PRIVATE_PORT'],
  508. protocol=options.get('--protocol') or 'tcp') or '')
  509. def ps(self, options):
  510. """
  511. List containers.
  512. Usage: ps [options] [SERVICE...]
  513. Options:
  514. -q Only display IDs
  515. """
  516. containers = sorted(
  517. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  518. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  519. key=attrgetter('name'))
  520. if options['-q']:
  521. for container in containers:
  522. print(container.id)
  523. else:
  524. headers = [
  525. 'Name',
  526. 'Command',
  527. 'State',
  528. 'Ports',
  529. ]
  530. rows = []
  531. for container in containers:
  532. command = container.human_readable_command
  533. if len(command) > 30:
  534. command = '%s ...' % command[:26]
  535. rows.append([
  536. container.name,
  537. command,
  538. container.human_readable_state,
  539. container.human_readable_ports,
  540. ])
  541. print(Formatter().table(headers, rows))
  542. def pull(self, options):
  543. """
  544. Pulls images for services.
  545. Usage: pull [options] [SERVICE...]
  546. Options:
  547. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  548. --parallel Pull multiple images in parallel.
  549. """
  550. self.project.pull(
  551. service_names=options['SERVICE'],
  552. ignore_pull_failures=options.get('--ignore-pull-failures'),
  553. parallel_pull=options.get('--parallel')
  554. )
  555. def push(self, options):
  556. """
  557. Pushes images for services.
  558. Usage: push [options] [SERVICE...]
  559. Options:
  560. --ignore-push-failures Push what it can and ignores images with push failures.
  561. """
  562. self.project.push(
  563. service_names=options['SERVICE'],
  564. ignore_push_failures=options.get('--ignore-push-failures')
  565. )
  566. def rm(self, options):
  567. """
  568. Removes stopped service containers.
  569. By default, anonymous volumes attached to containers will not be removed. You
  570. can override this with `-v`. To list all volumes, use `docker volume ls`.
  571. Any data which is not in a volume will be lost.
  572. Usage: rm [options] [SERVICE...]
  573. Options:
  574. -f, --force Don't ask to confirm removal
  575. -s, --stop Stop the containers, if required, before removing
  576. -v Remove any anonymous volumes attached to containers
  577. -a, --all Deprecated - no effect.
  578. """
  579. if options.get('--all'):
  580. log.warn(
  581. '--all flag is obsolete. This is now the default behavior '
  582. 'of `docker-compose rm`'
  583. )
  584. one_off = OneOffFilter.include
  585. if options.get('--stop'):
  586. running_containers = self.project.containers(
  587. service_names=options['SERVICE'], stopped=False, one_off=one_off
  588. )
  589. self.project.stop(
  590. service_names=running_containers,
  591. one_off=one_off
  592. )
  593. all_containers = self.project.containers(
  594. service_names=options['SERVICE'], stopped=True, one_off=one_off
  595. )
  596. stopped_containers = [c for c in all_containers if not c.is_running]
  597. if len(stopped_containers) > 0:
  598. print("Going to remove", list_containers(stopped_containers))
  599. if options.get('--force') \
  600. or yesno("Are you sure? [yN] ", default=False):
  601. self.project.remove_stopped(
  602. service_names=options['SERVICE'],
  603. v=options.get('-v', False),
  604. one_off=one_off
  605. )
  606. else:
  607. print("No stopped containers")
  608. def run(self, options):
  609. """
  610. Run a one-off command on a service.
  611. For example:
  612. $ docker-compose run web python manage.py shell
  613. By default, linked services will be started, unless they are already
  614. running. If you do not want to start linked services, use
  615. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  616. Usage: run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  617. Options:
  618. -d Detached mode: Run container in the background, print
  619. new container name.
  620. --name NAME Assign a name to the container
  621. --entrypoint CMD Override the entrypoint of the image.
  622. -e KEY=VAL Set an environment variable (can be used multiple times)
  623. -u, --user="" Run as specified username or uid
  624. --no-deps Don't start linked services.
  625. --rm Remove container after run. Ignored in detached mode.
  626. -p, --publish=[] Publish a container's port(s) to the host
  627. --service-ports Run command with the service's ports enabled and mapped
  628. to the host.
  629. -v, --volume=[] Bind mount a volume (default [])
  630. -T Disable pseudo-tty allocation. By default `docker-compose run`
  631. allocates a TTY.
  632. -w, --workdir="" Working directory inside the container
  633. """
  634. service = self.project.get_service(options['SERVICE'])
  635. detach = options['-d']
  636. if options['--publish'] and options['--service-ports']:
  637. raise UserError(
  638. 'Service port mapping and manual port mapping '
  639. 'can not be used together'
  640. )
  641. if options['COMMAND'] is not None:
  642. command = [options['COMMAND']] + options['ARGS']
  643. elif options['--entrypoint'] is not None:
  644. command = []
  645. else:
  646. command = service.options.get('command')
  647. container_options = build_container_options(options, detach, command)
  648. run_one_off_container(container_options, self.project, service, options)
  649. def scale(self, options):
  650. """
  651. Set number of containers to run for a service.
  652. Numbers are specified in the form `service=num` as arguments.
  653. For example:
  654. $ docker-compose scale web=2 worker=3
  655. Usage: scale [options] [SERVICE=NUM...]
  656. Options:
  657. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  658. (default: 10)
  659. """
  660. timeout = timeout_from_opts(options)
  661. for s in options['SERVICE=NUM']:
  662. if '=' not in s:
  663. raise UserError('Arguments to scale should be in the form service=num')
  664. service_name, num = s.split('=', 1)
  665. try:
  666. num = int(num)
  667. except ValueError:
  668. raise UserError('Number of containers for service "%s" is not a '
  669. 'number' % service_name)
  670. self.project.get_service(service_name).scale(num, timeout=timeout)
  671. def start(self, options):
  672. """
  673. Start existing containers.
  674. Usage: start [SERVICE...]
  675. """
  676. containers = self.project.start(service_names=options['SERVICE'])
  677. exit_if(not containers, 'No containers to start', 1)
  678. def stop(self, options):
  679. """
  680. Stop running containers without removing them.
  681. They can be started again with `docker-compose start`.
  682. Usage: stop [options] [SERVICE...]
  683. Options:
  684. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  685. (default: 10)
  686. """
  687. timeout = timeout_from_opts(options)
  688. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  689. def restart(self, options):
  690. """
  691. Restart running containers.
  692. Usage: restart [options] [SERVICE...]
  693. Options:
  694. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  695. (default: 10)
  696. """
  697. timeout = timeout_from_opts(options)
  698. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  699. exit_if(not containers, 'No containers to restart', 1)
  700. def top(self, options):
  701. """
  702. Display the running processes
  703. Usage: top [SERVICE...]
  704. """
  705. containers = sorted(
  706. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  707. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  708. key=attrgetter('name')
  709. )
  710. for idx, container in enumerate(containers):
  711. if idx > 0:
  712. print()
  713. top_data = self.project.client.top(container.name)
  714. headers = top_data.get("Titles")
  715. rows = []
  716. for process in top_data.get("Processes", []):
  717. rows.append(process)
  718. print(container.name)
  719. print(Formatter().table(headers, rows))
  720. def unpause(self, options):
  721. """
  722. Unpause services.
  723. Usage: unpause [SERVICE...]
  724. """
  725. containers = self.project.unpause(service_names=options['SERVICE'])
  726. exit_if(not containers, 'No containers to unpause', 1)
  727. def up(self, options):
  728. """
  729. Builds, (re)creates, starts, and attaches to containers for a service.
  730. Unless they are already running, this command also starts any linked services.
  731. The `docker-compose up` command aggregates the output of each container. When
  732. the command exits, all containers are stopped. Running `docker-compose up -d`
  733. starts the containers in the background and leaves them running.
  734. If there are existing containers for a service, and the service's configuration
  735. or image was changed after the container's creation, `docker-compose up` picks
  736. up the changes by stopping and recreating the containers (preserving mounted
  737. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  738. flag.
  739. If you want to force Compose to stop and recreate all containers, use the
  740. `--force-recreate` flag.
  741. Usage: up [options] [SERVICE...]
  742. Options:
  743. -d Detached mode: Run containers in the background,
  744. print new container names.
  745. Incompatible with --abort-on-container-exit.
  746. --no-color Produce monochrome output.
  747. --no-deps Don't start linked services.
  748. --force-recreate Recreate containers even if their configuration
  749. and image haven't changed.
  750. Incompatible with --no-recreate.
  751. --no-recreate If containers already exist, don't recreate them.
  752. Incompatible with --force-recreate.
  753. --no-build Don't build an image, even if it's missing.
  754. --build Build images before starting containers.
  755. --abort-on-container-exit Stops all containers if any container was stopped.
  756. Incompatible with -d.
  757. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  758. when attached or when containers are already
  759. running. (default: 10)
  760. --remove-orphans Remove containers for services not
  761. defined in the Compose file
  762. --exit-code-from SERVICE Return the exit code of the selected service container.
  763. Requires --abort-on-container-exit.
  764. """
  765. start_deps = not options['--no-deps']
  766. exit_value_from = exitval_from_opts(options, self.project)
  767. cascade_stop = options['--abort-on-container-exit']
  768. service_names = options['SERVICE']
  769. timeout = timeout_from_opts(options)
  770. remove_orphans = options['--remove-orphans']
  771. detached = options.get('-d')
  772. if detached and cascade_stop:
  773. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  774. with up_shutdown_context(self.project, service_names, timeout, detached):
  775. to_attach = self.project.up(
  776. service_names=service_names,
  777. start_deps=start_deps,
  778. strategy=convergence_strategy_from_opts(options),
  779. do_build=build_action_from_opts(options),
  780. timeout=timeout,
  781. detached=detached,
  782. remove_orphans=remove_orphans)
  783. if detached:
  784. return
  785. attached_containers = filter_containers_to_service_names(to_attach, service_names)
  786. log_printer = log_printer_from_project(
  787. self.project,
  788. attached_containers,
  789. options['--no-color'],
  790. {'follow': True},
  791. cascade_stop,
  792. event_stream=self.project.events(service_names=service_names))
  793. print("Attaching to", list_containers(log_printer.containers))
  794. cascade_starter = log_printer.run()
  795. if cascade_stop:
  796. print("Aborting on container exit...")
  797. exit_code = 0
  798. if exit_value_from:
  799. candidates = filter(
  800. lambda c: c.service == exit_value_from,
  801. attached_containers)
  802. if not candidates:
  803. log.error(
  804. 'No containers matching the spec "{0}" '
  805. 'were run.'.format(exit_value_from)
  806. )
  807. exit_code = 2
  808. elif len(candidates) > 1:
  809. exit_values = filter(
  810. lambda e: e != 0,
  811. [c.inspect()['State']['ExitCode'] for c in candidates]
  812. )
  813. exit_code = exit_values[0]
  814. else:
  815. exit_code = candidates[0].inspect()['State']['ExitCode']
  816. else:
  817. for e in self.project.containers(service_names=options['SERVICE'], stopped=True):
  818. if (not e.is_running and cascade_starter == e.name):
  819. if not e.exit_code == 0:
  820. exit_code = e.exit_code
  821. break
  822. self.project.stop(service_names=service_names, timeout=timeout)
  823. sys.exit(exit_code)
  824. @classmethod
  825. def version(cls, options):
  826. """
  827. Show version informations
  828. Usage: version [--short]
  829. Options:
  830. --short Shows only Compose's version number.
  831. """
  832. if options['--short']:
  833. print(__version__)
  834. else:
  835. print(get_version_info('full'))
  836. def convergence_strategy_from_opts(options):
  837. no_recreate = options['--no-recreate']
  838. force_recreate = options['--force-recreate']
  839. if force_recreate and no_recreate:
  840. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  841. if force_recreate:
  842. return ConvergenceStrategy.always
  843. if no_recreate:
  844. return ConvergenceStrategy.never
  845. return ConvergenceStrategy.changed
  846. def timeout_from_opts(options):
  847. timeout = options.get('--timeout')
  848. return None if timeout is None else int(timeout)
  849. def exitval_from_opts(options, project):
  850. exit_value_from = options.get('--exit-code-from')
  851. if exit_value_from:
  852. if not options.get('--abort-on-container-exit'):
  853. log.warn('using --exit-code-from implies --abort-on-container-exit')
  854. options['--abort-on-container-exit'] = True
  855. if exit_value_from not in [s.name for s in project.get_services()]:
  856. log.error('No service named "%s" was found in your compose file.',
  857. exit_value_from)
  858. sys.exit(2)
  859. return exit_value_from
  860. def image_type_from_opt(flag, value):
  861. if not value:
  862. return ImageType.none
  863. try:
  864. return ImageType[value]
  865. except KeyError:
  866. raise UserError("%s flag must be one of: all, local" % flag)
  867. def build_action_from_opts(options):
  868. if options['--build'] and options['--no-build']:
  869. raise UserError("--build and --no-build can not be combined.")
  870. if options['--build']:
  871. return BuildAction.force
  872. if options['--no-build']:
  873. return BuildAction.skip
  874. return BuildAction.none
  875. def build_container_options(options, detach, command):
  876. container_options = {
  877. 'command': command,
  878. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  879. 'stdin_open': not detach,
  880. 'detach': detach,
  881. }
  882. if options['-e']:
  883. container_options['environment'] = Environment.from_command_line(
  884. parse_environment(options['-e'])
  885. )
  886. if options['--entrypoint']:
  887. container_options['entrypoint'] = options.get('--entrypoint')
  888. if options['--rm']:
  889. container_options['restart'] = None
  890. if options['--user']:
  891. container_options['user'] = options.get('--user')
  892. if not options['--service-ports']:
  893. container_options['ports'] = []
  894. if options['--publish']:
  895. container_options['ports'] = options.get('--publish')
  896. if options['--name']:
  897. container_options['name'] = options['--name']
  898. if options['--workdir']:
  899. container_options['working_dir'] = options['--workdir']
  900. if options['--volume']:
  901. volumes = [VolumeSpec.parse(i) for i in options['--volume']]
  902. container_options['volumes'] = volumes
  903. return container_options
  904. def run_one_off_container(container_options, project, service, options):
  905. if not options['--no-deps']:
  906. deps = service.get_dependency_names()
  907. if deps:
  908. project.up(
  909. service_names=deps,
  910. start_deps=True,
  911. strategy=ConvergenceStrategy.never)
  912. project.initialize()
  913. container = service.create_container(
  914. quiet=True,
  915. one_off=True,
  916. **container_options)
  917. if options['-d']:
  918. service.start_container(container)
  919. print(container.name)
  920. return
  921. def remove_container(force=False):
  922. if options['--rm']:
  923. project.client.remove_container(container.id, force=True, v=True)
  924. signals.set_signal_handler_to_shutdown()
  925. try:
  926. try:
  927. if IS_WINDOWS_PLATFORM:
  928. service.connect_container_to_networks(container)
  929. exit_code = call_docker(["start", "--attach", "--interactive", container.id])
  930. else:
  931. operation = RunOperation(
  932. project.client,
  933. container.id,
  934. interactive=not options['-T'],
  935. logs=False,
  936. )
  937. pty = PseudoTerminal(project.client, operation)
  938. sockets = pty.sockets()
  939. service.start_container(container)
  940. pty.start(sockets)
  941. exit_code = container.wait()
  942. except signals.ShutdownException:
  943. project.client.stop(container.id)
  944. exit_code = 1
  945. except signals.ShutdownException:
  946. project.client.kill(container.id)
  947. remove_container(force=True)
  948. sys.exit(2)
  949. remove_container()
  950. sys.exit(exit_code)
  951. def log_printer_from_project(
  952. project,
  953. containers,
  954. monochrome,
  955. log_args,
  956. cascade_stop=False,
  957. event_stream=None,
  958. ):
  959. return LogPrinter(
  960. containers,
  961. build_log_presenters(project.service_names, monochrome),
  962. event_stream or project.events(),
  963. cascade_stop=cascade_stop,
  964. log_args=log_args)
  965. def filter_containers_to_service_names(containers, service_names):
  966. if not service_names:
  967. return containers
  968. return [
  969. container
  970. for container in containers if container.service in service_names
  971. ]
  972. @contextlib.contextmanager
  973. def up_shutdown_context(project, service_names, timeout, detached):
  974. if detached:
  975. yield
  976. return
  977. signals.set_signal_handler_to_shutdown()
  978. try:
  979. try:
  980. yield
  981. except signals.ShutdownException:
  982. print("Gracefully stopping... (press Ctrl+C again to force)")
  983. project.stop(service_names=service_names, timeout=timeout)
  984. except signals.ShutdownException:
  985. project.kill(service_names=service_names)
  986. sys.exit(2)
  987. def list_containers(containers):
  988. return ", ".join(c.name for c in containers)
  989. def exit_if(condition, message, exit_code):
  990. if condition:
  991. log.error(message)
  992. raise SystemExit(exit_code)
  993. def call_docker(args):
  994. executable_path = find_executable('docker')
  995. if not executable_path:
  996. raise UserError(errors.docker_not_found_msg("Couldn't find `docker` binary."))
  997. args = [executable_path] + args
  998. log.debug(" ".join(map(pipes.quote, args)))
  999. return subprocess.call(args)