test_docker_container.py 45 KB

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