1
0

test_docker_container.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Integration tests for the docker_container states
  4. '''
  5. # Import Python Libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import errno
  8. import functools
  9. import logging
  10. import os
  11. import subprocess
  12. import tempfile
  13. # Import Salt Testing Libs
  14. from tests.support.unit import skipIf
  15. from tests.support.case import ModuleCase
  16. from tests.support.docker import with_network, random_name
  17. from tests.support.paths import FILES, TMP
  18. from tests.support.helpers import destructiveTest, with_tempdir
  19. from tests.support.mixins import SaltReturnAssertsMixin
  20. # Import Salt Libs
  21. import salt.utils.files
  22. import salt.utils.network
  23. import salt.utils.path
  24. from salt.exceptions import CommandExecutionError
  25. # Import 3rd-party libs
  26. from salt.ext import six
  27. log = logging.getLogger(__name__)
  28. IPV6_ENABLED = bool(salt.utils.network.ip_addrs6(include_loopback=True))
  29. def container_name(func):
  30. '''
  31. Generate a randomized name for a container and clean it up afterward
  32. '''
  33. @functools.wraps(func)
  34. def wrapper(self, *args, **kwargs):
  35. name = random_name(prefix='salt_test_')
  36. try:
  37. return func(self, name, *args, **kwargs)
  38. finally:
  39. try:
  40. self.run_function('docker.rm', [name], force=True)
  41. except CommandExecutionError as exc:
  42. if 'No such container' not in exc.__str__():
  43. raise
  44. return wrapper
  45. @destructiveTest
  46. @skipIf(not salt.utils.path.which('busybox'), 'Busybox not installed')
  47. @skipIf(not salt.utils.path.which('dockerd'), 'Docker not installed')
  48. class DockerContainerTestCase(ModuleCase, SaltReturnAssertsMixin):
  49. '''
  50. Test docker_container states
  51. '''
  52. @classmethod
  53. def setUpClass(cls):
  54. '''
  55. '''
  56. # Create temp dir
  57. cls.image_build_rootdir = tempfile.mkdtemp(dir=TMP)
  58. # Generate image name
  59. cls.image = random_name(prefix='salt_busybox_')
  60. script_path = \
  61. os.path.join(FILES, 'file/base/mkimage-busybox-static')
  62. cmd = [script_path, cls.image_build_rootdir, cls.image]
  63. log.debug('Running \'%s\' to build busybox image', ' '.join(cmd))
  64. process = subprocess.Popen(
  65. cmd,
  66. close_fds=True,
  67. stdout=subprocess.PIPE,
  68. stderr=subprocess.STDOUT)
  69. output = process.communicate()[0]
  70. log.debug('Output from mkimge-busybox-static:\n%s', output)
  71. if process.returncode != 0:
  72. raise Exception('Failed to build image')
  73. try:
  74. salt.utils.files.rm_rf(cls.image_build_rootdir)
  75. except OSError as exc:
  76. if exc.errno != errno.ENOENT:
  77. raise
  78. @classmethod
  79. def tearDownClass(cls):
  80. cmd = ['docker', 'rmi', '--force', cls.image]
  81. log.debug('Running \'%s\' to destroy busybox image', ' '.join(cmd))
  82. process = subprocess.Popen(
  83. cmd,
  84. close_fds=True,
  85. stdout=subprocess.PIPE,
  86. stderr=subprocess.STDOUT)
  87. output = process.communicate()[0]
  88. log.debug('Output from %s:\n%s', ' '.join(cmd), output)
  89. if process.returncode != 0:
  90. raise Exception('Failed to destroy image')
  91. def run_state(self, function, **kwargs):
  92. ret = super(DockerContainerTestCase, self).run_state(function, **kwargs)
  93. log.debug('ret = %s', ret)
  94. return ret
  95. @with_tempdir()
  96. @container_name
  97. def test_running_with_no_predefined_volume(self, name, bind_dir_host):
  98. '''
  99. This tests that a container created using the docker_container.running
  100. state, with binds defined, will also create the corresponding volumes
  101. if they aren't pre-defined in the image.
  102. '''
  103. ret = self.run_state(
  104. 'docker_container.running',
  105. name=name,
  106. image=self.image,
  107. binds=bind_dir_host + ':/foo',
  108. shutdown_timeout=1,
  109. )
  110. self.assertSaltTrueReturn(ret)
  111. # Now check to ensure that the container has volumes to match the
  112. # binds that we used when creating it.
  113. ret = self.run_function('docker.inspect_container', [name])
  114. self.assertTrue('/foo' in ret['Config']['Volumes'])
  115. @container_name
  116. def test_running_with_no_predefined_ports(self, name):
  117. '''
  118. This tests that a container created using the docker_container.running
  119. state, with port_bindings defined, will also configure the
  120. corresponding ports if they aren't pre-defined in the image.
  121. '''
  122. ret = self.run_state(
  123. 'docker_container.running',
  124. name=name,
  125. image=self.image,
  126. port_bindings='14505-14506:24505-24506,2123:2123/udp,8080',
  127. shutdown_timeout=1,
  128. )
  129. self.assertSaltTrueReturn(ret)
  130. # Now check to ensure that the container has ports to match the
  131. # port_bindings that we used when creating it.
  132. expected_ports = (4505, 4506, 8080, '2123/udp')
  133. ret = self.run_function('docker.inspect_container', [name])
  134. self.assertTrue(x in ret['NetworkSettings']['Ports']
  135. for x in expected_ports)
  136. @container_name
  137. def test_running_updated_image_id(self, name):
  138. '''
  139. This tests the case of an image being changed after the container is
  140. created. The next time the state is run, the container should be
  141. replaced because the image ID is now different.
  142. '''
  143. # Create and start a container
  144. ret = self.run_state(
  145. 'docker_container.running',
  146. name=name,
  147. image=self.image,
  148. shutdown_timeout=1,
  149. )
  150. self.assertSaltTrueReturn(ret)
  151. # Get the container's info
  152. c_info = self.run_function('docker.inspect_container', [name])
  153. c_name, c_id = (c_info[x] for x in ('Name', 'Id'))
  154. # Alter the filesystem inside the container
  155. self.assertEqual(
  156. self.run_function('docker.retcode', [name, 'touch /.salttest']),
  157. 0
  158. )
  159. # Commit the changes and overwrite the test class' image
  160. self.run_function('docker.commit', [c_id, self.image])
  161. # Re-run the state
  162. ret = self.run_state(
  163. 'docker_container.running',
  164. name=name,
  165. image=self.image,
  166. shutdown_timeout=1,
  167. )
  168. self.assertSaltTrueReturn(ret)
  169. # Discard the outer dict with the state compiler data to make below
  170. # asserts easier to read/write
  171. ret = ret[next(iter(ret))]
  172. # Check to make sure that the container was replaced
  173. self.assertTrue('container_id' in ret['changes'])
  174. # Check to make sure that the image is in the changes dict, since
  175. # it should have changed
  176. self.assertTrue('image' in ret['changes'])
  177. # Check that the comment in the state return states that
  178. # container's image has changed
  179. self.assertTrue('Container has a new image' in ret['comment'])
  180. @container_name
  181. def test_running_start_false_without_replace(self, name):
  182. '''
  183. Test that we do not start a container which is stopped, when it is not
  184. being replaced.
  185. '''
  186. # Create a container
  187. ret = self.run_state(
  188. 'docker_container.running',
  189. name=name,
  190. image=self.image,
  191. shutdown_timeout=1,
  192. )
  193. self.assertSaltTrueReturn(ret)
  194. # Stop the container
  195. self.run_function('docker.stop', [name], force=True)
  196. # Re-run the state with start=False
  197. ret = self.run_state(
  198. 'docker_container.running',
  199. name=name,
  200. image=self.image,
  201. start=False,
  202. shutdown_timeout=1,
  203. )
  204. self.assertSaltTrueReturn(ret)
  205. # Discard the outer dict with the state compiler data to make below
  206. # asserts easier to read/write
  207. ret = ret[next(iter(ret))]
  208. # Check to make sure that the container was not replaced
  209. self.assertTrue('container_id' not in ret['changes'])
  210. # Check to make sure that the state is not the changes dict, since
  211. # it should not have changed
  212. self.assertTrue('state' not in ret['changes'])
  213. @container_name
  214. def test_running_start_false_with_replace(self, name):
  215. '''
  216. Test that we do start a container which was previously stopped, even
  217. though start=False, because the container was replaced.
  218. '''
  219. # Create a container
  220. ret = self.run_state(
  221. 'docker_container.running',
  222. name=name,
  223. image=self.image,
  224. shutdown_timeout=1,
  225. )
  226. self.assertSaltTrueReturn(ret)
  227. # Stop the container
  228. self.run_function('docker.stop', [name], force=True)
  229. # Re-run the state with start=False but also change the command to
  230. # trigger the container being replaced.
  231. ret = self.run_state(
  232. 'docker_container.running',
  233. name=name,
  234. image=self.image,
  235. command='sleep 600',
  236. start=False,
  237. shutdown_timeout=1,
  238. )
  239. self.assertSaltTrueReturn(ret)
  240. # Discard the outer dict with the state compiler data to make below
  241. # asserts easier to read/write
  242. ret = ret[next(iter(ret))]
  243. # Check to make sure that the container was not replaced
  244. self.assertTrue('container_id' in ret['changes'])
  245. # Check to make sure that the state is not the changes dict, since
  246. # it should not have changed
  247. self.assertTrue('state' not in ret['changes'])
  248. @container_name
  249. def test_running_start_true(self, name):
  250. '''
  251. This tests that we *do* start a container that is stopped, when the
  252. "start" argument is set to True.
  253. '''
  254. # Create a container
  255. ret = self.run_state(
  256. 'docker_container.running',
  257. name=name,
  258. image=self.image,
  259. shutdown_timeout=1,
  260. )
  261. self.assertSaltTrueReturn(ret)
  262. # Stop the container
  263. self.run_function('docker.stop', [name], force=True)
  264. # Re-run the state with start=True
  265. ret = self.run_state(
  266. 'docker_container.running',
  267. name=name,
  268. image=self.image,
  269. start=True,
  270. shutdown_timeout=1,
  271. )
  272. self.assertSaltTrueReturn(ret)
  273. # Discard the outer dict with the state compiler data to make below
  274. # asserts easier to read/write
  275. ret = ret[next(iter(ret))]
  276. # Check to make sure that the container was not replaced
  277. self.assertTrue('container_id' not in ret['changes'])
  278. # Check to make sure that the state is in the changes dict, since
  279. # it should have changed
  280. self.assertTrue('state' in ret['changes'])
  281. # Check that the comment in the state return states that
  282. # container's state has changed
  283. self.assertTrue(
  284. "State changed from 'stopped' to 'running'" in ret['comment'])
  285. @container_name
  286. def test_running_with_invalid_input(self, name):
  287. '''
  288. This tests that the input tranlation code identifies invalid input and
  289. includes information about that invalid argument in the state return.
  290. '''
  291. # Try to create a container with invalid input
  292. ret = self.run_state(
  293. 'docker_container.running',
  294. name=name,
  295. image=self.image,
  296. ulimits='nofile:2048',
  297. shutdown_timeout=1,
  298. )
  299. self.assertSaltFalseReturn(ret)
  300. # Discard the outer dict with the state compiler data to make below
  301. # asserts easier to read/write
  302. ret = ret[next(iter(ret))]
  303. # Check to make sure that the container was not created
  304. self.assertTrue('container_id' not in ret['changes'])
  305. # Check that the error message about the invalid argument is
  306. # included in the comment for the state
  307. self.assertTrue(
  308. 'Ulimit definition \'nofile:2048\' is not in the format '
  309. 'type=soft_limit[:hard_limit]' in ret['comment']
  310. )
  311. @container_name
  312. def test_running_with_argument_collision(self, name):
  313. '''
  314. this tests that the input tranlation code identifies an argument
  315. collision (API args and their aliases being simultaneously used) and
  316. includes information about them in the state return.
  317. '''
  318. # try to create a container with invalid input
  319. ret = self.run_state(
  320. 'docker_container.running',
  321. name=name,
  322. image=self.image,
  323. ulimits='nofile=2048',
  324. ulimit='nofile=1024:2048',
  325. shutdown_timeout=1,
  326. )
  327. self.assertSaltFalseReturn(ret)
  328. # Ciscard the outer dict with the state compiler data to make below
  329. # asserts easier to read/write
  330. ret = ret[next(iter(ret))]
  331. # Check to make sure that the container was not created
  332. self.assertTrue('container_id' not in ret['changes'])
  333. # Check that the error message about the collision is included in
  334. # the comment for the state
  335. self.assertTrue(
  336. '\'ulimit\' is an alias for \'ulimits\'' in ret['comment'])
  337. @container_name
  338. def test_running_with_ignore_collisions(self, name):
  339. '''
  340. This tests that the input tranlation code identifies an argument
  341. collision (API args and their aliases being simultaneously used)
  342. includes information about them in the state return.
  343. '''
  344. # try to create a container with invalid input
  345. ret = self.run_state(
  346. 'docker_container.running',
  347. name=name,
  348. image=self.image,
  349. ignore_collisions=True,
  350. ulimits='nofile=2048',
  351. ulimit='nofile=1024:2048',
  352. shutdown_timeout=1,
  353. )
  354. self.assertSaltTrueReturn(ret)
  355. # Discard the outer dict with the state compiler data to make below
  356. # asserts easier to read/write
  357. ret = ret[next(iter(ret))]
  358. # Check to make sure that the container was created
  359. self.assertTrue('container_id' in ret['changes'])
  360. # Check that the value from the API argument was one that was used
  361. # to create the container
  362. c_info = self.run_function('docker.inspect_container', [name])
  363. actual = c_info['HostConfig']['Ulimits']
  364. expected = [{'Name': 'nofile', 'Soft': 2048, 'Hard': 2048}]
  365. self.assertEqual(actual, expected)
  366. @container_name
  367. def test_running_with_removed_argument(self, name):
  368. '''
  369. This tests that removing an argument from a created container will
  370. be detected and result in the container being replaced.
  371. It also tests that we revert back to the value from the image. This
  372. way, when the "command" argument is removed, we confirm that we are
  373. reverting back to the image's command.
  374. '''
  375. # Create the container
  376. ret = self.run_state(
  377. 'docker_container.running',
  378. name=name,
  379. image=self.image,
  380. command='sleep 600',
  381. shutdown_timeout=1,
  382. )
  383. self.assertSaltTrueReturn(ret)
  384. # Run the state again with the "command" argument removed
  385. ret = self.run_state(
  386. 'docker_container.running',
  387. name=name,
  388. image=self.image,
  389. shutdown_timeout=1,
  390. )
  391. self.assertSaltTrueReturn(ret)
  392. # Discard the outer dict with the state compiler data to make below
  393. # asserts easier to read/write
  394. ret = ret[next(iter(ret))]
  395. # Now check to ensure that the changes include the command
  396. # reverting back to the image's command.
  397. image_info = self.run_function('docker.inspect_image', [self.image])
  398. self.assertEqual(
  399. ret['changes']['container']['Config']['Cmd']['new'],
  400. image_info['Config']['Cmd']
  401. )
  402. @container_name
  403. def test_running_with_port_bindings(self, name):
  404. '''
  405. This tests that the ports which are being bound are also exposed, even
  406. when not explicitly configured. This test will create a container with
  407. only some of the ports exposed, including some which aren't even bound.
  408. The resulting containers exposed ports should contain all of the ports
  409. defined in the "ports" argument, as well as each of the ports which are
  410. being bound.
  411. '''
  412. # Create the container
  413. ret = self.run_state(
  414. 'docker_container.running',
  415. name=name,
  416. image=self.image,
  417. command='sleep 600',
  418. shutdown_timeout=1,
  419. port_bindings=[1234, '1235-1236', '2234/udp', '2235-2236/udp'],
  420. ports=[1235, '2235/udp', 9999],
  421. )
  422. self.assertSaltTrueReturn(ret)
  423. # Check the created container's port bindings and exposed ports. The
  424. # port bindings should only contain the ports defined in the
  425. # port_bindings argument, while the exposed ports should also contain
  426. # the extra port (9999/tcp) which was included in the ports argument.
  427. cinfo = self.run_function('docker.inspect_container', [name])
  428. ports = ['1234/tcp', '1235/tcp', '1236/tcp',
  429. '2234/udp', '2235/udp', '2236/udp']
  430. self.assertEqual(
  431. sorted(cinfo['HostConfig']['PortBindings']),
  432. ports
  433. )
  434. self.assertEqual(
  435. sorted(cinfo['Config']['ExposedPorts']),
  436. ports + ['9999/tcp']
  437. )
  438. @container_name
  439. def test_absent_with_stopped_container(self, name):
  440. '''
  441. This tests the docker_container.absent state on a stopped container
  442. '''
  443. # Create the container
  444. self.run_function('docker.create', [self.image], name=name)
  445. # Remove the container
  446. ret = self.run_state(
  447. 'docker_container.absent',
  448. name=name,
  449. )
  450. self.assertSaltTrueReturn(ret)
  451. # Discard the outer dict with the state compiler data to make below
  452. # asserts easier to read/write
  453. ret = ret[next(iter(ret))]
  454. # Check that we have a removed container ID in the changes dict
  455. self.assertTrue('removed' in ret['changes'])
  456. # Run the state again to confirm it changes nothing
  457. ret = self.run_state(
  458. 'docker_container.absent',
  459. name=name,
  460. )
  461. self.assertSaltTrueReturn(ret)
  462. # Discard the outer dict with the state compiler data to make below
  463. # asserts easier to read/write
  464. ret = ret[next(iter(ret))]
  465. # Nothing should have changed
  466. self.assertEqual(ret['changes'], {})
  467. # Ensure that the comment field says the container does not exist
  468. self.assertEqual(
  469. ret['comment'],
  470. 'Container \'{0}\' does not exist'.format(name)
  471. )
  472. @container_name
  473. def test_absent_with_running_container(self, name):
  474. '''
  475. This tests the docker_container.absent state and
  476. '''
  477. # Create the container
  478. ret = self.run_state(
  479. 'docker_container.running',
  480. name=name,
  481. image=self.image,
  482. command='sleep 600',
  483. shutdown_timeout=1,
  484. )
  485. self.assertSaltTrueReturn(ret)
  486. # Try to remove the container. This should fail because force=True
  487. # is needed to remove a container that is running.
  488. ret = self.run_state(
  489. 'docker_container.absent',
  490. name=name,
  491. )
  492. self.assertSaltFalseReturn(ret)
  493. # Discard the outer dict with the state compiler data to make below
  494. # asserts easier to read/write
  495. ret = ret[next(iter(ret))]
  496. # Nothing should have changed
  497. self.assertEqual(ret['changes'], {})
  498. # Ensure that the comment states that force=True is required
  499. self.assertEqual(
  500. ret['comment'],
  501. 'Container is running, set force to True to forcibly remove it'
  502. )
  503. # Try again with force=True. This should succeed.
  504. ret = self.run_state('docker_container.absent',
  505. name=name,
  506. force=True,
  507. )
  508. self.assertSaltTrueReturn(ret)
  509. # Discard the outer dict with the state compiler data to make below
  510. # asserts easier to read/write
  511. ret = ret[next(iter(ret))]
  512. # Check that we have a removed container ID in the changes dict
  513. self.assertTrue('removed' in ret['changes'])
  514. # The comment should mention that the container was removed
  515. self.assertEqual(
  516. ret['comment'],
  517. 'Forcibly removed container \'{0}\''.format(name)
  518. )
  519. @container_name
  520. def test_running_image_name(self, name):
  521. '''
  522. Ensure that we create the container using the image name instead of ID
  523. '''
  524. ret = self.run_state(
  525. 'docker_container.running',
  526. name=name,
  527. image=self.image,
  528. shutdown_timeout=1,
  529. )
  530. self.assertSaltTrueReturn(ret)
  531. ret = self.run_function('docker.inspect_container', [name])
  532. self.assertEqual(ret['Config']['Image'], self.image)
  533. @container_name
  534. def test_env_with_running_container(self, name):
  535. '''
  536. docker_container.running environnment part. Testing issue 39838.
  537. '''
  538. ret = self.run_state(
  539. 'docker_container.running',
  540. name=name,
  541. image=self.image,
  542. env='VAR1=value1,VAR2=value2,VAR3=value3',
  543. shutdown_timeout=1,
  544. )
  545. self.assertSaltTrueReturn(ret)
  546. ret = self.run_function('docker.inspect_container', [name])
  547. self.assertTrue('VAR1=value1' in ret['Config']['Env'])
  548. self.assertTrue('VAR2=value2' in ret['Config']['Env'])
  549. self.assertTrue('VAR3=value3' in ret['Config']['Env'])
  550. ret = self.run_state(
  551. 'docker_container.running',
  552. name=name,
  553. image=self.image,
  554. env='VAR1=value1,VAR2=value2',
  555. shutdown_timeout=1,
  556. )
  557. self.assertSaltTrueReturn(ret)
  558. ret = self.run_function('docker.inspect_container', [name])
  559. self.assertTrue('VAR1=value1' in ret['Config']['Env'])
  560. self.assertTrue('VAR2=value2' in ret['Config']['Env'])
  561. self.assertTrue('VAR3=value3' not in ret['Config']['Env'])
  562. @with_network(subnet='10.247.197.96/27', create=True)
  563. @container_name
  564. def test_static_ip_one_network(self, container_name, net):
  565. '''
  566. Ensure that if a network is created and specified as network_mode, that is the only network, and
  567. the static IP is applied.
  568. '''
  569. requested_ip = '10.247.197.100'
  570. kwargs = {
  571. 'name': container_name,
  572. 'image': self.image,
  573. 'network_mode': net.name,
  574. 'networks': [{net.name: [{'ipv4_address': requested_ip}]}],
  575. 'shutdown_timeout': 1,
  576. }
  577. # Create a container
  578. ret = self.run_state('docker_container.running', **kwargs)
  579. self.assertSaltTrueReturn(ret)
  580. inspect_result = self.run_function('docker.inspect_container',
  581. [container_name])
  582. connected_networks = inspect_result['NetworkSettings']['Networks']
  583. self.assertEqual(list(connected_networks.keys()), [net.name])
  584. self.assertEqual(inspect_result['HostConfig']['NetworkMode'], net.name)
  585. self.assertEqual(connected_networks[net.name]['IPAMConfig']['IPv4Address'], requested_ip)
  586. def _test_running(self, container_name, *nets):
  587. '''
  588. DRY function for testing static IPs
  589. '''
  590. networks = []
  591. for net in nets:
  592. net_def = {
  593. net.name: [
  594. {net.ip_arg: net[0]}
  595. ]
  596. }
  597. networks.append(net_def)
  598. kwargs = {
  599. 'name': container_name,
  600. 'image': self.image,
  601. 'networks': networks,
  602. 'shutdown_timeout': 1,
  603. }
  604. # Create a container
  605. ret = self.run_state('docker_container.running', **kwargs)
  606. self.assertSaltTrueReturn(ret)
  607. inspect_result = self.run_function('docker.inspect_container',
  608. [container_name])
  609. connected_networks = inspect_result['NetworkSettings']['Networks']
  610. # Check that the correct IP was set
  611. try:
  612. for net in nets:
  613. self.assertEqual(
  614. connected_networks[net.name]['IPAMConfig'][net.arg_map(net.ip_arg)],
  615. net[0]
  616. )
  617. except KeyError:
  618. # Fail with a meaningful error
  619. msg = (
  620. 'Container does not have the expected network config for '
  621. 'network {0}'.format(net.name)
  622. )
  623. log.error(msg)
  624. log.error('Connected networks: %s', connected_networks)
  625. self.fail('{0}. See log for more information.'.format(msg))
  626. # Check that container continued running and didn't immediately exit
  627. self.assertTrue(inspect_result['State']['Running'])
  628. # Update the SLS configuration to use the second random IP so that we
  629. # can test updating a container's network configuration without
  630. # replacing the container.
  631. for idx, net in enumerate(nets):
  632. kwargs['networks'][idx][net.name][0][net.ip_arg] = net[1]
  633. ret = self.run_state('docker_container.running', **kwargs)
  634. self.assertSaltTrueReturn(ret)
  635. ret = ret[next(iter(ret))]
  636. expected = {'container': {'Networks': {}}}
  637. for net in nets:
  638. expected['container']['Networks'][net.name] = {
  639. 'IPAMConfig': {
  640. 'old': {net.arg_map(net.ip_arg): net[0]},
  641. 'new': {net.arg_map(net.ip_arg): net[1]},
  642. }
  643. }
  644. self.assertEqual(ret['changes'], expected)
  645. expected = [
  646. "Container '{0}' is already configured as specified.".format(
  647. container_name
  648. )
  649. ]
  650. expected.extend([
  651. "Reconnected to network '{0}' with updated configuration.".format(
  652. x.name
  653. )
  654. for x in sorted(nets, key=lambda y: y.name)
  655. ])
  656. expected = ' '.join(expected)
  657. self.assertEqual(ret['comment'], expected)
  658. # Update the SLS configuration to remove the last network
  659. kwargs['networks'].pop(-1)
  660. ret = self.run_state('docker_container.running', **kwargs)
  661. self.assertSaltTrueReturn(ret)
  662. ret = ret[next(iter(ret))]
  663. expected = {
  664. 'container': {
  665. 'Networks': {
  666. nets[-1].name: {
  667. 'IPAMConfig': {
  668. 'old': {
  669. nets[-1].arg_map(nets[-1].ip_arg): nets[-1][1]
  670. },
  671. 'new': None,
  672. }
  673. }
  674. }
  675. }
  676. }
  677. self.assertEqual(ret['changes'], expected)
  678. expected = (
  679. "Container '{0}' is already configured as specified. Disconnected "
  680. "from network '{1}'.".format(container_name, nets[-1].name)
  681. )
  682. self.assertEqual(ret['comment'], expected)
  683. # Update the SLS configuration to add back the last network, only use
  684. # an automatic IP instead of static IP.
  685. kwargs['networks'].append(nets[-1].name)
  686. ret = self.run_state('docker_container.running', **kwargs)
  687. self.assertSaltTrueReturn(ret)
  688. ret = ret[next(iter(ret))]
  689. # Get the automatic IP by inspecting the container, and use it to build
  690. # the expected changes.
  691. container_netinfo = self.run_function(
  692. 'docker.inspect_container',
  693. [container_name]).get('NetworkSettings', {}).get('Networks', {})[nets[-1].name]
  694. autoip_keys = self.minion_opts['docker.compare_container_networks']['automatic']
  695. autoip_config = {
  696. x: y for x, y in six.iteritems(container_netinfo)
  697. if x in autoip_keys and y
  698. }
  699. expected = {'container': {'Networks': {nets[-1].name: {}}}}
  700. for key, val in six.iteritems(autoip_config):
  701. expected['container']['Networks'][nets[-1].name][key] = {
  702. 'old': None, 'new': val
  703. }
  704. self.assertEqual(ret['changes'], expected)
  705. expected = (
  706. "Container '{0}' is already configured as specified. Connected "
  707. "to network '{1}'.".format(container_name, nets[-1].name)
  708. )
  709. self.assertEqual(ret['comment'], expected)
  710. # Update the SLS configuration to remove the last network
  711. kwargs['networks'].pop(-1)
  712. ret = self.run_state('docker_container.running', **kwargs)
  713. self.assertSaltTrueReturn(ret)
  714. ret = ret[next(iter(ret))]
  715. expected = {'container': {'Networks': {nets[-1].name: {}}}}
  716. for key, val in six.iteritems(autoip_config):
  717. expected['container']['Networks'][nets[-1].name][key] = {
  718. 'old': val, 'new': None
  719. }
  720. self.assertEqual(ret['changes'], expected)
  721. expected = (
  722. "Container '{0}' is already configured as specified. Disconnected "
  723. "from network '{1}'.".format(container_name, nets[-1].name)
  724. )
  725. self.assertEqual(ret['comment'], expected)
  726. @with_network(subnet='10.247.197.96/27', create=True)
  727. @container_name
  728. def test_running_ipv4(self, container_name, *nets):
  729. self._test_running(container_name, *nets)
  730. @with_network(subnet='10.247.197.128/27', create=True)
  731. @with_network(subnet='10.247.197.96/27', create=True)
  732. @container_name
  733. def test_running_dual_ipv4(self, container_name, *nets):
  734. self._test_running(container_name, *nets)
  735. @with_network(subnet='fe3f:2180:26:1::/123', create=True)
  736. @container_name
  737. @skipIf(not IPV6_ENABLED, 'IPv6 not enabled')
  738. def test_running_ipv6(self, container_name, *nets):
  739. self._test_running(container_name, *nets)
  740. @with_network(subnet='fe3f:2180:26:1::20/123', create=True)
  741. @with_network(subnet='fe3f:2180:26:1::/123', create=True)
  742. @container_name
  743. @skipIf(not IPV6_ENABLED, 'IPv6 not enabled')
  744. def test_running_dual_ipv6(self, container_name, *nets):
  745. self._test_running(container_name, *nets)
  746. @with_network(subnet='fe3f:2180:26:1::/123', create=True)
  747. @with_network(subnet='10.247.197.96/27', create=True)
  748. @container_name
  749. @skipIf(not IPV6_ENABLED, 'IPv6 not enabled')
  750. def test_running_mixed_ipv4_and_ipv6(self, container_name, *nets):
  751. self._test_running(container_name, *nets)
  752. @with_network(subnet='10.247.197.96/27', create=True)
  753. @container_name
  754. def test_running_explicit_networks(self, container_name, net):
  755. '''
  756. Ensure that if we use an explicit network configuration, we remove any
  757. default networks not specified (e.g. the default "bridge" network).
  758. '''
  759. # Create a container with no specific network configuration. The only
  760. # networks connected will be the default ones.
  761. ret = self.run_state(
  762. 'docker_container.running',
  763. name=container_name,
  764. image=self.image,
  765. shutdown_timeout=1)
  766. self.assertSaltTrueReturn(ret)
  767. inspect_result = self.run_function('docker.inspect_container',
  768. [container_name])
  769. # Get the default network names
  770. default_networks = list(inspect_result['NetworkSettings']['Networks'])
  771. # Re-run the state with an explicit network configuration. All of the
  772. # default networks should be disconnected.
  773. ret = self.run_state(
  774. 'docker_container.running',
  775. name=container_name,
  776. image=self.image,
  777. networks=[net.name],
  778. shutdown_timeout=1)
  779. self.assertSaltTrueReturn(ret)
  780. ret = ret[next(iter(ret))]
  781. net_changes = ret['changes']['container']['Networks']
  782. self.assertIn(
  783. "Container '{0}' is already configured as specified.".format(
  784. container_name
  785. ),
  786. ret['comment']
  787. )
  788. updated_networks = self.run_function(
  789. 'docker.inspect_container',
  790. [container_name])['NetworkSettings']['Networks']
  791. for default_network in default_networks:
  792. self.assertIn(
  793. "Disconnected from network '{0}'.".format(default_network),
  794. ret['comment']
  795. )
  796. self.assertIn(default_network, net_changes)
  797. # We've tested that the state return is correct, but let's be extra
  798. # paranoid and check the actual connected networks.
  799. self.assertNotIn(default_network, updated_networks)
  800. self.assertIn(
  801. "Connected to network '{0}'.".format(net.name),
  802. ret['comment']
  803. )
  804. @container_name
  805. def test_run_with_onlyif(self, name):
  806. '''
  807. Test docker_container.run with onlyif. The container should not run
  808. (and the state should return a True result) if the onlyif has a nonzero
  809. return code, but if the onlyif has a zero return code the container
  810. should run.
  811. '''
  812. for cmd in ('/bin/false', ['/bin/true', '/bin/false']):
  813. log.debug('Trying %s', cmd)
  814. ret = self.run_state(
  815. 'docker_container.run',
  816. name=name,
  817. image=self.image,
  818. command='whoami',
  819. onlyif=cmd)
  820. self.assertSaltTrueReturn(ret)
  821. ret = ret[next(iter(ret))]
  822. self.assertFalse(ret['changes'])
  823. self.assertTrue(
  824. ret['comment'].startswith(
  825. 'onlyif command /bin/false returned exit code of'
  826. )
  827. )
  828. self.run_function('docker.rm', [name], force=True)
  829. for cmd in ('/bin/true', ['/bin/true', 'ls /']):
  830. log.debug('Trying %s', cmd)
  831. ret = self.run_state(
  832. 'docker_container.run',
  833. name=name,
  834. image=self.image,
  835. command='whoami',
  836. onlyif=cmd)
  837. self.assertSaltTrueReturn(ret)
  838. ret = ret[next(iter(ret))]
  839. self.assertEqual(ret['changes']['Logs'], 'root\n')
  840. self.assertEqual(
  841. ret['comment'],
  842. 'Container ran and exited with a return code of 0'
  843. )
  844. self.run_function('docker.rm', [name], force=True)
  845. @container_name
  846. def test_run_with_unless(self, name):
  847. '''
  848. Test docker_container.run with unless. The container should not run
  849. (and the state should return a True result) if the unless has a zero
  850. return code, but if the unless has a nonzero return code the container
  851. should run.
  852. '''
  853. for cmd in ('/bin/true', ['/bin/false', '/bin/true']):
  854. log.debug('Trying %s', cmd)
  855. ret = self.run_state(
  856. 'docker_container.run',
  857. name=name,
  858. image=self.image,
  859. command='whoami',
  860. unless=cmd)
  861. self.assertSaltTrueReturn(ret)
  862. ret = ret[next(iter(ret))]
  863. self.assertFalse(ret['changes'])
  864. self.assertEqual(
  865. ret['comment'],
  866. 'unless command /bin/true returned exit code of 0'
  867. )
  868. self.run_function('docker.rm', [name], force=True)
  869. for cmd in ('/bin/false', ['/bin/false', 'ls /paththatdoesnotexist']):
  870. log.debug('Trying %s', cmd)
  871. ret = self.run_state(
  872. 'docker_container.run',
  873. name=name,
  874. image=self.image,
  875. command='whoami',
  876. unless=cmd)
  877. self.assertSaltTrueReturn(ret)
  878. ret = ret[next(iter(ret))]
  879. self.assertEqual(ret['changes']['Logs'], 'root\n')
  880. self.assertEqual(
  881. ret['comment'],
  882. 'Container ran and exited with a return code of 0'
  883. )
  884. self.run_function('docker.rm', [name], force=True)
  885. @container_name
  886. def test_run_with_creates(self, name):
  887. '''
  888. Test docker_container.run with creates. The container should not run
  889. (and the state should return a True result) if all of the files exist,
  890. but if if any of the files do not exist the container should run.
  891. '''
  892. def _mkstemp():
  893. fd, ret = tempfile.mkstemp()
  894. try:
  895. os.close(fd)
  896. except OSError as exc:
  897. if exc.errno != errno.EBADF:
  898. raise exc
  899. else:
  900. self.addCleanup(os.remove, ret)
  901. return ret
  902. bad_file = '/tmp/filethatdoesnotexist'
  903. good_file1 = _mkstemp()
  904. good_file2 = _mkstemp()
  905. for path in (good_file1, [good_file1, good_file2]):
  906. log.debug('Trying %s', path)
  907. ret = self.run_state(
  908. 'docker_container.run',
  909. name=name,
  910. image=self.image,
  911. command='whoami',
  912. creates=path)
  913. self.assertSaltTrueReturn(ret)
  914. ret = ret[next(iter(ret))]
  915. self.assertFalse(ret['changes'])
  916. self.assertEqual(
  917. ret['comment'],
  918. 'All specified paths in \'creates\' argument exist'
  919. )
  920. self.run_function('docker.rm', [name], force=True)
  921. for path in (bad_file, [good_file1, bad_file]):
  922. log.debug('Trying %s', path)
  923. ret = self.run_state(
  924. 'docker_container.run',
  925. name=name,
  926. image=self.image,
  927. command='whoami',
  928. creates=path)
  929. self.assertSaltTrueReturn(ret)
  930. ret = ret[next(iter(ret))]
  931. self.assertEqual(ret['changes']['Logs'], 'root\n')
  932. self.assertEqual(
  933. ret['comment'],
  934. 'Container ran and exited with a return code of 0'
  935. )
  936. self.run_function('docker.rm', [name], force=True)
  937. @container_name
  938. def test_run_replace(self, name):
  939. '''
  940. Test the replace and force arguments to make sure they work properly
  941. '''
  942. # Run once to create the container
  943. ret = self.run_state(
  944. 'docker_container.run',
  945. name=name,
  946. image=self.image,
  947. command='whoami')
  948. self.assertSaltTrueReturn(ret)
  949. ret = ret[next(iter(ret))]
  950. self.assertEqual(ret['changes']['Logs'], 'root\n')
  951. self.assertEqual(
  952. ret['comment'],
  953. 'Container ran and exited with a return code of 0'
  954. )
  955. # Run again with replace=False, this should fail
  956. ret = self.run_state(
  957. 'docker_container.run',
  958. name=name,
  959. image=self.image,
  960. command='whoami',
  961. replace=False)
  962. self.assertSaltFalseReturn(ret)
  963. ret = ret[next(iter(ret))]
  964. self.assertFalse(ret['changes'])
  965. self.assertEqual(
  966. ret['comment'],
  967. 'Encountered error running container: Container \'{0}\' exists. '
  968. 'Run with replace=True to remove the existing container'.format(name)
  969. )
  970. # Run again with replace=True, this should proceed and there should be
  971. # a "Replaces" key in the changes dict to show that a container was
  972. # replaced.
  973. ret = self.run_state(
  974. 'docker_container.run',
  975. name=name,
  976. image=self.image,
  977. command='whoami',
  978. replace=True)
  979. self.assertSaltTrueReturn(ret)
  980. ret = ret[next(iter(ret))]
  981. self.assertEqual(ret['changes']['Logs'], 'root\n')
  982. self.assertTrue('Replaces' in ret['changes'])
  983. self.assertEqual(
  984. ret['comment'],
  985. 'Container ran and exited with a return code of 0'
  986. )
  987. @container_name
  988. def test_run_force(self, name):
  989. '''
  990. Test the replace and force arguments to make sure they work properly
  991. '''
  992. # Start up a container that will stay running
  993. ret = self.run_state(
  994. 'docker_container.running',
  995. name=name,
  996. image=self.image)
  997. self.assertSaltTrueReturn(ret)
  998. # Run again with replace=True, this should fail because the container
  999. # is still running
  1000. ret = self.run_state(
  1001. 'docker_container.run',
  1002. name=name,
  1003. image=self.image,
  1004. command='whoami',
  1005. replace=True,
  1006. force=False)
  1007. self.assertSaltFalseReturn(ret)
  1008. ret = ret[next(iter(ret))]
  1009. self.assertFalse(ret['changes'])
  1010. self.assertEqual(
  1011. ret['comment'],
  1012. 'Encountered error running container: Container \'{0}\' exists '
  1013. 'and is running. Run with replace=True and force=True to force '
  1014. 'removal of the existing container.'.format(name)
  1015. )
  1016. # Run again with replace=True and force=True, this should proceed and
  1017. # there should be a "Replaces" key in the changes dict to show that a
  1018. # container was replaced.
  1019. ret = self.run_state(
  1020. 'docker_container.run',
  1021. name=name,
  1022. image=self.image,
  1023. command='whoami',
  1024. replace=True,
  1025. force=True)
  1026. self.assertSaltTrueReturn(ret)
  1027. ret = ret[next(iter(ret))]
  1028. self.assertEqual(ret['changes']['Logs'], 'root\n')
  1029. self.assertTrue('Replaces' in ret['changes'])
  1030. self.assertEqual(
  1031. ret['comment'],
  1032. 'Container ran and exited with a return code of 0'
  1033. )
  1034. @container_name
  1035. def test_run_failhard(self, name):
  1036. '''
  1037. Test to make sure that we fail a state when the container exits with
  1038. nonzero status if failhard is set to True, and that we don't when it is
  1039. set to False.
  1040. '''
  1041. ret = self.run_state(
  1042. 'docker_container.run',
  1043. name=name,
  1044. image=self.image,
  1045. command='/bin/false',
  1046. failhard=True)
  1047. self.assertSaltFalseReturn(ret)
  1048. ret = ret[next(iter(ret))]
  1049. self.assertEqual(ret['changes']['Logs'], '')
  1050. self.assertTrue(
  1051. ret['comment'].startswith(
  1052. 'Container ran and exited with a return code of'
  1053. )
  1054. )
  1055. self.run_function('docker.rm', [name], force=True)
  1056. ret = self.run_state(
  1057. 'docker_container.run',
  1058. name=name,
  1059. image=self.image,
  1060. command='/bin/false',
  1061. failhard=False)
  1062. self.assertSaltTrueReturn(ret)
  1063. ret = ret[next(iter(ret))]
  1064. self.assertEqual(ret['changes']['Logs'], '')
  1065. self.assertTrue(
  1066. ret['comment'].startswith(
  1067. 'Container ran and exited with a return code of'
  1068. )
  1069. )
  1070. self.run_function('docker.rm', [name], force=True)
  1071. @container_name
  1072. def test_run_bg(self, name):
  1073. '''
  1074. Test to make sure that if the container is run in the background, we do
  1075. not include an ExitCode or Logs key in the return. Then check the logs
  1076. for the container to ensure that it ran as expected.
  1077. '''
  1078. ret = self.run_state(
  1079. 'docker_container.run',
  1080. name=name,
  1081. image=self.image,
  1082. command='sh -c "sleep 5 && whoami"',
  1083. bg=True)
  1084. self.assertSaltTrueReturn(ret)
  1085. ret = ret[next(iter(ret))]
  1086. self.assertTrue('Logs' not in ret['changes'])
  1087. self.assertTrue('ExitCode' not in ret['changes'])
  1088. self.assertEqual(ret['comment'], 'Container was run in the background')
  1089. # Now check the logs. The expectation is that the above asserts
  1090. # completed during the 5-second sleep.
  1091. self.assertEqual(
  1092. self.run_function('docker.logs', [name], follow=True),
  1093. 'root\n'
  1094. )