Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

exec_api.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from .. import errors
  2. from .. import utils
  3. from ..types import CancellableStream
  4. class ExecApiMixin:
  5. @utils.check_resource('container')
  6. def exec_create(self, container, cmd, stdout=True, stderr=True,
  7. stdin=False, tty=False, privileged=False, user='',
  8. environment=None, workdir=None, detach_keys=None):
  9. """
  10. Sets up an exec instance in a running container.
  11. Args:
  12. container (str): Target container where exec instance will be
  13. created
  14. cmd (str or list): Command to be executed
  15. stdout (bool): Attach to stdout. Default: ``True``
  16. stderr (bool): Attach to stderr. Default: ``True``
  17. stdin (bool): Attach to stdin. Default: ``False``
  18. tty (bool): Allocate a pseudo-TTY. Default: False
  19. privileged (bool): Run as privileged.
  20. user (str): User to execute command as. Default: root
  21. environment (dict or list): A dictionary or a list of strings in
  22. the following format ``["PASSWORD=xxx"]`` or
  23. ``{"PASSWORD": "xxx"}``.
  24. workdir (str): Path to working directory for this exec session
  25. detach_keys (str): Override the key sequence for detaching
  26. a container. Format is a single character `[a-Z]`
  27. or `ctrl-<value>` where `<value>` is one of:
  28. `a-z`, `@`, `^`, `[`, `,` or `_`.
  29. ~/.docker/config.json is used by default.
  30. Returns:
  31. (dict): A dictionary with an exec ``Id`` key.
  32. Raises:
  33. :py:class:`docker.errors.APIError`
  34. If the server returns an error.
  35. """
  36. if environment is not None and utils.version_lt(self._version, '1.25'):
  37. raise errors.InvalidVersion(
  38. 'Setting environment for exec is not supported in API < 1.25'
  39. )
  40. if isinstance(cmd, str):
  41. cmd = utils.split_command(cmd)
  42. if isinstance(environment, dict):
  43. environment = utils.utils.format_environment(environment)
  44. data = {
  45. 'Container': container,
  46. 'User': user,
  47. 'Privileged': privileged,
  48. 'Tty': tty,
  49. 'AttachStdin': stdin,
  50. 'AttachStdout': stdout,
  51. 'AttachStderr': stderr,
  52. 'Cmd': cmd,
  53. 'Env': environment,
  54. }
  55. if workdir is not None:
  56. if utils.version_lt(self._version, '1.35'):
  57. raise errors.InvalidVersion(
  58. 'workdir is not supported for API version < 1.35'
  59. )
  60. data['WorkingDir'] = workdir
  61. if detach_keys:
  62. data['detachKeys'] = detach_keys
  63. elif 'detachKeys' in self._general_configs:
  64. data['detachKeys'] = self._general_configs['detachKeys']
  65. url = self._url('/containers/{0}/exec', container)
  66. res = self._post_json(url, data=data)
  67. return self._result(res, True)
  68. def exec_inspect(self, exec_id):
  69. """
  70. Return low-level information about an exec command.
  71. Args:
  72. exec_id (str): ID of the exec instance
  73. Returns:
  74. (dict): Dictionary of values returned by the endpoint.
  75. Raises:
  76. :py:class:`docker.errors.APIError`
  77. If the server returns an error.
  78. """
  79. if isinstance(exec_id, dict):
  80. exec_id = exec_id.get('Id')
  81. res = self._get(self._url("/exec/{0}/json", exec_id))
  82. return self._result(res, True)
  83. def exec_resize(self, exec_id, height=None, width=None):
  84. """
  85. Resize the tty session used by the specified exec command.
  86. Args:
  87. exec_id (str): ID of the exec instance
  88. height (int): Height of tty session
  89. width (int): Width of tty session
  90. """
  91. if isinstance(exec_id, dict):
  92. exec_id = exec_id.get('Id')
  93. params = {'h': height, 'w': width}
  94. url = self._url("/exec/{0}/resize", exec_id)
  95. res = self._post(url, params=params)
  96. self._raise_for_status(res)
  97. @utils.check_resource('exec_id')
  98. def exec_start(self, exec_id, detach=False, tty=False, stream=False,
  99. socket=False, demux=False):
  100. """
  101. Start a previously set up exec instance.
  102. Args:
  103. exec_id (str): ID of the exec instance
  104. detach (bool): If true, detach from the exec command.
  105. Default: False
  106. tty (bool): Allocate a pseudo-TTY. Default: False
  107. stream (bool): Return response data progressively as an iterator
  108. of strings, rather than a single string.
  109. socket (bool): Return the connection socket to allow custom
  110. read/write operations. Must be closed by the caller when done.
  111. demux (bool): Return stdout and stderr separately
  112. Returns:
  113. (generator or str or tuple): If ``stream=True``, a generator
  114. yielding response chunks. If ``socket=True``, a socket object for
  115. the connection. A string containing response data otherwise. If
  116. ``demux=True``, a tuple with two elements of type byte: stdout and
  117. stderr.
  118. Raises:
  119. :py:class:`docker.errors.APIError`
  120. If the server returns an error.
  121. """
  122. # we want opened socket if socket == True
  123. data = {
  124. 'Tty': tty,
  125. 'Detach': detach
  126. }
  127. headers = {} if detach else {
  128. 'Connection': 'Upgrade',
  129. 'Upgrade': 'tcp'
  130. }
  131. res = self._post_json(
  132. self._url('/exec/{0}/start', exec_id),
  133. headers=headers,
  134. data=data,
  135. stream=True
  136. )
  137. if detach:
  138. try:
  139. return self._result(res)
  140. finally:
  141. res.close()
  142. if socket:
  143. return self._get_raw_response_socket(res)
  144. output = self._read_from_socket(res, stream, tty=tty, demux=demux)
  145. if stream:
  146. return CancellableStream(output, res)
  147. else:
  148. return output