service_test.py 22 KB

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