service_test.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from .. import unittest
  4. import mock
  5. import docker
  6. from compose.service import Service
  7. from compose.container import Container
  8. from compose.const import LABEL_SERVICE, LABEL_PROJECT, LABEL_ONE_OFF
  9. from compose.service import (
  10. ConfigError,
  11. NeedsBuildError,
  12. build_port_bindings,
  13. build_volume_binding,
  14. get_container_data_volumes,
  15. merge_volume_bindings,
  16. parse_repository_tag,
  17. parse_volume_spec,
  18. split_port,
  19. )
  20. class ServiceTest(unittest.TestCase):
  21. def setUp(self):
  22. self.mock_client = mock.create_autospec(docker.Client)
  23. def test_name_validations(self):
  24. self.assertRaises(ConfigError, lambda: Service(name=''))
  25. self.assertRaises(ConfigError, lambda: Service(name=' '))
  26. self.assertRaises(ConfigError, lambda: Service(name='/'))
  27. self.assertRaises(ConfigError, lambda: Service(name='!'))
  28. self.assertRaises(ConfigError, lambda: Service(name='\xe2'))
  29. self.assertRaises(ConfigError, lambda: Service(name='_'))
  30. self.assertRaises(ConfigError, lambda: Service(name='____'))
  31. self.assertRaises(ConfigError, lambda: Service(name='foo_bar'))
  32. self.assertRaises(ConfigError, lambda: Service(name='__foo_bar__'))
  33. Service('a', image='foo')
  34. Service('foo', image='foo')
  35. def test_project_validation(self):
  36. self.assertRaises(ConfigError, lambda: Service('bar'))
  37. self.assertRaises(ConfigError, lambda: Service(name='foo', project='_', image='foo'))
  38. Service(name='foo', project='bar', image='foo')
  39. def test_containers(self):
  40. service = Service('db', self.mock_client, 'myproject', image='foo')
  41. self.mock_client.containers.return_value = []
  42. self.assertEqual(service.containers(), [])
  43. def test_containers_with_containers(self):
  44. self.mock_client.containers.return_value = [
  45. dict(Name=str(i), Image='foo', Id=i) for i in range(3)
  46. ]
  47. service = Service('db', self.mock_client, 'myproject', image='foo')
  48. self.assertEqual([c.id for c in service.containers()], range(3))
  49. expected_labels = [
  50. '{0}=myproject'.format(LABEL_PROJECT),
  51. '{0}=db'.format(LABEL_SERVICE),
  52. '{0}=False'.format(LABEL_ONE_OFF),
  53. ]
  54. self.mock_client.containers.assert_called_once_with(
  55. all=False,
  56. filters={'label': expected_labels})
  57. def test_get_volumes_from_container(self):
  58. container_id = 'aabbccddee'
  59. service = Service(
  60. 'test',
  61. image='foo',
  62. volumes_from=[mock.Mock(id=container_id, spec=Container)])
  63. self.assertEqual(service._get_volumes_from(), [container_id])
  64. def test_get_volumes_from_service_container_exists(self):
  65. container_ids = ['aabbccddee', '12345']
  66. from_service = mock.create_autospec(Service)
  67. from_service.containers.return_value = [
  68. mock.Mock(id=container_id, spec=Container)
  69. for container_id in container_ids
  70. ]
  71. service = Service('test', volumes_from=[from_service], image='foo')
  72. self.assertEqual(service._get_volumes_from(), container_ids)
  73. def test_get_volumes_from_service_no_container(self):
  74. container_id = 'abababab'
  75. from_service = mock.create_autospec(Service)
  76. from_service.containers.return_value = []
  77. from_service.create_container.return_value = mock.Mock(
  78. id=container_id,
  79. spec=Container)
  80. service = Service('test', image='foo', volumes_from=[from_service])
  81. self.assertEqual(service._get_volumes_from(), [container_id])
  82. from_service.create_container.assert_called_once_with()
  83. def test_split_port_with_host_ip(self):
  84. internal_port, external_port = split_port("127.0.0.1:1000:2000")
  85. self.assertEqual(internal_port, "2000")
  86. self.assertEqual(external_port, ("127.0.0.1", "1000"))
  87. def test_split_port_with_protocol(self):
  88. internal_port, external_port = split_port("127.0.0.1:1000:2000/udp")
  89. self.assertEqual(internal_port, "2000/udp")
  90. self.assertEqual(external_port, ("127.0.0.1", "1000"))
  91. def test_split_port_with_host_ip_no_port(self):
  92. internal_port, external_port = split_port("127.0.0.1::2000")
  93. self.assertEqual(internal_port, "2000")
  94. self.assertEqual(external_port, ("127.0.0.1", None))
  95. def test_split_port_with_host_port(self):
  96. internal_port, external_port = split_port("1000:2000")
  97. self.assertEqual(internal_port, "2000")
  98. self.assertEqual(external_port, "1000")
  99. def test_split_port_no_host_port(self):
  100. internal_port, external_port = split_port("2000")
  101. self.assertEqual(internal_port, "2000")
  102. self.assertEqual(external_port, None)
  103. def test_split_port_invalid(self):
  104. with self.assertRaises(ConfigError):
  105. split_port("0.0.0.0:1000:2000:tcp")
  106. def test_build_port_bindings_with_one_port(self):
  107. port_bindings = build_port_bindings(["127.0.0.1:1000:1000"])
  108. self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")])
  109. def test_build_port_bindings_with_matching_internal_ports(self):
  110. port_bindings = build_port_bindings(["127.0.0.1:1000:1000", "127.0.0.1:2000:1000"])
  111. self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000"), ("127.0.0.1", "2000")])
  112. def test_build_port_bindings_with_nonmatching_internal_ports(self):
  113. port_bindings = build_port_bindings(["127.0.0.1:1000:1000", "127.0.0.1:2000:2000"])
  114. self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")])
  115. self.assertEqual(port_bindings["2000"], [("127.0.0.1", "2000")])
  116. def test_split_domainname_none(self):
  117. service = Service('foo', image='foo', hostname='name', client=self.mock_client)
  118. self.mock_client.containers.return_value = []
  119. opts = service._get_container_create_options({'image': 'foo'}, 1)
  120. self.assertEqual(opts['hostname'], 'name', 'hostname')
  121. self.assertFalse('domainname' in opts, 'domainname')
  122. def test_split_domainname_fqdn(self):
  123. service = Service(
  124. 'foo',
  125. hostname='name.domain.tld',
  126. image='foo',
  127. client=self.mock_client)
  128. self.mock_client.containers.return_value = []
  129. opts = service._get_container_create_options({'image': 'foo'}, 1)
  130. self.assertEqual(opts['hostname'], 'name', 'hostname')
  131. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  132. def test_split_domainname_both(self):
  133. service = Service(
  134. 'foo',
  135. hostname='name',
  136. image='foo',
  137. domainname='domain.tld',
  138. client=self.mock_client)
  139. self.mock_client.containers.return_value = []
  140. opts = service._get_container_create_options({'image': 'foo'}, 1)
  141. self.assertEqual(opts['hostname'], 'name', 'hostname')
  142. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  143. def test_split_domainname_weird(self):
  144. service = Service(
  145. 'foo',
  146. hostname='name.sub',
  147. domainname='domain.tld',
  148. image='foo',
  149. client=self.mock_client)
  150. self.mock_client.containers.return_value = []
  151. opts = service._get_container_create_options({'image': 'foo'}, 1)
  152. self.assertEqual(opts['hostname'], 'name.sub', 'hostname')
  153. self.assertEqual(opts['domainname'], 'domain.tld', 'domainname')
  154. def test_get_container_not_found(self):
  155. self.mock_client.containers.return_value = []
  156. service = Service('foo', client=self.mock_client, image='foo')
  157. self.assertRaises(ValueError, service.get_container)
  158. @mock.patch('compose.service.Container', autospec=True)
  159. def test_get_container(self, mock_container_class):
  160. container_dict = dict(Name='default_foo_2')
  161. self.mock_client.containers.return_value = [container_dict]
  162. service = Service('foo', image='foo', client=self.mock_client)
  163. container = service.get_container(number=2)
  164. self.assertEqual(container, mock_container_class.from_ps.return_value)
  165. mock_container_class.from_ps.assert_called_once_with(
  166. self.mock_client, container_dict)
  167. @mock.patch('compose.service.log', autospec=True)
  168. def test_pull_image(self, mock_log):
  169. service = Service('foo', client=self.mock_client, image='someimage:sometag')
  170. service.pull(insecure_registry=True)
  171. self.mock_client.pull.assert_called_once_with(
  172. 'someimage',
  173. tag='sometag',
  174. insecure_registry=True,
  175. stream=True)
  176. mock_log.info.assert_called_once_with('Pulling foo (someimage:sometag)...')
  177. def test_pull_image_no_tag(self):
  178. service = Service('foo', client=self.mock_client, image='ababab')
  179. service.pull()
  180. self.mock_client.pull.assert_called_once_with(
  181. 'ababab',
  182. tag='latest',
  183. insecure_registry=False,
  184. stream=True)
  185. def test_create_container_from_insecure_registry(self):
  186. service = Service('foo', client=self.mock_client, image='someimage:sometag')
  187. images = []
  188. def pull(repo, tag=None, insecure_registry=False, **kwargs):
  189. self.assertEqual('someimage', repo)
  190. self.assertEqual('sometag', tag)
  191. self.assertTrue(insecure_registry)
  192. images.append({'Id': 'abc123'})
  193. return []
  194. service.image = lambda: images[0] if images else None
  195. self.mock_client.pull = pull
  196. service.create_container(insecure_registry=True)
  197. self.assertEqual(1, len(images))
  198. @mock.patch('compose.service.Container', autospec=True)
  199. def test_recreate_container(self, _):
  200. mock_container = mock.create_autospec(Container)
  201. service = Service('foo', client=self.mock_client, image='someimage')
  202. service.image = lambda: {'Id': 'abc123'}
  203. new_container = service.recreate_container(mock_container)
  204. mock_container.stop.assert_called_once_with()
  205. self.mock_client.rename.assert_called_once_with(
  206. mock_container.id,
  207. '%s_%s' % (mock_container.short_id, mock_container.name))
  208. new_container.start.assert_called_once_with()
  209. mock_container.remove.assert_called_once_with()
  210. def test_parse_repository_tag(self):
  211. self.assertEqual(parse_repository_tag("root"), ("root", ""))
  212. self.assertEqual(parse_repository_tag("root:tag"), ("root", "tag"))
  213. self.assertEqual(parse_repository_tag("user/repo"), ("user/repo", ""))
  214. self.assertEqual(parse_repository_tag("user/repo:tag"), ("user/repo", "tag"))
  215. self.assertEqual(parse_repository_tag("url:5000/repo"), ("url:5000/repo", ""))
  216. self.assertEqual(parse_repository_tag("url:5000/repo:tag"), ("url:5000/repo", "tag"))
  217. @mock.patch('compose.service.Container', autospec=True)
  218. def test_create_container_latest_is_used_when_no_tag_specified(self, mock_container):
  219. service = Service('foo', client=self.mock_client, image='someimage')
  220. images = []
  221. def pull(repo, tag=None, **kwargs):
  222. self.assertEqual('someimage', repo)
  223. self.assertEqual('latest', tag)
  224. images.append({'Id': 'abc123'})
  225. return []
  226. service.image = lambda: images[0] if images else None
  227. self.mock_client.pull = pull
  228. service.create_container()
  229. self.assertEqual(1, len(images))
  230. def test_create_container_with_build(self):
  231. service = Service('foo', client=self.mock_client, build='.')
  232. images = []
  233. service.image = lambda *args, **kwargs: images[0] if images else None
  234. service.build = lambda: images.append({'Id': 'abc123'})
  235. service.create_container(do_build=True)
  236. self.assertEqual(1, len(images))
  237. def test_create_container_no_build(self):
  238. service = Service('foo', client=self.mock_client, build='.')
  239. service.image = lambda: {'Id': 'abc123'}
  240. service.create_container(do_build=False)
  241. self.assertFalse(self.mock_client.build.called)
  242. def test_create_container_no_build_but_needs_build(self):
  243. service = Service('foo', client=self.mock_client, build='.')
  244. service.image = lambda: None
  245. with self.assertRaises(NeedsBuildError):
  246. service.create_container(do_build=False)
  247. def test_build_does_not_pull(self):
  248. self.mock_client.build.return_value = [
  249. '{"stream": "Successfully built 12345"}',
  250. ]
  251. service = Service('foo', client=self.mock_client, build='.')
  252. service.build()
  253. self.assertEqual(self.mock_client.build.call_count, 1)
  254. self.assertFalse(self.mock_client.build.call_args[1]['pull'])
  255. class ServiceVolumesTest(unittest.TestCase):
  256. def setUp(self):
  257. self.mock_client = mock.create_autospec(docker.Client)
  258. def test_parse_volume_spec_only_one_path(self):
  259. spec = parse_volume_spec('/the/volume')
  260. self.assertEqual(spec, (None, '/the/volume', 'rw'))
  261. def test_parse_volume_spec_internal_and_external(self):
  262. spec = parse_volume_spec('external:interval')
  263. self.assertEqual(spec, ('external', 'interval', 'rw'))
  264. def test_parse_volume_spec_with_mode(self):
  265. spec = parse_volume_spec('external:interval:ro')
  266. self.assertEqual(spec, ('external', 'interval', 'ro'))
  267. def test_parse_volume_spec_too_many_parts(self):
  268. with self.assertRaises(ConfigError):
  269. parse_volume_spec('one:two:three:four')
  270. def test_parse_volume_bad_mode(self):
  271. with self.assertRaises(ConfigError):
  272. parse_volume_spec('one:two:notrw')
  273. def test_build_volume_binding(self):
  274. binding = build_volume_binding(parse_volume_spec('/outside:/inside'))
  275. self.assertEqual(binding, ('/inside', '/outside:/inside:rw'))
  276. def test_get_container_data_volumes(self):
  277. options = [
  278. '/host/volume:/host/volume:ro',
  279. '/new/volume',
  280. '/existing/volume',
  281. ]
  282. self.mock_client.inspect_image.return_value = {
  283. 'ContainerConfig': {
  284. 'Volumes': {
  285. '/mnt/image/data': {},
  286. }
  287. }
  288. }
  289. container = Container(self.mock_client, {
  290. 'Image': 'ababab',
  291. 'Volumes': {
  292. '/host/volume': '/host/volume',
  293. '/existing/volume': '/var/lib/docker/aaaaaaaa',
  294. '/removed/volume': '/var/lib/docker/bbbbbbbb',
  295. '/mnt/image/data': '/var/lib/docker/cccccccc',
  296. },
  297. }, has_been_inspected=True)
  298. expected = {
  299. '/existing/volume': '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  300. '/mnt/image/data': '/var/lib/docker/cccccccc:/mnt/image/data:rw',
  301. }
  302. binds = get_container_data_volumes(container, options)
  303. self.assertEqual(binds, expected)
  304. def test_merge_volume_bindings(self):
  305. options = [
  306. '/host/volume:/host/volume:ro',
  307. '/host/rw/volume:/host/rw/volume',
  308. '/new/volume',
  309. '/existing/volume',
  310. ]
  311. self.mock_client.inspect_image.return_value = {
  312. 'ContainerConfig': {'Volumes': {}}
  313. }
  314. intermediate_container = Container(self.mock_client, {
  315. 'Image': 'ababab',
  316. 'Volumes': {'/existing/volume': '/var/lib/docker/aaaaaaaa'},
  317. }, has_been_inspected=True)
  318. expected = [
  319. '/host/volume:/host/volume:ro',
  320. '/host/rw/volume:/host/rw/volume:rw',
  321. '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  322. ]
  323. binds = merge_volume_bindings(options, intermediate_container)
  324. self.assertEqual(set(binds), set(expected))
  325. def test_mount_same_host_path_to_two_volumes(self):
  326. service = Service(
  327. 'web',
  328. image='busybox',
  329. volumes=[
  330. '/host/path:/data1',
  331. '/host/path:/data2',
  332. ],
  333. client=self.mock_client,
  334. )
  335. self.mock_client.inspect_image.return_value = {
  336. 'Id': 'ababab',
  337. 'ContainerConfig': {
  338. 'Volumes': {}
  339. }
  340. }
  341. create_options = service._get_container_create_options(
  342. override_options={},
  343. number=1,
  344. )
  345. self.assertEqual(
  346. set(create_options['host_config']['Binds']),
  347. set([
  348. '/host/path:/data1:rw',
  349. '/host/path:/data2:rw',
  350. ]),
  351. )
  352. def test_different_host_path_in_container_json(self):
  353. service = Service(
  354. 'web',
  355. image='busybox',
  356. volumes=['/host/path:/data'],
  357. client=self.mock_client,
  358. )
  359. self.mock_client.inspect_image.return_value = {
  360. 'Id': 'ababab',
  361. 'ContainerConfig': {
  362. 'Volumes': {
  363. '/data': {},
  364. }
  365. }
  366. }
  367. self.mock_client.inspect_container.return_value = {
  368. 'Id': '123123123',
  369. 'Image': 'ababab',
  370. 'Volumes': {
  371. '/data': '/mnt/sda1/host/path',
  372. },
  373. }
  374. create_options = service._get_container_create_options(
  375. override_options={},
  376. number=1,
  377. previous_container=Container(self.mock_client, {'Id': '123123123'}),
  378. )
  379. self.assertEqual(
  380. create_options['host_config']['Binds'],
  381. ['/mnt/sda1/host/path:/data:rw'],
  382. )