1
0

test_docker_container.py 45 KB

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