client.py 26 KB

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