client.py 26 KB

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