client.py 27 KB

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