service_test.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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='', image='foo'))
  25. self.assertRaises(ConfigError, lambda: Service(name=' ', image='foo'))
  26. self.assertRaises(ConfigError, lambda: Service(name='/', image='foo'))
  27. self.assertRaises(ConfigError, lambda: Service(name='!', image='foo'))
  28. self.assertRaises(ConfigError, lambda: Service(name='\xe2', image='foo'))
  29. self.assertRaises(ConfigError, lambda: Service(name='_', image='foo'))
  30. self.assertRaises(ConfigError, lambda: Service(name='____', image='foo'))
  31. self.assertRaises(ConfigError, lambda: Service(name='foo_bar', image='foo'))
  32. self.assertRaises(ConfigError, lambda: Service(name='__foo_bar__', image='foo'))
  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(timeout=10)
  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. @mock.patch('compose.service.Container', autospec=True)
  211. def test_recreate_container_with_timeout(self, _):
  212. mock_container = mock.create_autospec(Container)
  213. self.mock_client.inspect_image.return_value = {'Id': 'abc123'}
  214. service = Service('foo', client=self.mock_client, image='someimage')
  215. service.recreate_container(mock_container, timeout=1)
  216. mock_container.stop.assert_called_once_with(timeout=1)
  217. def test_parse_repository_tag(self):
  218. self.assertEqual(parse_repository_tag("root"), ("root", ""))
  219. self.assertEqual(parse_repository_tag("root:tag"), ("root", "tag"))
  220. self.assertEqual(parse_repository_tag("user/repo"), ("user/repo", ""))
  221. self.assertEqual(parse_repository_tag("user/repo:tag"), ("user/repo", "tag"))
  222. self.assertEqual(parse_repository_tag("url:5000/repo"), ("url:5000/repo", ""))
  223. self.assertEqual(parse_repository_tag("url:5000/repo:tag"), ("url:5000/repo", "tag"))
  224. @mock.patch('compose.service.Container', autospec=True)
  225. def test_create_container_latest_is_used_when_no_tag_specified(self, mock_container):
  226. service = Service('foo', client=self.mock_client, image='someimage')
  227. images = []
  228. def pull(repo, tag=None, **kwargs):
  229. self.assertEqual('someimage', repo)
  230. self.assertEqual('latest', tag)
  231. images.append({'Id': 'abc123'})
  232. return []
  233. service.image = lambda: images[0] if images else None
  234. self.mock_client.pull = pull
  235. service.create_container()
  236. self.assertEqual(1, len(images))
  237. def test_create_container_with_build(self):
  238. service = Service('foo', client=self.mock_client, build='.')
  239. images = []
  240. service.image = lambda *args, **kwargs: images[0] if images else None
  241. service.build = lambda: images.append({'Id': 'abc123'})
  242. service.create_container(do_build=True)
  243. self.assertEqual(1, len(images))
  244. def test_create_container_no_build(self):
  245. service = Service('foo', client=self.mock_client, build='.')
  246. service.image = lambda: {'Id': 'abc123'}
  247. service.create_container(do_build=False)
  248. self.assertFalse(self.mock_client.build.called)
  249. def test_create_container_no_build_but_needs_build(self):
  250. service = Service('foo', client=self.mock_client, build='.')
  251. service.image = lambda: None
  252. with self.assertRaises(NeedsBuildError):
  253. service.create_container(do_build=False)
  254. def test_build_does_not_pull(self):
  255. self.mock_client.build.return_value = [
  256. '{"stream": "Successfully built 12345"}',
  257. ]
  258. service = Service('foo', client=self.mock_client, build='.')
  259. service.build()
  260. self.assertEqual(self.mock_client.build.call_count, 1)
  261. self.assertFalse(self.mock_client.build.call_args[1]['pull'])
  262. class ServiceVolumesTest(unittest.TestCase):
  263. def setUp(self):
  264. self.mock_client = mock.create_autospec(docker.Client)
  265. def test_parse_volume_spec_only_one_path(self):
  266. spec = parse_volume_spec('/the/volume')
  267. self.assertEqual(spec, (None, '/the/volume', 'rw'))
  268. def test_parse_volume_spec_internal_and_external(self):
  269. spec = parse_volume_spec('external:interval')
  270. self.assertEqual(spec, ('external', 'interval', 'rw'))
  271. def test_parse_volume_spec_with_mode(self):
  272. spec = parse_volume_spec('external:interval:ro')
  273. self.assertEqual(spec, ('external', 'interval', 'ro'))
  274. def test_parse_volume_spec_too_many_parts(self):
  275. with self.assertRaises(ConfigError):
  276. parse_volume_spec('one:two:three:four')
  277. def test_parse_volume_bad_mode(self):
  278. with self.assertRaises(ConfigError):
  279. parse_volume_spec('one:two:notrw')
  280. def test_build_volume_binding(self):
  281. binding = build_volume_binding(parse_volume_spec('/outside:/inside'))
  282. self.assertEqual(binding, ('/inside', '/outside:/inside:rw'))
  283. def test_get_container_data_volumes(self):
  284. options = [
  285. '/host/volume:/host/volume:ro',
  286. '/new/volume',
  287. '/existing/volume',
  288. ]
  289. self.mock_client.inspect_image.return_value = {
  290. 'ContainerConfig': {
  291. 'Volumes': {
  292. '/mnt/image/data': {},
  293. }
  294. }
  295. }
  296. container = Container(self.mock_client, {
  297. 'Image': 'ababab',
  298. 'Volumes': {
  299. '/host/volume': '/host/volume',
  300. '/existing/volume': '/var/lib/docker/aaaaaaaa',
  301. '/removed/volume': '/var/lib/docker/bbbbbbbb',
  302. '/mnt/image/data': '/var/lib/docker/cccccccc',
  303. },
  304. }, has_been_inspected=True)
  305. expected = {
  306. '/existing/volume': '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  307. '/mnt/image/data': '/var/lib/docker/cccccccc:/mnt/image/data:rw',
  308. }
  309. binds = get_container_data_volumes(container, options)
  310. self.assertEqual(binds, expected)
  311. def test_merge_volume_bindings(self):
  312. options = [
  313. '/host/volume:/host/volume:ro',
  314. '/host/rw/volume:/host/rw/volume',
  315. '/new/volume',
  316. '/existing/volume',
  317. ]
  318. self.mock_client.inspect_image.return_value = {
  319. 'ContainerConfig': {'Volumes': {}}
  320. }
  321. intermediate_container = Container(self.mock_client, {
  322. 'Image': 'ababab',
  323. 'Volumes': {'/existing/volume': '/var/lib/docker/aaaaaaaa'},
  324. }, has_been_inspected=True)
  325. expected = [
  326. '/host/volume:/host/volume:ro',
  327. '/host/rw/volume:/host/rw/volume:rw',
  328. '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  329. ]
  330. binds = merge_volume_bindings(options, intermediate_container)
  331. self.assertEqual(set(binds), set(expected))
  332. def test_mount_same_host_path_to_two_volumes(self):
  333. service = Service(
  334. 'web',
  335. image='busybox',
  336. volumes=[
  337. '/host/path:/data1',
  338. '/host/path:/data2',
  339. ],
  340. client=self.mock_client,
  341. )
  342. self.mock_client.inspect_image.return_value = {
  343. 'Id': 'ababab',
  344. 'ContainerConfig': {
  345. 'Volumes': {}
  346. }
  347. }
  348. create_options = service._get_container_create_options(
  349. override_options={},
  350. number=1,
  351. )
  352. self.assertEqual(
  353. set(create_options['host_config']['Binds']),
  354. set([
  355. '/host/path:/data1:rw',
  356. '/host/path:/data2:rw',
  357. ]),
  358. )
  359. def test_different_host_path_in_container_json(self):
  360. service = Service(
  361. 'web',
  362. image='busybox',
  363. volumes=['/host/path:/data'],
  364. client=self.mock_client,
  365. )
  366. self.mock_client.inspect_image.return_value = {
  367. 'Id': 'ababab',
  368. 'ContainerConfig': {
  369. 'Volumes': {
  370. '/data': {},
  371. }
  372. }
  373. }
  374. self.mock_client.inspect_container.return_value = {
  375. 'Id': '123123123',
  376. 'Image': 'ababab',
  377. 'Volumes': {
  378. '/data': '/mnt/sda1/host/path',
  379. },
  380. }
  381. create_options = service._get_container_create_options(
  382. override_options={},
  383. number=1,
  384. previous_container=Container(self.mock_client, {'Id': '123123123'}),
  385. )
  386. self.assertEqual(
  387. create_options['host_config']['Binds'],
  388. ['/mnt/sda1/host/path:/data:rw'],
  389. )