client.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. # Copyright 2013 dotCloud inc.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import json
  12. import re
  13. import shlex
  14. import struct
  15. import requests
  16. import requests.exceptions
  17. import six
  18. from .auth import auth
  19. from .unixconn import unixconn
  20. from .utils import utils
  21. if not six.PY3:
  22. import websocket
  23. DEFAULT_TIMEOUT_SECONDS = 60
  24. STREAM_HEADER_SIZE_BYTES = 8
  25. class APIError(requests.exceptions.HTTPError):
  26. def __init__(self, message, response, explanation=None):
  27. super(APIError, self).__init__(message, response=response)
  28. self.explanation = explanation
  29. if self.explanation is None and response.content:
  30. self.explanation = response.content.strip()
  31. def __str__(self):
  32. message = super(APIError, self).__str__()
  33. if self.is_client_error():
  34. message = '%s Client Error: %s' % (
  35. self.response.status_code, self.response.reason)
  36. elif self.is_server_error():
  37. message = '%s Server Error: %s' % (
  38. self.response.status_code, self.response.reason)
  39. if self.explanation:
  40. message = '%s ("%s")' % (message, self.explanation)
  41. return message
  42. def is_client_error(self):
  43. return 400 <= self.response.status_code < 500
  44. def is_server_error(self):
  45. return 500 <= self.response.status_code < 600
  46. class Client(requests.Session):
  47. def __init__(self, base_url=None, version="1.6",
  48. timeout=DEFAULT_TIMEOUT_SECONDS):
  49. super(Client, self).__init__()
  50. if base_url is None:
  51. base_url = "unix://var/run/docker.sock"
  52. if base_url.startswith('unix:///'):
  53. base_url = base_url.replace('unix:/', 'unix:')
  54. if base_url.startswith('tcp:'):
  55. base_url = base_url.replace('tcp:', 'http:')
  56. if base_url.endswith('/'):
  57. base_url = base_url[:-1]
  58. self.base_url = base_url
  59. self._version = version
  60. self._timeout = timeout
  61. self._auth_configs = auth.load_config()
  62. self.mount('unix://', unixconn.UnixAdapter(base_url, timeout))
  63. def _set_request_timeout(self, kwargs):
  64. """Prepare the kwargs for an HTTP request by inserting the timeout
  65. parameter, if not already present."""
  66. kwargs.setdefault('timeout', self._timeout)
  67. return kwargs
  68. def _post(self, url, **kwargs):
  69. return self.post(url, **self._set_request_timeout(kwargs))
  70. def _get(self, url, **kwargs):
  71. return self.get(url, **self._set_request_timeout(kwargs))
  72. def _delete(self, url, **kwargs):
  73. return self.delete(url, **self._set_request_timeout(kwargs))
  74. def _url(self, path):
  75. return '{0}/v{1}{2}'.format(self.base_url, self._version, path)
  76. def _raise_for_status(self, response, explanation=None):
  77. """Raises stored :class:`APIError`, if one occurred."""
  78. try:
  79. response.raise_for_status()
  80. except requests.exceptions.HTTPError as e:
  81. raise APIError(e, response, explanation=explanation)
  82. def _result(self, response, json=False, binary=False):
  83. assert not (json and binary)
  84. self._raise_for_status(response)
  85. if json:
  86. return response.json()
  87. if binary:
  88. return response.content
  89. return response.text
  90. def _container_config(self, image, command, hostname=None, user=None,
  91. detach=False, stdin_open=False, tty=False,
  92. mem_limit=0, ports=None, environment=None, dns=None,
  93. volumes=None, volumes_from=None,
  94. network_disabled=False, entrypoint=None,
  95. cpu_shares=None, working_dir=None):
  96. if isinstance(command, six.string_types):
  97. command = shlex.split(str(command))
  98. if isinstance(environment, dict):
  99. environment = [
  100. '{0}={1}'.format(k, v) for k, v in environment.items()
  101. ]
  102. if ports and isinstance(ports, list):
  103. exposed_ports = {}
  104. for port_definition in ports:
  105. port = port_definition
  106. proto = 'tcp'
  107. if isinstance(port_definition, tuple):
  108. if len(port_definition) == 2:
  109. proto = port_definition[1]
  110. port = port_definition[0]
  111. exposed_ports['{0}/{1}'.format(port, proto)] = {}
  112. ports = exposed_ports
  113. if volumes and isinstance(volumes, list):
  114. volumes_dict = {}
  115. for vol in volumes:
  116. volumes_dict[vol] = {}
  117. volumes = volumes_dict
  118. attach_stdin = False
  119. attach_stdout = False
  120. attach_stderr = False
  121. if not detach:
  122. attach_stdout = True
  123. attach_stderr = True
  124. if stdin_open:
  125. attach_stdin = True
  126. return {
  127. 'Hostname': hostname,
  128. 'ExposedPorts': ports,
  129. 'User': user,
  130. 'Tty': tty,
  131. 'OpenStdin': stdin_open,
  132. 'Memory': mem_limit,
  133. 'AttachStdin': attach_stdin,
  134. 'AttachStdout': attach_stdout,
  135. 'AttachStderr': attach_stderr,
  136. 'Env': environment,
  137. 'Cmd': command,
  138. 'Dns': dns,
  139. 'Image': image,
  140. 'Volumes': volumes,
  141. 'VolumesFrom': volumes_from,
  142. 'NetworkDisabled': network_disabled,
  143. 'Entrypoint': entrypoint,
  144. 'CpuShares': cpu_shares,
  145. 'WorkingDir': working_dir
  146. }
  147. def _post_json(self, url, data, **kwargs):
  148. # Go <1.1 can't unserialize null to a string
  149. # so we do this disgusting thing here.
  150. data2 = {}
  151. if data is not None:
  152. for k, v in six.iteritems(data):
  153. if v is not None:
  154. data2[k] = v
  155. if 'headers' not in kwargs:
  156. kwargs['headers'] = {}
  157. kwargs['headers']['Content-Type'] = 'application/json'
  158. return self._post(url, data=json.dumps(data2), **kwargs)
  159. def _attach_params(self, override=None):
  160. return override or {
  161. 'stdout': 1,
  162. 'stderr': 1,
  163. 'stream': 1
  164. }
  165. def _attach_websocket(self, container, params=None):
  166. if six.PY3:
  167. raise NotImplementedError("This method is not currently supported "
  168. "under python 3")
  169. url = self._url("/containers/{0}/attach/ws".format(container))
  170. req = requests.Request("POST", url, params=self._attach_params(params))
  171. full_url = req.prepare().url
  172. full_url = full_url.replace("http://", "ws://", 1)
  173. full_url = full_url.replace("https://", "wss://", 1)
  174. return self._create_websocket_connection(full_url)
  175. def _create_websocket_connection(self, url):
  176. return websocket.create_connection(url)
  177. def _stream_result(self, response):
  178. """Generator for straight-out, non chunked-encoded HTTP responses."""
  179. self._raise_for_status(response)
  180. for line in response.iter_lines(chunk_size=1):
  181. # filter out keep-alive new lines
  182. if line:
  183. yield line + '\n'
  184. def _stream_result_socket(self, response):
  185. self._raise_for_status(response)
  186. return response.raw._fp.fp._sock
  187. def _stream_helper(self, response):
  188. """Generator for data coming from a chunked-encoded HTTP response."""
  189. socket_fp = self._stream_result_socket(response)
  190. socket_fp.setblocking(1)
  191. socket = socket_fp.makefile()
  192. while True:
  193. size = int(socket.readline(), 16)
  194. if size <= 0:
  195. break
  196. data = socket.readline()
  197. if not data:
  198. break
  199. yield data
  200. def _multiplexed_buffer_helper(self, response):
  201. """A generator of multiplexed data blocks read from a buffered
  202. response."""
  203. buf = self._result(response, binary=True)
  204. walker = 0
  205. while True:
  206. if len(buf[walker:]) < 8:
  207. break
  208. _, length = struct.unpack_from('>BxxxL', buf[walker:])
  209. start = walker + STREAM_HEADER_SIZE_BYTES
  210. end = start + length
  211. walker = end
  212. yield str(buf[start:end])
  213. def _multiplexed_socket_stream_helper(self, response):
  214. """A generator of multiplexed data blocks coming from a response
  215. socket."""
  216. socket = self._stream_result_socket(response)
  217. def recvall(socket, size):
  218. data = ''
  219. while size > 0:
  220. block = socket.recv(size)
  221. if not block:
  222. return None
  223. data += block
  224. size -= len(block)
  225. return data
  226. while True:
  227. socket.settimeout(None)
  228. header = recvall(socket, STREAM_HEADER_SIZE_BYTES)
  229. if not header:
  230. break
  231. _, length = struct.unpack('>BxxxL', header)
  232. if not length:
  233. break
  234. data = recvall(socket, length)
  235. if not data:
  236. break
  237. yield data
  238. def attach(self, container, stdout=True, stderr=True,
  239. stream=False, logs=False):
  240. if isinstance(container, dict):
  241. container = container.get('Id')
  242. params = {
  243. 'logs': logs and 1 or 0,
  244. 'stdout': stdout and 1 or 0,
  245. 'stderr': stderr and 1 or 0,
  246. 'stream': stream and 1 or 0,
  247. }
  248. u = self._url("/containers/{0}/attach".format(container))
  249. response = self._post(u, params=params, stream=stream)
  250. # Stream multi-plexing was introduced in API v1.6.
  251. if utils.compare_version('1.6', self._version) < 0:
  252. return stream and self._stream_result(response) or \
  253. self._result(response, binary=True)
  254. return stream and self._multiplexed_socket_stream_helper(response) or \
  255. ''.join([x for x in self._multiplexed_buffer_helper(response)])
  256. def attach_socket(self, container, params=None, ws=False):
  257. if params is None:
  258. params = {
  259. 'stdout': 1,
  260. 'stderr': 1,
  261. 'stream': 1
  262. }
  263. if ws:
  264. return self._attach_websocket(container, params)
  265. if isinstance(container, dict):
  266. container = container.get('Id')
  267. u = self._url("/containers/{0}/attach".format(container))
  268. return self._stream_result_socket(self.post(
  269. u, None, params=self._attach_params(params), stream=True))
  270. def build(self, path=None, tag=None, quiet=False, fileobj=None,
  271. nocache=False, rm=False, stream=False, timeout=None):
  272. remote = context = headers = None
  273. if path is None and fileobj is None:
  274. raise Exception("Either path or fileobj needs to be provided.")
  275. if fileobj is not None:
  276. context = utils.mkbuildcontext(fileobj)
  277. elif path.startswith(('http://', 'https://', 'git://', 'github.com/')):
  278. remote = path
  279. else:
  280. context = utils.tar(path)
  281. u = self._url('/build')
  282. params = {
  283. 't': tag,
  284. 'remote': remote,
  285. 'q': quiet,
  286. 'nocache': nocache,
  287. 'rm': rm
  288. }
  289. if context is not None:
  290. headers = {'Content-Type': 'application/tar'}
  291. response = self._post(
  292. u,
  293. data=context,
  294. params=params,
  295. headers=headers,
  296. stream=stream,
  297. timeout=timeout,
  298. )
  299. if context is not None:
  300. context.close()
  301. if stream:
  302. return self._stream_result(response)
  303. else:
  304. output = self._result(response)
  305. srch = r'Successfully built ([0-9a-f]+)'
  306. match = re.search(srch, output)
  307. if not match:
  308. return None, output
  309. return match.group(1), output
  310. def commit(self, container, repository=None, tag=None, message=None,
  311. author=None, conf=None):
  312. params = {
  313. 'container': container,
  314. 'repo': repository,
  315. 'tag': tag,
  316. 'comment': message,
  317. 'author': author
  318. }
  319. u = self._url("/commit")
  320. return self._result(self._post_json(u, data=conf, params=params),
  321. json=True)
  322. def containers(self, quiet=False, all=False, trunc=True, latest=False,
  323. since=None, before=None, limit=-1):
  324. params = {
  325. 'limit': 1 if latest else limit,
  326. 'all': 1 if all else 0,
  327. 'trunc_cmd': 1 if trunc else 0,
  328. 'since': since,
  329. 'before': before
  330. }
  331. u = self._url("/containers/json")
  332. res = self._result(self._get(u, params=params), True)
  333. if quiet:
  334. return [{'Id': x['Id']} for x in res]
  335. return res
  336. def copy(self, container, resource):
  337. res = self._post_json(
  338. self._url("/containers/{0}/copy".format(container)),
  339. data={"Resource": resource},
  340. stream=True
  341. )
  342. self._raise_for_status(res)
  343. return res.raw
  344. def create_container(self, image, command=None, hostname=None, user=None,
  345. detach=False, stdin_open=False, tty=False,
  346. mem_limit=0, ports=None, environment=None, dns=None,
  347. volumes=None, volumes_from=None,
  348. network_disabled=False, name=None, entrypoint=None,
  349. cpu_shares=None, working_dir=None):
  350. config = self._container_config(
  351. image, command, hostname, user, detach, stdin_open, tty, mem_limit,
  352. ports, environment, dns, volumes, volumes_from, network_disabled,
  353. entrypoint, cpu_shares, working_dir
  354. )
  355. return self.create_container_from_config(config, name)
  356. def create_container_from_config(self, config, name=None):
  357. u = self._url("/containers/create")
  358. params = {
  359. 'name': name
  360. }
  361. res = self._post_json(u, data=config, params=params)
  362. return self._result(res, True)
  363. def diff(self, container):
  364. if isinstance(container, dict):
  365. container = container.get('Id')
  366. return self._result(self._get(self._url("/containers/{0}/changes".
  367. format(container))), True)
  368. def events(self):
  369. u = self._url("/events")
  370. socket = self._stream_result_socket(self.get(u, stream=True))
  371. while True:
  372. chunk = socket.recv(4096)
  373. if chunk:
  374. # Messages come in the format of length, data, newline.
  375. length, data = chunk.split("\n", 1)
  376. length = int(length, 16)
  377. if length > len(data):
  378. data += socket.recv(length - len(data))
  379. yield json.loads(data)
  380. else:
  381. break
  382. def export(self, container):
  383. if isinstance(container, dict):
  384. container = container.get('Id')
  385. res = self._get(self._url("/containers/{0}/export".format(container)),
  386. stream=True)
  387. self._raise_for_status(res)
  388. return res.raw
  389. def history(self, image):
  390. res = self._get(self._url("/images/{0}/history".format(image)))
  391. self._raise_for_status(res)
  392. return self._result(res)
  393. def images(self, name=None, quiet=False, all=False, viz=False):
  394. if viz:
  395. return self._result(self._get(self._url("images/viz")))
  396. params = {
  397. 'filter': name,
  398. 'only_ids': 1 if quiet else 0,
  399. 'all': 1 if all else 0,
  400. }
  401. res = self._result(self._get(self._url("/images/json"), params=params),
  402. True)
  403. if quiet:
  404. return [x['Id'] for x in res]
  405. return res
  406. def import_image(self, src=None, repository=None, tag=None, image=None):
  407. u = self._url("/images/create")
  408. params = {
  409. 'repo': repository,
  410. 'tag': tag
  411. }
  412. if src:
  413. try:
  414. # XXX: this is ways not optimal but the only way
  415. # for now to import tarballs through the API
  416. fic = open(src)
  417. data = fic.read()
  418. fic.close()
  419. src = "-"
  420. except IOError:
  421. # file does not exists or not a file (URL)
  422. data = None
  423. if isinstance(src, six.string_types):
  424. params['fromSrc'] = src
  425. return self._result(self._post(u, data=data, params=params))
  426. return self._result(self._post(u, data=src, params=params))
  427. if image:
  428. params['fromImage'] = image
  429. return self._result(self._post(u, data=None, params=params))
  430. raise Exception("Must specify a src or image")
  431. def info(self):
  432. return self._result(self._get(self._url("/info")),
  433. True)
  434. def insert(self, image, url, path):
  435. api_url = self._url("/images/" + image + "/insert")
  436. params = {
  437. 'url': url,
  438. 'path': path
  439. }
  440. return self._result(self._post(api_url, params=params))
  441. def inspect_container(self, container):
  442. if isinstance(container, dict):
  443. container = container.get('Id')
  444. return self._result(
  445. self._get(self._url("/containers/{0}/json".format(container))),
  446. True)
  447. def inspect_image(self, image_id):
  448. return self._result(
  449. self._get(self._url("/images/{0}/json".format(image_id))),
  450. True
  451. )
  452. def kill(self, container, signal=None):
  453. if isinstance(container, dict):
  454. container = container.get('Id')
  455. url = self._url("/containers/{0}/kill".format(container))
  456. params = {}
  457. if signal is not None:
  458. params['signal'] = signal
  459. res = self._post(url, params=params)
  460. self._raise_for_status(res)
  461. def login(self, username, password=None, email=None, registry=None,
  462. reauth=False):
  463. # If we don't have any auth data so far, try reloading the config file
  464. # one more time in case anything showed up in there.
  465. if not self._auth_configs:
  466. self._auth_configs = auth.load_config()
  467. registry = registry or auth.INDEX_URL
  468. authcfg = auth.resolve_authconfig(self._auth_configs, registry)
  469. # If we found an existing auth config for this registry and username
  470. # combination, we can return it immediately unless reauth is requested.
  471. if authcfg and authcfg.get('username', None) == username \
  472. and not reauth:
  473. return authcfg
  474. req_data = {
  475. 'username': username,
  476. 'password': password,
  477. 'email': email,
  478. 'serveraddress': registry,
  479. }
  480. response = self._post_json(self._url('/auth'), data=req_data)
  481. if response.status_code == 200:
  482. self._auth_configs[registry] = req_data
  483. return self._result(response, json=True)
  484. def logs(self, container, stdout=True, stderr=True, stream=False):
  485. return self.attach(
  486. container,
  487. stdout=stdout,
  488. stderr=stderr,
  489. stream=stream,
  490. logs=True
  491. )
  492. def port(self, container, private_port):
  493. if isinstance(container, dict):
  494. container = container.get('Id')
  495. res = self._get(self._url("/containers/{0}/json".format(container)))
  496. self._raise_for_status(res)
  497. json_ = res.json()
  498. s_port = str(private_port)
  499. h_ports = None
  500. h_ports = json_['NetworkSettings']['Ports'].get(s_port + '/udp')
  501. if h_ports is None:
  502. h_ports = json_['NetworkSettings']['Ports'].get(s_port + '/tcp')
  503. return h_ports
  504. def pull(self, repository, tag=None, stream=False):
  505. registry, repo_name = auth.resolve_repository_name(repository)
  506. if repo_name.count(":") == 1:
  507. repository, tag = repository.rsplit(":", 1)
  508. params = {
  509. 'tag': tag,
  510. 'fromImage': repository
  511. }
  512. headers = {}
  513. if utils.compare_version('1.5', self._version) >= 0:
  514. # If we don't have any auth data so far, try reloading the config
  515. # file one more time in case anything showed up in there.
  516. if not self._auth_configs:
  517. self._auth_configs = auth.load_config()
  518. authcfg = auth.resolve_authconfig(self._auth_configs, registry)
  519. # Do not fail here if no atuhentication exists for this specific
  520. # registry as we can have a readonly pull. Just put the header if
  521. # we can.
  522. if authcfg:
  523. headers['X-Registry-Auth'] = auth.encode_header(authcfg)
  524. response = self._post(self._url('/images/create'), params=params,
  525. headers=headers, stream=stream, timeout=None)
  526. if stream:
  527. return self._stream_helper(response)
  528. else:
  529. return self._result(response)
  530. def push(self, repository, stream=False):
  531. registry, repo_name = auth.resolve_repository_name(repository)
  532. u = self._url("/images/{0}/push".format(repository))
  533. headers = {}
  534. if utils.compare_version('1.5', self._version) >= 0:
  535. # If we don't have any auth data so far, try reloading the config
  536. # file one more time in case anything showed up in there.
  537. if not self._auth_configs:
  538. self._auth_configs = auth.load_config()
  539. authcfg = auth.resolve_authconfig(self._auth_configs, registry)
  540. # Do not fail here if no atuhentication exists for this specific
  541. # registry as we can have a readonly pull. Just put the header if
  542. # we can.
  543. if authcfg:
  544. headers['X-Registry-Auth'] = auth.encode_header(authcfg)
  545. response = self._post_json(u, None, headers=headers, stream=stream)
  546. else:
  547. response = self._post_json(u, authcfg, stream=stream)
  548. return stream and self._stream_helper(response) \
  549. or self._result(response)
  550. def remove_container(self, container, v=False, link=False):
  551. if isinstance(container, dict):
  552. container = container.get('Id')
  553. params = {'v': v, 'link': link}
  554. res = self._delete(self._url("/containers/" + container),
  555. params=params)
  556. self._raise_for_status(res)
  557. def remove_image(self, image):
  558. res = self._delete(self._url("/images/" + image))
  559. self._raise_for_status(res)
  560. def restart(self, container, timeout=10):
  561. if isinstance(container, dict):
  562. container = container.get('Id')
  563. params = {'t': timeout}
  564. url = self._url("/containers/{0}/restart".format(container))
  565. res = self._post(url, params=params)
  566. self._raise_for_status(res)
  567. def search(self, term):
  568. return self._result(self._get(self._url("/images/search"),
  569. params={'term': term}),
  570. True)
  571. def start(self, container, binds=None, port_bindings=None, lxc_conf=None,
  572. publish_all_ports=False, links=None, privileged=False):
  573. if isinstance(container, dict):
  574. container = container.get('Id')
  575. if isinstance(lxc_conf, dict):
  576. formatted = []
  577. for k, v in six.iteritems(lxc_conf):
  578. formatted.append({'Key': k, 'Value': str(v)})
  579. lxc_conf = formatted
  580. start_config = {
  581. 'LxcConf': lxc_conf
  582. }
  583. if binds:
  584. bind_pairs = [
  585. '{0}:{1}'.format(host, dest) for host, dest in binds.items()
  586. ]
  587. start_config['Binds'] = bind_pairs
  588. if port_bindings:
  589. start_config['PortBindings'] = utils.convert_port_bindings(
  590. port_bindings
  591. )
  592. start_config['PublishAllPorts'] = publish_all_ports
  593. if links:
  594. formatted_links = [
  595. '{0}:{1}'.format(k, v) for k, v in sorted(six.iteritems(links))
  596. ]
  597. start_config['Links'] = formatted_links
  598. start_config['Privileged'] = privileged
  599. url = self._url("/containers/{0}/start".format(container))
  600. res = self._post_json(url, data=start_config)
  601. self._raise_for_status(res)
  602. def stop(self, container, timeout=10):
  603. if isinstance(container, dict):
  604. container = container.get('Id')
  605. params = {'t': timeout}
  606. url = self._url("/containers/{0}/stop".format(container))
  607. res = self._post(url, params=params,
  608. timeout=max(timeout, self._timeout))
  609. self._raise_for_status(res)
  610. def tag(self, image, repository, tag=None, force=False):
  611. params = {
  612. 'tag': tag,
  613. 'repo': repository,
  614. 'force': 1 if force else 0
  615. }
  616. url = self._url("/images/{0}/tag".format(image))
  617. res = self._post(url, params=params)
  618. self._raise_for_status(res)
  619. return res.status_code == 201
  620. def top(self, container):
  621. u = self._url("/containers/{0}/top".format(container))
  622. return self._result(self._get(u), True)
  623. def version(self):
  624. return self._result(self._get(self._url("/version")), True)
  625. def wait(self, container):
  626. if isinstance(container, dict):
  627. container = container.get('Id')
  628. url = self._url("/containers/{0}/wait".format(container))
  629. res = self._post(url, timeout=None)
  630. self._raise_for_status(res)
  631. json_ = res.json()
  632. if 'StatusCode' in json_:
  633. return json_['StatusCode']
  634. return -1