main.py 48 KB

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