main.py 39 KB

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