service_test.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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(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. class ServiceVolumesTest(unittest.TestCase):
  255. def setUp(self):
  256. self.mock_client = mock.create_autospec(docker.Client)
  257. def test_parse_volume_spec_only_one_path(self):
  258. spec = parse_volume_spec('/the/volume')
  259. self.assertEqual(spec, (None, '/the/volume', 'rw'))
  260. def test_parse_volume_spec_internal_and_external(self):
  261. spec = parse_volume_spec('external:interval')
  262. self.assertEqual(spec, ('external', 'interval', 'rw'))
  263. def test_parse_volume_spec_with_mode(self):
  264. spec = parse_volume_spec('external:interval:ro')
  265. self.assertEqual(spec, ('external', 'interval', 'ro'))
  266. def test_parse_volume_spec_too_many_parts(self):
  267. with self.assertRaises(ConfigError):
  268. parse_volume_spec('one:two:three:four')
  269. def test_parse_volume_bad_mode(self):
  270. with self.assertRaises(ConfigError):
  271. parse_volume_spec('one:two:notrw')
  272. def test_build_volume_binding(self):
  273. binding = build_volume_binding(parse_volume_spec('/outside:/inside'))
  274. self.assertEqual(binding, ('/inside', '/outside:/inside:rw'))
  275. def test_get_container_data_volumes(self):
  276. options = [
  277. '/host/volume:/host/volume:ro',
  278. '/new/volume',
  279. '/existing/volume',
  280. ]
  281. self.mock_client.inspect_image.return_value = {
  282. 'ContainerConfig': {
  283. 'Volumes': {
  284. '/mnt/image/data': {},
  285. }
  286. }
  287. }
  288. container = Container(self.mock_client, {
  289. 'Image': 'ababab',
  290. 'Volumes': {
  291. '/host/volume': '/host/volume',
  292. '/existing/volume': '/var/lib/docker/aaaaaaaa',
  293. '/removed/volume': '/var/lib/docker/bbbbbbbb',
  294. '/mnt/image/data': '/var/lib/docker/cccccccc',
  295. },
  296. }, has_been_inspected=True)
  297. expected = {
  298. '/existing/volume': '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  299. '/mnt/image/data': '/var/lib/docker/cccccccc:/mnt/image/data:rw',
  300. }
  301. binds = get_container_data_volumes(container, options)
  302. self.assertEqual(binds, expected)
  303. def test_merge_volume_bindings(self):
  304. options = [
  305. '/host/volume:/host/volume:ro',
  306. '/host/rw/volume:/host/rw/volume',
  307. '/new/volume',
  308. '/existing/volume',
  309. ]
  310. self.mock_client.inspect_image.return_value = {
  311. 'ContainerConfig': {'Volumes': {}}
  312. }
  313. intermediate_container = Container(self.mock_client, {
  314. 'Image': 'ababab',
  315. 'Volumes': {'/existing/volume': '/var/lib/docker/aaaaaaaa'},
  316. }, has_been_inspected=True)
  317. expected = [
  318. '/host/volume:/host/volume:ro',
  319. '/host/rw/volume:/host/rw/volume:rw',
  320. '/var/lib/docker/aaaaaaaa:/existing/volume:rw',
  321. ]
  322. binds = merge_volume_bindings(options, intermediate_container)
  323. self.assertEqual(set(binds), set(expected))
  324. def test_mount_same_host_path_to_two_volumes(self):
  325. service = Service(
  326. 'web',
  327. image='busybox',
  328. volumes=[
  329. '/host/path:/data1',
  330. '/host/path:/data2',
  331. ],
  332. client=self.mock_client,
  333. )
  334. self.mock_client.inspect_image.return_value = {
  335. 'Id': 'ababab',
  336. 'ContainerConfig': {
  337. 'Volumes': {}
  338. }
  339. }
  340. create_options = service._get_container_create_options(
  341. override_options={},
  342. number=1,
  343. )
  344. self.assertEqual(
  345. set(create_options['host_config']['Binds']),
  346. set([
  347. '/host/path:/data1:rw',
  348. '/host/path:/data2:rw',
  349. ]),
  350. )
  351. def test_different_host_path_in_container_json(self):
  352. service = Service(
  353. 'web',
  354. image='busybox',
  355. volumes=['/host/path:/data'],
  356. client=self.mock_client,
  357. )
  358. self.mock_client.inspect_image.return_value = {
  359. 'Id': 'ababab',
  360. 'ContainerConfig': {
  361. 'Volumes': {
  362. '/data': {},
  363. }
  364. }
  365. }
  366. self.mock_client.inspect_container.return_value = {
  367. 'Id': '123123123',
  368. 'Image': 'ababab',
  369. 'Volumes': {
  370. '/data': '/mnt/sda1/host/path',
  371. },
  372. }
  373. create_options = service._get_container_create_options(
  374. override_options={},
  375. number=1,
  376. previous_container=Container(self.mock_client, {'Id': '123123123'}),
  377. )
  378. self.assertEqual(
  379. create_options['host_config']['Binds'],
  380. ['/mnt/sda1/host/path:/data:rw'],
  381. )