service_test.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import docker
  4. import pytest
  5. from .. import mock
  6. from .. import unittest
  7. from compose.const import IS_WINDOWS_PLATFORM
  8. from compose.const import LABEL_CONFIG_HASH
  9. from compose.const import LABEL_ONE_OFF
  10. from compose.const import LABEL_PROJECT
  11. from compose.const import LABEL_SERVICE
  12. from compose.container import Container
  13. from compose.service import build_volume_binding
  14. from compose.service import ConfigError
  15. from compose.service import ContainerNet
  16. from compose.service import get_container_data_volumes
  17. from compose.service import merge_volume_bindings
  18. from compose.service import NeedsBuildError
  19. from compose.service import Net
  20. from compose.service import NoSuchImageError
  21. from compose.service import parse_repository_tag
  22. from compose.service import parse_volume_spec
  23. from compose.service import Service
  24. from compose.service import ServiceNet
  25. from compose.service import VolumeFromSpec
  26. class ServiceTest(unittest.TestCase):
  27. def setUp(self):
  28. self.mock_client = mock.create_autospec(docker.Client)
  29. def test_project_validation(self):
  30. self.assertRaises(ConfigError, lambda: Service(name='foo', project='>', image='foo'))
  31. Service(name='foo', project='bar.bar__', image='foo')
  32. def test_containers(self):
  33. service = Service('db', self.mock_client, 'myproject', image='foo')
  34. self.mock_client.containers.return_value = []
  35. self.assertEqual(list(service.containers()), [])
  36. def test_containers_with_containers(self):
  37. self.mock_client.containers.return_value = [
  38. dict(Name=str(i), Image='foo', Id=i) for i in range(3)
  39. ]
  40. service = Service('db', self.mock_client, 'myproject', image='foo')
  41. self.assertEqual([c.id for c in service.containers()], list(range(3)))
  42. expected_labels = [
  43. '{0}=myproject'.format(LABEL_PROJECT),
  44. '{0}=db'.format(LABEL_SERVICE),
  45. '{0}=False'.format(LABEL_ONE_OFF),
  46. ]
  47. self.mock_client.containers.assert_called_once_with(
  48. all=False,
  49. filters={'label': expected_labels})
  50. def test_container_without_name(self):
  51. self.mock_client.containers.return_value = [
  52. {'Image': 'foo', 'Id': '1', 'Name': '1'},
  53. {'Image': 'foo', 'Id': '2', 'Name': None},
  54. {'Image': 'foo', 'Id': '3'},
  55. ]
  56. service = Service('db', self.mock_client, 'myproject', image='foo')
  57. self.assertEqual([c.id for c in service.containers()], ['1'])
  58. self.assertEqual(service._next_container_number(), 2)
  59. self.assertEqual(service.get_container(1).id, '1')
  60. def test_get_volumes_from_container(self):
  61. container_id = 'aabbccddee'
  62. service = Service(
  63. 'test',
  64. image='foo',
  65. volumes_from=[VolumeFromSpec(mock.Mock(id=container_id, spec=Container), 'rw')])
  66. self.assertEqual(service._get_volumes_from(), [container_id + ':rw'])
  67. def test_get_volumes_from_container_read_only(self):
  68. container_id = 'aabbccddee'
  69. service = Service(
  70. 'test',
  71. image='foo',
  72. volumes_from=[VolumeFromSpec(mock.Mock(id=container_id, spec=Container), 'ro')])
  73. self.assertEqual(service._get_volumes_from(), [container_id + ':ro'])
  74. def test_get_volumes_from_service_container_exists(self):
  75. container_ids = ['aabbccddee', '12345']
  76. from_service = mock.create_autospec(Service)
  77. from_service.containers.return_value = [
  78. mock.Mock(id=container_id, spec=Container)
  79. for container_id in container_ids
  80. ]
  81. service = Service('test', volumes_from=[VolumeFromSpec(from_service, 'rw')], image='foo')
  82. self.assertEqual(service._get_volumes_from(), [container_ids[0] + ":rw"])
  83. def test_get_volumes_from_service_container_exists_with_flags(self):
  84. for mode in ['ro', 'rw', 'z', 'rw,z', 'z,rw']:
  85. container_ids = ['aabbccddee:' + mode, '12345:' + mode]
  86. from_service = mock.create_autospec(Service)
  87. from_service.containers.return_value = [
  88. mock.Mock(id=container_id.split(':')[0], spec=Container)
  89. for container_id in container_ids
  90. ]
  91. service = Service('test', volumes_from=[VolumeFromSpec(from_service, mode)], image='foo')
  92. self.assertEqual(service._get_volumes_from(), [container_ids[0]])
  93. def test_get_volumes_from_service_no_container(self):
  94. container_id = 'abababab'
  95. from_service = mock.create_autospec(Service)
  96. from_service.containers.return_value = []
  97. from_service.create_container.return_value = mock.Mock(
  98. id=container_id,
  99. spec=Container)
  100. service = Service('test', image='foo', volumes_from=[VolumeFromSpec(from_service, 'rw')])
  101. self.assertEqual(service._get_volumes_from(), [container_id + ':rw'])
  102. from_service.create_container.assert_called_once_with()
  103. def test_split_domainname_none(self):
  104. service = Service('foo', image='foo', hostname='name', client=self.mock_client)
  105. opts = service._get_container_create_options({'image': 'foo'}, 1)
  106. self.assertEqual(opts['hostname'], 'name', 'hostname')
  107. self.assertFalse('domainname' in opts, 'domainname')
  108. def test_memory_swap_limit(self):
  109. self.mock_client.create_host_config.return_value = {}
  110. service = Service(name='foo', image='foo', hostname='name', client=self.mock_client, mem_limit=1000000000, memswap_limit=2000000000)
  111. service._get_container_create_options({'some': 'overrides'}, 1)
  112. self.assertTrue(self.mock_client.create_host_config.called)
  113. self.assertEqual(
  114. self.mock_client.create_host_config.call_args[1]['mem_limit'],
  115. 1000000000
  116. )
  117. self.assertEqual(
  118. self.mock_client.create_host_config.call_args[1]['memswap_limit'],
  119. 2000000000
  120. )
  121. def test_cgroup_parent(self):
  122. self.mock_client.create_host_config.return_value = {}
  123. service = Service(name='foo', image='foo', hostname='name', client=self.mock_client, cgroup_parent='test')
  124. service._get_container_create_options({'some': 'overrides'}, 1)
  125. self.assertTrue(self.mock_client.create_host_config.called)
  126. self.assertEqual(
  127. self.mock_client.create_host_config.call_args[1]['cgroup_parent'],
  128. 'test'
  129. )
  130. def test_log_opt(self):
  131. self.mock_client.create_host_config.return_value = {}
  132. log_opt = {'syslog-address': 'tcp://192.168.0.42:123'}
  133. service = Service(name='foo', image='foo', hostname='name', client=self.mock_client, log_driver='syslog', log_opt=log_opt)
  134. service._get_container_create_options({'some': 'overrides'}, 1)
  135. self.assertTrue(self.mock_client.create_host_config.called)
  136. self.assertEqual(
  137. self.mock_client.create_host_config.call_args[1]['log_config'],
  138. {'Type': 'syslog', 'Config': {'syslog-address': 'tcp://192.168.0.42:123'}}
  139. )
  140. def test_split_domainname_fqdn(self):
  141. service = Service(
  142. 'foo',
  143. hostname='name.domain.tld',
  144. image='foo',
  145. client=self.mock_client)
  146. opts = service._get_container_create_options({'image': 'foo'}, 1)
  147. self.assertEqual(opts['hostname'], 'name', 'hostname')
  148. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  149. def test_split_domainname_both(self):
  150. service = Service(
  151. 'foo',
  152. hostname='name',
  153. image='foo',
  154. domainname='domain.tld',
  155. client=self.mock_client)
  156. opts = service._get_container_create_options({'image': 'foo'}, 1)
  157. self.assertEqual(opts['hostname'], 'name', 'hostname')
  158. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  159. def test_split_domainname_weird(self):
  160. service = Service(
  161. 'foo',
  162. hostname='name.sub',
  163. domainname='domain.tld',
  164. image='foo',
  165. client=self.mock_client)
  166. opts = service._get_container_create_options({'image': 'foo'}, 1)
  167. self.assertEqual(opts['hostname'], 'name.sub', 'hostname')
  168. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  169. def test_no_default_hostname_when_not_using_networking(self):
  170. service = Service(
  171. 'foo',
  172. image='foo',
  173. use_networking=False,
  174. client=self.mock_client,
  175. )
  176. opts = service._get_container_create_options({'image': 'foo'}, 1)
  177. self.assertIsNone(opts.get('hostname'))
  178. def test_hostname_defaults_to_service_name_when_using_networking(self):
  179. service = Service(
  180. 'foo',
  181. image='foo',
  182. use_networking=True,
  183. client=self.mock_client,
  184. )
  185. opts = service._get_container_create_options({'image': 'foo'}, 1)
  186. self.assertEqual(opts['hostname'], 'foo')
  187. def test_get_container_create_options_with_name_option(self):
  188. service = Service(
  189. 'foo',
  190. image='foo',
  191. client=self.mock_client,
  192. container_name='foo1')
  193. name = 'the_new_name'
  194. opts = service._get_container_create_options(
  195. {'name': name},
  196. 1,
  197. one_off=True)
  198. self.assertEqual(opts['name'], name)
  199. def test_get_container_create_options_does_not_mutate_options(self):
  200. labels = {'thing': 'real'}
  201. environment = {'also': 'real'}
  202. service = Service(
  203. 'foo',
  204. image='foo',
  205. labels=dict(labels),
  206. client=self.mock_client,
  207. environment=dict(environment),
  208. )
  209. self.mock_client.inspect_image.return_value = {'Id': 'abcd'}
  210. prev_container = mock.Mock(
  211. id='ababab',
  212. image_config={'ContainerConfig': {}})
  213. opts = service._get_container_create_options(
  214. {},
  215. 1,
  216. previous_container=prev_container)
  217. self.assertEqual(service.options['labels'], labels)
  218. self.assertEqual(service.options['environment'], environment)
  219. self.assertEqual(
  220. opts['labels'][LABEL_CONFIG_HASH],
  221. '3c85881a8903b9d73a06c41860c8be08acce1494ab4cf8408375966dccd714de')
  222. self.assertEqual(
  223. opts['environment'],
  224. {
  225. 'affinity:container': '=ababab',
  226. 'also': 'real',
  227. }
  228. )
  229. def test_get_container_not_found(self):
  230. self.mock_client.containers.return_value = []
  231. service = Service('foo', client=self.mock_client, image='foo')
  232. self.assertRaises(ValueError, service.get_container)
  233. @mock.patch('compose.service.Container', autospec=True)
  234. def test_get_container(self, mock_container_class):
  235. container_dict = dict(Name='default_foo_2')
  236. self.mock_client.containers.return_value = [container_dict]
  237. service = Service('foo', image='foo', client=self.mock_client)
  238. container = service.get_container(number=2)
  239. self.assertEqual(container, mock_container_class.from_ps.return_value)
  240. mock_container_class.from_ps.assert_called_once_with(
  241. self.mock_client, container_dict)
  242. @mock.patch('compose.service.log', autospec=True)
  243. def test_pull_image(self, mock_log):
  244. service = Service('foo', client=self.mock_client, image='someimage:sometag')
  245. service.pull()
  246. self.mock_client.pull.assert_called_once_with(
  247. 'someimage',
  248. tag='sometag',
  249. stream=True)
  250. mock_log.info.assert_called_once_with('Pulling foo (someimage:sometag)...')
  251. def test_pull_image_no_tag(self):
  252. service = Service('foo', client=self.mock_client, image='ababab')
  253. service.pull()
  254. self.mock_client.pull.assert_called_once_with(
  255. 'ababab',
  256. tag='latest',
  257. stream=True)
  258. @mock.patch('compose.service.log', autospec=True)
  259. def test_pull_image_digest(self, mock_log):
  260. service = Service('foo', client=self.mock_client, image='someimage@sha256:1234')
  261. service.pull()
  262. self.mock_client.pull.assert_called_once_with(
  263. 'someimage',
  264. tag='sha256:1234',
  265. stream=True)
  266. mock_log.info.assert_called_once_with('Pulling foo (someimage@sha256:1234)...')
  267. @mock.patch('compose.service.Container', autospec=True)
  268. def test_recreate_container(self, _):
  269. mock_container = mock.create_autospec(Container)
  270. service = Service('foo', client=self.mock_client, image='someimage')
  271. service.image = lambda: {'Id': 'abc123'}
  272. new_container = service.recreate_container(mock_container)
  273. mock_container.stop.assert_called_once_with(timeout=10)
  274. self.mock_client.rename.assert_called_once_with(
  275. mock_container.id,
  276. '%s_%s' % (mock_container.short_id, mock_container.name))
  277. new_container.start.assert_called_once_with()
  278. mock_container.remove.assert_called_once_with()
  279. @mock.patch('compose.service.Container', autospec=True)
  280. def test_recreate_container_with_timeout(self, _):
  281. mock_container = mock.create_autospec(Container)
  282. self.mock_client.inspect_image.return_value = {'Id': 'abc123'}
  283. service = Service('foo', client=self.mock_client, image='someimage')
  284. service.recreate_container(mock_container, timeout=1)
  285. mock_container.stop.assert_called_once_with(timeout=1)
  286. def test_parse_repository_tag(self):
  287. self.assertEqual(parse_repository_tag("root"), ("root", "", ":"))
  288. self.assertEqual(parse_repository_tag("root:tag"), ("root", "tag", ":"))
  289. self.assertEqual(parse_repository_tag("user/repo"), ("user/repo", "", ":"))
  290. self.assertEqual(parse_repository_tag("user/repo:tag"), ("user/repo", "tag", ":"))
  291. self.assertEqual(parse_repository_tag("url:5000/repo"), ("url:5000/repo", "", ":"))
  292. self.assertEqual(parse_repository_tag("url:5000/repo:tag"), ("url:5000/repo", "tag", ":"))
  293. self.assertEqual(parse_repository_tag("root@sha256:digest"), ("root", "sha256:digest", "@"))
  294. self.assertEqual(parse_repository_tag("user/repo@sha256:digest"), ("user/repo", "sha256:digest", "@"))
  295. self.assertEqual(parse_repository_tag("url:5000/repo@sha256:digest"), ("url:5000/repo", "sha256:digest", "@"))
  296. @mock.patch('compose.service.Container', autospec=True)
  297. def test_create_container_latest_is_used_when_no_tag_specified(self, mock_container):
  298. service = Service('foo', client=self.mock_client, image='someimage')
  299. images = []
  300. def pull(repo, tag=None, **kwargs):
  301. self.assertEqual('someimage', repo)
  302. self.assertEqual('latest', tag)
  303. images.append({'Id': 'abc123'})
  304. return []
  305. service.image = lambda *args, **kwargs: mock_get_image(images)
  306. self.mock_client.pull = pull
  307. service.create_container()
  308. self.assertEqual(1, len(images))
  309. def test_create_container_with_build(self):
  310. service = Service('foo', client=self.mock_client, build='.')
  311. images = []
  312. service.image = lambda *args, **kwargs: mock_get_image(images)
  313. service.build = lambda: images.append({'Id': 'abc123'})
  314. service.create_container(do_build=True)
  315. self.assertEqual(1, len(images))
  316. def test_create_container_no_build(self):
  317. service = Service('foo', client=self.mock_client, build='.')
  318. service.image = lambda: {'Id': 'abc123'}
  319. service.create_container(do_build=False)
  320. self.assertFalse(self.mock_client.build.called)
  321. def test_create_container_no_build_but_needs_build(self):
  322. service = Service('foo', client=self.mock_client, build='.')
  323. service.image = lambda *args, **kwargs: mock_get_image([])
  324. with self.assertRaises(NeedsBuildError):
  325. service.create_container(do_build=False)
  326. def test_build_does_not_pull(self):
  327. self.mock_client.build.return_value = [
  328. b'{"stream": "Successfully built 12345"}',
  329. ]
  330. service = Service('foo', client=self.mock_client, build='.')
  331. service.build()
  332. self.assertEqual(self.mock_client.build.call_count, 1)
  333. self.assertFalse(self.mock_client.build.call_args[1]['pull'])
  334. def test_config_dict(self):
  335. self.mock_client.inspect_image.return_value = {'Id': 'abcd'}
  336. service = Service(
  337. 'foo',
  338. image='example.com/foo',
  339. client=self.mock_client,
  340. net=ServiceNet(Service('other')),
  341. links=[(Service('one'), 'one')],
  342. volumes_from=[VolumeFromSpec(Service('two'), 'rw')])
  343. config_dict = service.config_dict()
  344. expected = {
  345. 'image_id': 'abcd',
  346. 'options': {'image': 'example.com/foo'},
  347. 'links': [('one', 'one')],
  348. 'net': 'other',
  349. 'volumes_from': ['two'],
  350. }
  351. self.assertEqual(config_dict, expected)
  352. def test_config_dict_with_net_from_container(self):
  353. self.mock_client.inspect_image.return_value = {'Id': 'abcd'}
  354. container = Container(
  355. self.mock_client,
  356. {'Id': 'aaabbb', 'Name': '/foo_1'})
  357. service = Service(
  358. 'foo',
  359. image='example.com/foo',
  360. client=self.mock_client,
  361. net=container)
  362. config_dict = service.config_dict()
  363. expected = {
  364. 'image_id': 'abcd',
  365. 'options': {'image': 'example.com/foo'},
  366. 'links': [],
  367. 'net': 'aaabbb',
  368. 'volumes_from': [],
  369. }
  370. self.assertEqual(config_dict, expected)
  371. def test_specifies_host_port_with_no_ports(self):
  372. service = Service(
  373. 'foo',
  374. image='foo')
  375. self.assertEqual(service.specifies_host_port(), False)
  376. def test_specifies_host_port_with_container_port(self):
  377. service = Service(
  378. 'foo',
  379. image='foo',
  380. ports=["2000"])
  381. self.assertEqual(service.specifies_host_port(), False)
  382. def test_specifies_host_port_with_host_port(self):
  383. service = Service(
  384. 'foo',
  385. image='foo',
  386. ports=["1000:2000"])
  387. self.assertEqual(service.specifies_host_port(), True)
  388. def test_specifies_host_port_with_host_ip_no_port(self):
  389. service = Service(
  390. 'foo',
  391. image='foo',
  392. ports=["127.0.0.1::2000"])
  393. self.assertEqual(service.specifies_host_port(), False)
  394. def test_specifies_host_port_with_host_ip_and_port(self):
  395. service = Service(
  396. 'foo',
  397. image='foo',
  398. ports=["127.0.0.1:1000:2000"])
  399. self.assertEqual(service.specifies_host_port(), True)
  400. def test_specifies_host_port_with_container_port_range(self):
  401. service = Service(
  402. 'foo',
  403. image='foo',
  404. ports=["2000-3000"])
  405. self.assertEqual(service.specifies_host_port(), False)
  406. def test_specifies_host_port_with_host_port_range(self):
  407. service = Service(
  408. 'foo',
  409. image='foo',
  410. ports=["1000-2000:2000-3000"])
  411. self.assertEqual(service.specifies_host_port(), True)
  412. def test_specifies_host_port_with_host_ip_no_port_range(self):
  413. service = Service(
  414. 'foo',
  415. image='foo',
  416. ports=["127.0.0.1::2000-3000"])
  417. self.assertEqual(service.specifies_host_port(), False)
  418. def test_specifies_host_port_with_host_ip_and_port_range(self):
  419. service = Service(
  420. 'foo',
  421. image='foo',
  422. ports=["127.0.0.1:1000-2000:2000-3000"])
  423. self.assertEqual(service.specifies_host_port(), True)
  424. class NetTestCase(unittest.TestCase):
  425. def test_net(self):
  426. net = Net('host')
  427. self.assertEqual(net.id, 'host')
  428. self.assertEqual(net.mode, 'host')
  429. self.assertEqual(net.service_name, None)
  430. def test_net_container(self):
  431. container_id = 'abcd'
  432. net = ContainerNet(Container(None, {'Id': container_id}))
  433. self.assertEqual(net.id, container_id)
  434. self.assertEqual(net.mode, 'container:' + container_id)
  435. self.assertEqual(net.service_name, None)
  436. def test_net_service(self):
  437. container_id = 'bbbb'
  438. service_name = 'web'
  439. mock_client = mock.create_autospec(docker.Client)
  440. mock_client.containers.return_value = [
  441. {'Id': container_id, 'Name': container_id, 'Image': 'abcd'},
  442. ]
  443. service = Service(name=service_name, client=mock_client)
  444. net = ServiceNet(service)
  445. self.assertEqual(net.id, service_name)
  446. self.assertEqual(net.mode, 'container:' + container_id)
  447. self.assertEqual(net.service_name, service_name)
  448. def test_net_service_no_containers(self):
  449. service_name = 'web'
  450. mock_client = mock.create_autospec(docker.Client)
  451. mock_client.containers.return_value = []
  452. service = Service(name=service_name, client=mock_client)
  453. net = ServiceNet(service)
  454. self.assertEqual(net.id, service_name)
  455. self.assertEqual(net.mode, None)
  456. self.assertEqual(net.service_name, service_name)
  457. def mock_get_image(images):
  458. if images:
  459. return images[0]
  460. else:
  461. raise NoSuchImageError()
  462. class ServiceVolumesTest(unittest.TestCase):
  463. def setUp(self):
  464. self.mock_client = mock.create_autospec(docker.Client)
  465. def test_parse_volume_spec_only_one_path(self):
  466. spec = parse_volume_spec('/the/volume')
  467. self.assertEqual(spec, (None, '/the/volume', 'rw'))
  468. def test_parse_volume_spec_internal_and_external(self):
  469. spec = parse_volume_spec('external:interval')
  470. self.assertEqual(spec, ('external', 'interval', 'rw'))
  471. def test_parse_volume_spec_with_mode(self):
  472. spec = parse_volume_spec('external:interval:ro')
  473. self.assertEqual(spec, ('external', 'interval', 'ro'))
  474. spec = parse_volume_spec('external:interval:z')
  475. self.assertEqual(spec, ('external', 'interval', 'z'))
  476. def test_parse_volume_spec_too_many_parts(self):
  477. with self.assertRaises(ConfigError):
  478. parse_volume_spec('one:two:three:four')
  479. @pytest.mark.xfail((not IS_WINDOWS_PLATFORM), reason='does not have a drive')
  480. def test_parse_volume_windows_absolute_path(self):
  481. windows_absolute_path = "c:\\Users\\me\\Documents\\shiny\\config:\\opt\\shiny\\config:ro"
  482. spec = parse_volume_spec(windows_absolute_path)
  483. self.assertEqual(
  484. spec,
  485. (
  486. "/c/Users/me/Documents/shiny/config",
  487. "/opt/shiny/config",
  488. "ro"
  489. )
  490. )
  491. def test_build_volume_binding(self):
  492. binding = build_volume_binding(parse_volume_spec('/outside:/inside'))
  493. self.assertEqual(binding, ('/inside', '/outside:/inside:rw'))
  494. def test_get_container_data_volumes(self):
  495. options = [
  496. '/host/volume:/host/volume:ro',
  497. '/new/volume',
  498. '/existing/volume',
  499. ]
  500. self.mock_client.inspect_image.return_value = {
  501. 'ContainerConfig': {
  502. 'Volumes': {
  503. '/mnt/image/data': {},
  504. }
  505. }
  506. }
  507. container = Container(self.mock_client, {
  508. 'Image': 'ababab',
  509. 'Volumes': {
  510. '/host/volume': '/host/volume',
  511. '/existing/volume': '/var/lib/docker/aaaaaaaa',
  512. '/removed/volume': '/var/lib/docker/bbbbbbbb',
  513. '/mnt/image/data': '/var/lib/docker/cccccccc',
  514. },
  515. }, has_been_inspected=True)
  516. expected = {
  517. '/existing/volume': '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  518. '/mnt/image/data': '/var/lib/docker/cccccccc:/mnt/image/data:rw',
  519. }
  520. binds = get_container_data_volumes(container, options)
  521. self.assertEqual(binds, expected)
  522. def test_merge_volume_bindings(self):
  523. options = [
  524. '/host/volume:/host/volume:ro',
  525. '/host/rw/volume:/host/rw/volume',
  526. '/new/volume',
  527. '/existing/volume',
  528. ]
  529. self.mock_client.inspect_image.return_value = {
  530. 'ContainerConfig': {'Volumes': {}}
  531. }
  532. intermediate_container = Container(self.mock_client, {
  533. 'Image': 'ababab',
  534. 'Volumes': {'/existing/volume': '/var/lib/docker/aaaaaaaa'},
  535. }, has_been_inspected=True)
  536. expected = [
  537. '/host/volume:/host/volume:ro',
  538. '/host/rw/volume:/host/rw/volume:rw',
  539. '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  540. ]
  541. binds = merge_volume_bindings(options, intermediate_container)
  542. self.assertEqual(set(binds), set(expected))
  543. def test_mount_same_host_path_to_two_volumes(self):
  544. service = Service(
  545. 'web',
  546. image='busybox',
  547. volumes=[
  548. '/host/path:/data1',
  549. '/host/path:/data2',
  550. ],
  551. client=self.mock_client,
  552. )
  553. self.mock_client.inspect_image.return_value = {
  554. 'Id': 'ababab',
  555. 'ContainerConfig': {
  556. 'Volumes': {}
  557. }
  558. }
  559. service._get_container_create_options(
  560. override_options={},
  561. number=1,
  562. )
  563. self.assertEqual(
  564. set(self.mock_client.create_host_config.call_args[1]['binds']),
  565. set([
  566. '/host/path:/data1:rw',
  567. '/host/path:/data2:rw',
  568. ]),
  569. )
  570. def test_different_host_path_in_container_json(self):
  571. service = Service(
  572. 'web',
  573. image='busybox',
  574. volumes=['/host/path:/data'],
  575. client=self.mock_client,
  576. )
  577. self.mock_client.inspect_image.return_value = {
  578. 'Id': 'ababab',
  579. 'ContainerConfig': {
  580. 'Volumes': {
  581. '/data': {},
  582. }
  583. }
  584. }
  585. self.mock_client.inspect_container.return_value = {
  586. 'Id': '123123123',
  587. 'Image': 'ababab',
  588. 'Volumes': {
  589. '/data': '/mnt/sda1/host/path',
  590. },
  591. }
  592. service._get_container_create_options(
  593. override_options={},
  594. number=1,
  595. previous_container=Container(self.mock_client, {'Id': '123123123'}),
  596. )
  597. self.assertEqual(
  598. self.mock_client.create_host_config.call_args[1]['binds'],
  599. ['/mnt/sda1/host/path:/data:rw'],
  600. )
  601. def test_create_with_special_volume_mode(self):
  602. self.mock_client.inspect_image.return_value = {'Id': 'imageid'}
  603. create_calls = []
  604. def create_container(*args, **kwargs):
  605. create_calls.append((args, kwargs))
  606. return {'Id': 'containerid'}
  607. self.mock_client.create_container = create_container
  608. volumes = ['/tmp:/foo:z']
  609. Service(
  610. 'web',
  611. client=self.mock_client,
  612. image='busybox',
  613. volumes=volumes,
  614. ).create_container()
  615. self.assertEqual(len(create_calls), 1)
  616. self.assertEqual(self.mock_client.create_host_config.call_args[1]['binds'], volumes)