main.py 18 KB

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