test_config.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. # -*- coding: utf-8 -*-
  2. """
  3. Unit tests for salt.config
  4. """
  5. from __future__ import absolute_import, print_function, unicode_literals
  6. import logging
  7. import os
  8. import textwrap
  9. import pytest
  10. import salt.config
  11. import salt.minion
  12. import salt.syspaths
  13. import salt.utils.files
  14. import salt.utils.network
  15. import salt.utils.platform
  16. import salt.utils.yaml
  17. from salt.exceptions import (
  18. CommandExecutionError,
  19. SaltCloudConfigError,
  20. SaltConfigurationError,
  21. )
  22. from salt.ext import six
  23. from salt.syspaths import CONFIG_DIR
  24. from tests.support.helpers import patched_environ, with_tempdir, with_tempfile
  25. from tests.support.mixins import AdaptedConfigurationTestCaseMixin
  26. from tests.support.mock import MagicMock, Mock, patch
  27. from tests.support.runtests import RUNTIME_VARS
  28. from tests.support.unit import TestCase, skipIf
  29. log = logging.getLogger(__name__)
  30. SAMPLE_CONF_DIR = os.path.join(RUNTIME_VARS.CODE_DIR, "conf") + os.sep
  31. # mock hostname should be more complex than the systems FQDN
  32. MOCK_HOSTNAME = "very.long.complex.fqdn.that.is.crazy.extra.long.example.com"
  33. MOCK_ETC_HOSTS = textwrap.dedent(
  34. """\
  35. ##
  36. # Host Database
  37. #
  38. # localhost is used to configure the loopback interface
  39. # when the system is booting. Do not change this entry.
  40. ## The empty line below must remain, it factors into the tests.
  41. 127.0.0.1 localhost {hostname}
  42. 10.0.0.100 {hostname}
  43. 200.200.200.2 other.host.alias.com
  44. ::1 ip6-localhost ip6-loopback
  45. fe00::0 ip6-localnet
  46. ff00::0 ip6-mcastprefix
  47. """.format(
  48. hostname=MOCK_HOSTNAME
  49. )
  50. )
  51. MOCK_ETC_HOSTNAME = "{}\n".format(MOCK_HOSTNAME)
  52. PATH = "path/to/some/cloud/conf/file"
  53. DEFAULT = {"default_include": PATH}
  54. class DefaultConfigsBase(object):
  55. @classmethod
  56. def setUpClass(cls):
  57. cls.mock_master_default_opts = dict(
  58. root_dir=RUNTIME_VARS.TMP_ROOT_DIR,
  59. log_file=os.path.join(
  60. RUNTIME_VARS.TMP_ROOT_DIR, "var", "log", "salt", "master"
  61. ),
  62. pid_file=os.path.join(
  63. RUNTIME_VARS.TMP_ROOT_DIR, "var", "run", "salt-master.pid"
  64. ),
  65. )
  66. class SampleConfTest(DefaultConfigsBase, TestCase):
  67. """
  68. Validate files in the salt/conf directory.
  69. """
  70. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  71. def test_conf_master_sample_is_commented(self):
  72. """
  73. The sample config file located in salt/conf/master must be completely
  74. commented out. This test checks for any lines that are not commented or blank.
  75. """
  76. master_config = SAMPLE_CONF_DIR + "master"
  77. ret = salt.config._read_conf_file(master_config)
  78. self.assertEqual(
  79. ret,
  80. {},
  81. "Sample config file '{}' must be commented out.".format(master_config),
  82. )
  83. def test_conf_minion_sample_is_commented(self):
  84. """
  85. The sample config file located in salt/conf/minion must be completely
  86. commented out. This test checks for any lines that are not commented or blank.
  87. """
  88. minion_config = SAMPLE_CONF_DIR + "minion"
  89. ret = salt.config._read_conf_file(minion_config)
  90. self.assertEqual(
  91. ret,
  92. {},
  93. "Sample config file '{}' must be commented out.".format(minion_config),
  94. )
  95. def test_conf_cloud_sample_is_commented(self):
  96. """
  97. The sample config file located in salt/conf/cloud must be completely
  98. commented out. This test checks for any lines that are not commented or blank.
  99. """
  100. cloud_config = SAMPLE_CONF_DIR + "cloud"
  101. ret = salt.config._read_conf_file(cloud_config)
  102. self.assertEqual(
  103. ret,
  104. {},
  105. "Sample config file '{}' must be commented out.".format(cloud_config),
  106. )
  107. def test_conf_cloud_profiles_sample_is_commented(self):
  108. """
  109. The sample config file located in salt/conf/cloud.profiles must be completely
  110. commented out. This test checks for any lines that are not commented or blank.
  111. """
  112. cloud_profiles_config = SAMPLE_CONF_DIR + "cloud.profiles"
  113. ret = salt.config._read_conf_file(cloud_profiles_config)
  114. self.assertEqual(
  115. ret,
  116. {},
  117. "Sample config file '{}' must be commented out.".format(
  118. cloud_profiles_config
  119. ),
  120. )
  121. def test_conf_cloud_providers_sample_is_commented(self):
  122. """
  123. The sample config file located in salt/conf/cloud.providers must be completely
  124. commented out. This test checks for any lines that are not commented or blank.
  125. """
  126. cloud_providers_config = SAMPLE_CONF_DIR + "cloud.providers"
  127. ret = salt.config._read_conf_file(cloud_providers_config)
  128. self.assertEqual(
  129. ret,
  130. {},
  131. "Sample config file '{}' must be commented out.".format(
  132. cloud_providers_config
  133. ),
  134. )
  135. def test_conf_proxy_sample_is_commented(self):
  136. """
  137. The sample config file located in salt/conf/proxy must be completely
  138. commented out. This test checks for any lines that are not commented or blank.
  139. """
  140. proxy_config = SAMPLE_CONF_DIR + "proxy"
  141. ret = salt.config._read_conf_file(proxy_config)
  142. self.assertEqual(
  143. ret,
  144. {},
  145. "Sample config file '{}' must be commented out.".format(proxy_config),
  146. )
  147. def test_conf_roster_sample_is_commented(self):
  148. """
  149. The sample config file located in salt/conf/roster must be completely
  150. commented out. This test checks for any lines that are not commented or blank.
  151. """
  152. roster_config = SAMPLE_CONF_DIR + "roster"
  153. ret = salt.config._read_conf_file(roster_config)
  154. self.assertEqual(
  155. ret,
  156. {},
  157. "Sample config file '{}' must be commented out.".format(roster_config),
  158. )
  159. def test_conf_cloud_profiles_d_files_are_commented(self):
  160. """
  161. All cloud profile sample configs in salt/conf/cloud.profiles.d/* must be completely
  162. commented out. This test loops through all of the files in that directory to check
  163. for any lines that are not commented or blank.
  164. """
  165. cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.profiles.d/"
  166. if not os.path.exists(cloud_sample_dir):
  167. self.skipTest(
  168. "Sample config directory '{}' is missing.".format(cloud_sample_dir)
  169. )
  170. cloud_sample_files = os.listdir(cloud_sample_dir)
  171. for conf_file in cloud_sample_files:
  172. profile_conf = cloud_sample_dir + conf_file
  173. ret = salt.config._read_conf_file(profile_conf)
  174. self.assertEqual(
  175. ret,
  176. {},
  177. "Sample config file '{}' must be commented out.".format(conf_file),
  178. )
  179. def test_conf_cloud_providers_d_files_are_commented(self):
  180. """
  181. All cloud profile sample configs in salt/conf/cloud.providers.d/* must be completely
  182. commented out. This test loops through all of the files in that directory to check
  183. for any lines that are not commented or blank.
  184. """
  185. cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.providers.d/"
  186. if not os.path.exists(cloud_sample_dir):
  187. self.skipTest(
  188. "Sample config directory '{}' is missing.".format(cloud_sample_dir)
  189. )
  190. cloud_sample_files = os.listdir(cloud_sample_dir)
  191. for conf_file in cloud_sample_files:
  192. provider_conf = cloud_sample_dir + conf_file
  193. ret = salt.config._read_conf_file(provider_conf)
  194. self.assertEqual(
  195. ret,
  196. {},
  197. "Sample config file '{}' must be commented out.".format(conf_file),
  198. )
  199. def test_conf_cloud_maps_d_files_are_commented(self):
  200. """
  201. All cloud profile sample configs in salt/conf/cloud.maps.d/* must be completely
  202. commented out. This test loops through all of the files in that directory to check
  203. for any lines that are not commented or blank.
  204. """
  205. cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.maps.d/"
  206. if not os.path.exists(cloud_sample_dir):
  207. self.skipTest(
  208. "Sample config directory '{}' is missing.".format(cloud_sample_dir)
  209. )
  210. cloud_sample_files = os.listdir(cloud_sample_dir)
  211. for conf_file in cloud_sample_files:
  212. map_conf = cloud_sample_dir + conf_file
  213. ret = salt.config._read_conf_file(map_conf)
  214. self.assertEqual(
  215. ret,
  216. {},
  217. "Sample config file '{}' must be commented out.".format(conf_file),
  218. )
  219. def _unhandled_mock_read(filename):
  220. """
  221. Raise an error because we should not be calling salt.utils.files.fopen()
  222. """
  223. raise CommandExecutionError("Unhandled mock read for {}".format(filename))
  224. def _salt_configuration_error(filename):
  225. """
  226. Raise an error to indicate error in the Salt configuration file
  227. """
  228. raise SaltConfigurationError("Configuration error in {}".format(filename))
  229. class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin):
  230. @with_tempfile()
  231. def test_sha256_is_default_for_master(self, fpath):
  232. with salt.utils.files.fopen(fpath, "w") as wfh:
  233. wfh.write("root_dir: /\n" "key_logfile: key\n")
  234. config = salt.config.master_config(fpath)
  235. self.assertEqual(config["hash_type"], "sha256")
  236. @with_tempfile()
  237. def test_sha256_is_default_for_minion(self, fpath):
  238. with salt.utils.files.fopen(fpath, "w") as wfh:
  239. wfh.write("root_dir: /\n" "key_logfile: key\n")
  240. config = salt.config.minion_config(fpath)
  241. self.assertEqual(config["hash_type"], "sha256")
  242. @with_tempfile()
  243. def test_proper_path_joining(self, fpath):
  244. temp_config = "root_dir: /\n" "key_logfile: key\n"
  245. if salt.utils.platform.is_windows():
  246. temp_config = "root_dir: c:\\\n" "key_logfile: key\n"
  247. with salt.utils.files.fopen(fpath, "w") as fp_:
  248. fp_.write(temp_config)
  249. config = salt.config.master_config(fpath)
  250. expect_path_join = os.path.join("/", "key")
  251. expect_sep_join = "//key"
  252. if salt.utils.platform.is_windows():
  253. expect_path_join = os.path.join("c:\\", "key")
  254. expect_sep_join = "c:\\\\key"
  255. # os.path.join behavior
  256. self.assertEqual(config["key_logfile"], expect_path_join)
  257. # os.sep.join behavior
  258. self.assertNotEqual(config["key_logfile"], expect_sep_join)
  259. @with_tempdir()
  260. def test_common_prefix_stripping(self, tempdir):
  261. root_dir = os.path.join(tempdir, "foo", "bar")
  262. os.makedirs(root_dir)
  263. fpath = os.path.join(root_dir, "config")
  264. with salt.utils.files.fopen(fpath, "w") as fp_:
  265. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  266. config = salt.config.master_config(fpath)
  267. self.assertEqual(config["log_file"], fpath)
  268. @with_tempdir()
  269. def test_default_root_dir_included_in_config_root_dir(self, tempdir):
  270. root_dir = os.path.join(tempdir, "foo", "bar")
  271. os.makedirs(root_dir)
  272. fpath = os.path.join(root_dir, "config")
  273. with salt.utils.files.fopen(fpath, "w") as fp_:
  274. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  275. config = salt.config.master_config(fpath)
  276. self.assertEqual(config["log_file"], fpath)
  277. @skipIf(
  278. salt.utils.platform.is_windows(),
  279. "You can't set an environment dynamically in Windows",
  280. )
  281. @with_tempdir()
  282. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  283. def test_load_master_config_from_environ_var(self, tempdir):
  284. env_root_dir = os.path.join(tempdir, "foo", "env")
  285. os.makedirs(env_root_dir)
  286. env_fpath = os.path.join(env_root_dir, "config-env")
  287. with salt.utils.files.fopen(env_fpath, "w") as fp_:
  288. fp_.write("root_dir: {}\n" "log_file: {}\n".format(env_root_dir, env_fpath))
  289. with patched_environ(SALT_MASTER_CONFIG=env_fpath):
  290. # Should load from env variable, not the default configuration file.
  291. config = salt.config.master_config("{}/master".format(CONFIG_DIR))
  292. self.assertEqual(config["log_file"], env_fpath)
  293. root_dir = os.path.join(tempdir, "foo", "bar")
  294. os.makedirs(root_dir)
  295. fpath = os.path.join(root_dir, "config")
  296. with salt.utils.files.fopen(fpath, "w") as fp_:
  297. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  298. # Let's set the environment variable, yet, since the configuration
  299. # file path is not the default one, i.e., the user has passed an
  300. # alternative configuration file form the CLI parser, the
  301. # environment variable will be ignored.
  302. with patched_environ(SALT_MASTER_CONFIG=env_fpath):
  303. config = salt.config.master_config(fpath)
  304. self.assertEqual(config["log_file"], fpath)
  305. @skipIf(
  306. salt.utils.platform.is_windows(),
  307. "You can't set an environment dynamically in Windows",
  308. )
  309. @with_tempdir()
  310. def test_load_minion_config_from_environ_var(self, tempdir):
  311. env_root_dir = os.path.join(tempdir, "foo", "env")
  312. os.makedirs(env_root_dir)
  313. env_fpath = os.path.join(env_root_dir, "config-env")
  314. with salt.utils.files.fopen(env_fpath, "w") as fp_:
  315. fp_.write("root_dir: {}\n" "log_file: {}\n".format(env_root_dir, env_fpath))
  316. with patched_environ(SALT_MINION_CONFIG=env_fpath):
  317. # Should load from env variable, not the default configuration file
  318. config = salt.config.minion_config("{}/minion".format(CONFIG_DIR))
  319. self.assertEqual(config["log_file"], env_fpath)
  320. root_dir = os.path.join(tempdir, "foo", "bar")
  321. os.makedirs(root_dir)
  322. fpath = os.path.join(root_dir, "config")
  323. with salt.utils.files.fopen(fpath, "w") as fp_:
  324. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  325. # Let's set the environment variable, yet, since the configuration
  326. # file path is not the default one, i.e., the user has passed an
  327. # alternative configuration file form the CLI parser, the
  328. # environment variable will be ignored.
  329. with patched_environ(SALT_MINION_CONFIG=env_fpath):
  330. config = salt.config.minion_config(fpath)
  331. self.assertEqual(config["log_file"], fpath)
  332. @with_tempdir()
  333. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  334. def test_load_client_config_from_environ_var(self, tempdir):
  335. env_root_dir = os.path.join(tempdir, "foo", "env")
  336. os.makedirs(env_root_dir)
  337. # Let's populate a master configuration file which should not get
  338. # picked up since the client configuration tries to load the master
  339. # configuration settings using the provided client configuration
  340. # file
  341. master_config = os.path.join(env_root_dir, "master")
  342. with salt.utils.files.fopen(master_config, "w") as fp_:
  343. fp_.write(
  344. "blah: true\n"
  345. "root_dir: {}\n"
  346. "log_file: {}\n".format(env_root_dir, master_config)
  347. )
  348. # Now the client configuration file
  349. env_fpath = os.path.join(env_root_dir, "config-env")
  350. with salt.utils.files.fopen(env_fpath, "w") as fp_:
  351. fp_.write("root_dir: {}\n" "log_file: {}\n".format(env_root_dir, env_fpath))
  352. with patched_environ(
  353. SALT_MASTER_CONFIG=master_config, SALT_CLIENT_CONFIG=env_fpath
  354. ):
  355. # Should load from env variable, not the default configuration file
  356. config = salt.config.client_config(os.path.expanduser("~/.salt"))
  357. self.assertEqual(config["log_file"], env_fpath)
  358. self.assertTrue("blah" not in config)
  359. root_dir = os.path.join(tempdir, "foo", "bar")
  360. os.makedirs(root_dir)
  361. fpath = os.path.join(root_dir, "config")
  362. with salt.utils.files.fopen(fpath, "w") as fp_:
  363. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  364. # Let's set the environment variable, yet, since the configuration
  365. # file path is not the default one, i.e., the user has passed an
  366. # alternative configuration file form the CLI parser, the
  367. # environment variable will be ignored.
  368. with patched_environ(
  369. SALT_MASTER_CONFIG=env_fpath, SALT_CLIENT_CONFIG=env_fpath
  370. ):
  371. config = salt.config.master_config(fpath)
  372. self.assertEqual(config["log_file"], fpath)
  373. @with_tempdir()
  374. def test_issue_5970_minion_confd_inclusion(self, tempdir):
  375. minion_config = os.path.join(tempdir, "minion")
  376. minion_confd = os.path.join(tempdir, "minion.d")
  377. os.makedirs(minion_confd)
  378. # Let's populate a minion configuration file with some basic
  379. # settings
  380. with salt.utils.files.fopen(minion_config, "w") as fp_:
  381. fp_.write(
  382. "blah: false\n"
  383. "root_dir: {}\n"
  384. "log_file: {}\n".format(tempdir, minion_config)
  385. )
  386. # Now, let's populate an extra configuration file under minion.d
  387. # Notice that above we've set blah as False and below as True.
  388. # Since the minion.d files are loaded after the main configuration
  389. # file so overrides can happen, the final value of blah should be
  390. # True.
  391. extra_config = os.path.join(minion_confd, "extra.conf")
  392. with salt.utils.files.fopen(extra_config, "w") as fp_:
  393. fp_.write("blah: true\n")
  394. # Let's load the configuration
  395. config = salt.config.minion_config(minion_config)
  396. self.assertEqual(config["log_file"], minion_config)
  397. # As proven by the assertion below, blah is True
  398. self.assertTrue(config["blah"])
  399. @with_tempdir()
  400. def test_master_confd_inclusion(self, tempdir):
  401. master_config = os.path.join(tempdir, "master")
  402. master_confd = os.path.join(tempdir, "master.d")
  403. os.makedirs(master_confd)
  404. # Let's populate a master configuration file with some basic
  405. # settings
  406. with salt.utils.files.fopen(master_config, "w") as fp_:
  407. fp_.write(
  408. "blah: false\n"
  409. "root_dir: {}\n"
  410. "log_file: {}\n".format(tempdir, master_config)
  411. )
  412. # Now, let's populate an extra configuration file under master.d
  413. # Notice that above we've set blah as False and below as True.
  414. # Since the master.d files are loaded after the main configuration
  415. # file so overrides can happen, the final value of blah should be
  416. # True.
  417. extra_config = os.path.join(master_confd, "extra.conf")
  418. with salt.utils.files.fopen(extra_config, "w") as fp_:
  419. fp_.write("blah: true\n")
  420. # Let's load the configuration
  421. config = salt.config.master_config(master_config)
  422. self.assertEqual(config["log_file"], master_config)
  423. # As proven by the assertion below, blah is True
  424. self.assertTrue(config["blah"])
  425. @with_tempfile()
  426. @with_tempdir()
  427. def test_master_file_roots_glob(self, tempdir, fpath):
  428. # Create some files
  429. for f in "abc":
  430. fpath = os.path.join(tempdir, f)
  431. with salt.utils.files.fopen(fpath, "w") as wfh:
  432. wfh.write(f)
  433. with salt.utils.files.fopen(fpath, "w") as wfh:
  434. wfh.write(
  435. "file_roots:\n"
  436. " base:\n"
  437. " - {}".format(os.path.join(tempdir, "*"))
  438. )
  439. config = salt.config.master_config(fpath)
  440. base = config["file_roots"]["base"]
  441. self.assertEqual(
  442. set(base),
  443. {
  444. os.path.join(tempdir, "a"),
  445. os.path.join(tempdir, "b"),
  446. os.path.join(tempdir, "c"),
  447. },
  448. )
  449. def test_validate_bad_file_roots(self):
  450. expected = salt.config._expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])
  451. with patch("salt.config._normalize_roots") as mk:
  452. ret = salt.config._validate_file_roots(None)
  453. assert not mk.called
  454. assert ret == {"base": expected}
  455. @with_tempfile()
  456. @with_tempdir()
  457. def test_master_pillar_roots_glob(self, tempdir, fpath):
  458. # Create some files.
  459. for f in "abc":
  460. fpath = os.path.join(tempdir, f)
  461. with salt.utils.files.fopen(fpath, "w") as wfh:
  462. wfh.write(f)
  463. with salt.utils.files.fopen(fpath, "w") as wfh:
  464. wfh.write(
  465. "pillar_roots:\n"
  466. " base:\n"
  467. " - {}".format(os.path.join(tempdir, "*"))
  468. )
  469. config = salt.config.master_config(fpath)
  470. base = config["pillar_roots"]["base"]
  471. self.assertEqual(
  472. set(base),
  473. {
  474. os.path.join(tempdir, "a"),
  475. os.path.join(tempdir, "b"),
  476. os.path.join(tempdir, "c"),
  477. },
  478. )
  479. def test_validate_bad_pillar_roots(self):
  480. expected = salt.config._expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])
  481. with patch("salt.config._normalize_roots") as mk:
  482. ret = salt.config._validate_pillar_roots(None)
  483. assert not mk.called
  484. assert ret == {"base": expected}
  485. @with_tempdir()
  486. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  487. def test_master_id_function(self, tempdir):
  488. master_config = os.path.join(tempdir, "master")
  489. with salt.utils.files.fopen(master_config, "w") as fp_:
  490. fp_.write(
  491. "id_function:\n"
  492. " test.echo:\n"
  493. " text: hello_world\n"
  494. "root_dir: {}\n"
  495. "log_file: {}\n".format(tempdir, master_config)
  496. )
  497. # Let's load the configuration
  498. config = salt.config.master_config(master_config)
  499. self.assertEqual(config["log_file"], master_config)
  500. # 'master_config' appends '_master' to the ID
  501. self.assertEqual(config["id"], "hello_world_master")
  502. @with_tempfile()
  503. @with_tempdir()
  504. def test_minion_file_roots_glob(self, tempdir, fpath):
  505. # Create some files.
  506. for f in "abc":
  507. fpath = os.path.join(tempdir, f)
  508. with salt.utils.files.fopen(fpath, "w") as wfh:
  509. wfh.write(f)
  510. with salt.utils.files.fopen(fpath, "w") as wfh:
  511. wfh.write(
  512. "file_roots:\n"
  513. " base:\n"
  514. " - {}".format(os.path.join(tempdir, "*"))
  515. )
  516. config = salt.config.minion_config(fpath)
  517. base = config["file_roots"]["base"]
  518. self.assertEqual(
  519. set(base),
  520. {
  521. os.path.join(tempdir, "a"),
  522. os.path.join(tempdir, "b"),
  523. os.path.join(tempdir, "c"),
  524. },
  525. )
  526. @with_tempfile()
  527. @with_tempdir()
  528. def test_minion_pillar_roots_glob(self, tempdir, fpath):
  529. # Create some files.
  530. for f in "abc":
  531. fpath = os.path.join(tempdir, f)
  532. with salt.utils.files.fopen(fpath, "w") as wfh:
  533. wfh.write(f)
  534. with salt.utils.files.fopen(fpath, "w") as wfh:
  535. wfh.write(
  536. "pillar_roots:\n"
  537. " base:\n"
  538. " - {}".format(os.path.join(tempdir, "*"))
  539. )
  540. config = salt.config.minion_config(fpath)
  541. base = config["pillar_roots"]["base"]
  542. self.assertEqual(
  543. set(base),
  544. {
  545. os.path.join(tempdir, "a"),
  546. os.path.join(tempdir, "b"),
  547. os.path.join(tempdir, "c"),
  548. },
  549. )
  550. @with_tempdir()
  551. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  552. def test_minion_id_function(self, tempdir):
  553. minion_config = os.path.join(tempdir, "minion")
  554. with salt.utils.files.fopen(minion_config, "w") as fp_:
  555. fp_.write(
  556. "id_function:\n"
  557. " test.echo:\n"
  558. " text: hello_world\n"
  559. "root_dir: {}\n"
  560. "log_file: {}\n".format(tempdir, minion_config)
  561. )
  562. # Let's load the configuration
  563. config = salt.config.minion_config(minion_config)
  564. self.assertEqual(config["log_file"], minion_config)
  565. self.assertEqual(config["id"], "hello_world")
  566. @with_tempdir()
  567. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  568. def test_minion_id_lowercase(self, tempdir):
  569. """
  570. This tests that setting `minion_id_lowercase: True` does lower case
  571. the minion id. Lowercase does not operate on a static `id: KING_BOB`
  572. setting, or a cached id.
  573. """
  574. minion_config = os.path.join(tempdir, "minion")
  575. with salt.utils.files.fopen(minion_config, "w") as fp_:
  576. fp_.write(
  577. textwrap.dedent(
  578. """\
  579. id_function:
  580. test.echo:
  581. text: KING_BOB
  582. minion_id_caching: False
  583. minion_id_lowercase: True
  584. """
  585. )
  586. )
  587. config = salt.config.minion_config(minion_config) # Load the configuration
  588. self.assertEqual(config["minion_id_caching"], False) # Check the configuration
  589. self.assertEqual(config["minion_id_lowercase"], True) # Check the configuration
  590. self.assertEqual(config["id"], "king_bob")
  591. @with_tempdir()
  592. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  593. def test_minion_id_remove_domain_string_positive(self, tempdir):
  594. """
  595. This tests that the values of `minion_id_remove_domain` is suppressed from a generated minion id,
  596. effectivly generating a hostname minion_id.
  597. """
  598. minion_config = os.path.join(tempdir, "minion")
  599. with salt.utils.files.fopen(minion_config, "w") as fp_:
  600. fp_.write(
  601. textwrap.dedent(
  602. """\
  603. id_function:
  604. test.echo:
  605. text: king_bob.foo.org
  606. minion_id_remove_domain: foo.org
  607. minion_id_caching: False
  608. """
  609. )
  610. )
  611. # Let's load the configuration
  612. config = salt.config.minion_config(minion_config)
  613. self.assertEqual(config["minion_id_remove_domain"], "foo.org")
  614. self.assertEqual(config["id"], "king_bob")
  615. @with_tempdir()
  616. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  617. def test_minion_id_remove_domain_string_negative(self, tempdir):
  618. """
  619. See above
  620. """
  621. minion_config = os.path.join(tempdir, "minion")
  622. with salt.utils.files.fopen(minion_config, "w") as fp_:
  623. fp_.write(
  624. textwrap.dedent(
  625. """\
  626. id_function:
  627. test.echo:
  628. text: king_bob.foo.org
  629. minion_id_remove_domain: bar.org
  630. minion_id_caching: False
  631. """
  632. )
  633. )
  634. config = salt.config.minion_config(minion_config)
  635. self.assertEqual(config["id"], "king_bob.foo.org")
  636. @with_tempdir()
  637. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  638. def test_minion_id_remove_domain_bool_true(self, tempdir):
  639. """
  640. See above
  641. """
  642. minion_config = os.path.join(tempdir, "minion")
  643. with salt.utils.files.fopen(minion_config, "w") as fp_:
  644. fp_.write(
  645. textwrap.dedent(
  646. """\
  647. id_function:
  648. test.echo:
  649. text: king_bob.foo.org
  650. minion_id_remove_domain: True
  651. minion_id_caching: False
  652. """
  653. )
  654. )
  655. config = salt.config.minion_config(minion_config)
  656. self.assertEqual(config["id"], "king_bob")
  657. @with_tempdir()
  658. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  659. def test_minion_id_remove_domain_bool_false(self, tempdir):
  660. """
  661. See above
  662. """
  663. minion_config = os.path.join(tempdir, "minion")
  664. with salt.utils.files.fopen(minion_config, "w") as fp_:
  665. fp_.write(
  666. textwrap.dedent(
  667. """\
  668. id_function:
  669. test.echo:
  670. text: king_bob.foo.org
  671. minion_id_remove_domain: False
  672. minion_id_caching: False
  673. """
  674. )
  675. )
  676. config = salt.config.minion_config(minion_config)
  677. self.assertEqual(config["id"], "king_bob.foo.org")
  678. @with_tempdir()
  679. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  680. def test_backend_rename(self, tempdir):
  681. """
  682. This tests that we successfully rename git, hg, svn, and minion to
  683. gitfs, hgfs, svnfs, and minionfs in the master and minion opts.
  684. """
  685. fpath = salt.utils.files.mkstemp(dir=tempdir)
  686. with salt.utils.files.fopen(fpath, "w") as fp_:
  687. fp_.write(
  688. textwrap.dedent(
  689. """\
  690. fileserver_backend:
  691. - roots
  692. - git
  693. - hg
  694. - svn
  695. - minion
  696. """
  697. )
  698. )
  699. master_config = salt.config.master_config(fpath)
  700. minion_config = salt.config.minion_config(fpath)
  701. expected = ["roots", "gitfs", "hgfs", "svnfs", "minionfs"]
  702. self.assertEqual(master_config["fileserver_backend"], expected)
  703. self.assertEqual(minion_config["fileserver_backend"], expected)
  704. def test_syndic_config(self):
  705. minion_conf_path = self.get_config_file_path("syndic")
  706. master_conf_path = os.path.join(os.path.dirname(minion_conf_path), "master")
  707. syndic_opts = salt.config.syndic_config(master_conf_path, minion_conf_path)
  708. root_dir = syndic_opts["root_dir"]
  709. # id & pki dir are shared & so configured on the minion side
  710. self.assertEqual(syndic_opts["id"], "syndic")
  711. self.assertEqual(syndic_opts["pki_dir"], os.path.join(root_dir, "pki"))
  712. # the rest is configured master side
  713. self.assertEqual(syndic_opts["master"], "127.0.0.1")
  714. self.assertEqual(
  715. syndic_opts["sock_dir"], os.path.join(root_dir, "run", "minion")
  716. )
  717. self.assertEqual(syndic_opts["cachedir"], os.path.join(root_dir, "cache"))
  718. self.assertEqual(
  719. syndic_opts["log_file"], os.path.join(root_dir, "logs", "syndic.log")
  720. )
  721. self.assertEqual(
  722. syndic_opts["pidfile"], os.path.join(root_dir, "run", "syndic.pid")
  723. )
  724. # Show that the options of localclient that repub to local master
  725. # are not merged with syndic ones
  726. self.assertEqual(syndic_opts["_master_conf_file"], minion_conf_path)
  727. self.assertEqual(syndic_opts["_minion_conf_file"], master_conf_path)
  728. @with_tempfile()
  729. def _get_tally(self, fpath, conf_func):
  730. """
  731. This ensures that any strings which are loaded are unicode strings
  732. """
  733. tally = {}
  734. def _count_strings(config):
  735. if isinstance(config, dict):
  736. for key, val in six.iteritems(config):
  737. log.debug("counting strings in dict key: %s", key)
  738. log.debug("counting strings in dict val: %s", val)
  739. _count_strings(key)
  740. _count_strings(val)
  741. elif isinstance(config, list):
  742. log.debug("counting strings in list: %s", config)
  743. for item in config:
  744. _count_strings(item)
  745. else:
  746. if isinstance(config, six.string_types):
  747. if isinstance(config, six.text_type):
  748. tally["unicode"] = tally.get("unicode", 0) + 1
  749. else:
  750. # We will never reach this on PY3
  751. tally.setdefault("non_unicode", []).append(config)
  752. with salt.utils.files.fopen(fpath, "w") as wfh:
  753. wfh.write(
  754. textwrap.dedent(
  755. """
  756. foo: bar
  757. mylist:
  758. - somestring
  759. - 9
  760. - 123.456
  761. - True
  762. - nested:
  763. - key: val
  764. - nestedlist:
  765. - foo
  766. - bar
  767. - baz
  768. mydict:
  769. - somestring: 9
  770. - 123.456: 789
  771. - True: False
  772. - nested:
  773. - key: val
  774. - nestedlist:
  775. - foo
  776. - bar
  777. - baz"""
  778. )
  779. )
  780. if conf_func is salt.config.master_config:
  781. wfh.write("\n\n")
  782. wfh.write(
  783. textwrap.dedent(
  784. """
  785. rest_cherrypy:
  786. port: 8000
  787. disable_ssl: True
  788. app_path: /beacon_demo
  789. app: /srv/web/html/index.html
  790. static: /srv/web/static"""
  791. )
  792. )
  793. config = conf_func(fpath)
  794. _count_strings(config)
  795. return tally
  796. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  797. def test_conf_file_strings_are_unicode_for_master(self):
  798. """
  799. This ensures that any strings which are loaded are unicode strings
  800. """
  801. # pylint: disable=no-value-for-parameter
  802. tally = self._get_tally(salt.config.master_config)
  803. # pylint: enable=no-value-for-parameter
  804. non_unicode = tally.get("non_unicode", [])
  805. self.assertEqual(len(non_unicode), 8 if six.PY2 else 0, non_unicode)
  806. self.assertTrue(tally["unicode"] > 0)
  807. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  808. def test_conf_file_strings_are_unicode_for_minion(self):
  809. """
  810. This ensures that any strings which are loaded are unicode strings
  811. """
  812. # pylint: disable=no-value-for-parameter
  813. tally = self._get_tally(salt.config.minion_config)
  814. # pylint: enable=no-value-for-parameter
  815. non_unicode = tally.get("non_unicode", [])
  816. self.assertEqual(len(non_unicode), 0, non_unicode)
  817. self.assertTrue(tally["unicode"] > 0)
  818. # <---- Salt Cloud Configuration Tests ---------------------------------------------
  819. # cloud_config tests
  820. def test_cloud_config_double_master_path(self):
  821. """
  822. Tests passing in master_config_path and master_config kwargs.
  823. """
  824. with patch("salt.config.load_config", MagicMock(return_value={})):
  825. self.assertRaises(
  826. SaltCloudConfigError,
  827. salt.config.cloud_config,
  828. PATH,
  829. master_config_path="foo",
  830. master_config="bar",
  831. )
  832. def test_cloud_config_double_providers_path(self):
  833. """
  834. Tests passing in providers_config_path and providers_config kwargs.
  835. """
  836. with patch("salt.config.load_config", MagicMock(return_value={})):
  837. self.assertRaises(
  838. SaltCloudConfigError,
  839. salt.config.cloud_config,
  840. PATH,
  841. providers_config_path="foo",
  842. providers_config="bar",
  843. )
  844. def test_cloud_config_double_profiles_path(self):
  845. """
  846. Tests passing in profiles_config_path and profiles_config kwargs.
  847. """
  848. with patch("salt.config.load_config", MagicMock(return_value={})):
  849. self.assertRaises(
  850. SaltCloudConfigError,
  851. salt.config.cloud_config,
  852. PATH,
  853. profiles_config_path="foo",
  854. profiles_config="bar",
  855. )
  856. def test_cloud_config_providers_in_opts(self):
  857. """
  858. Tests mixing old cloud providers with pre-configured providers configurations
  859. using the providers_config kwarg
  860. """
  861. with patch("salt.config.load_config", MagicMock(return_value={})):
  862. with patch(
  863. "salt.config.apply_cloud_config",
  864. MagicMock(return_value={"providers": "foo"}),
  865. ):
  866. self.assertRaises(
  867. SaltCloudConfigError,
  868. salt.config.cloud_config,
  869. PATH,
  870. providers_config="bar",
  871. )
  872. def test_cloud_config_providers_in_opts_path(self):
  873. """
  874. Tests mixing old cloud providers with pre-configured providers configurations
  875. using the providers_config_path kwarg
  876. """
  877. with patch("salt.config.load_config", MagicMock(return_value={})):
  878. with patch(
  879. "salt.config.apply_cloud_config",
  880. MagicMock(return_value={"providers": "foo"}),
  881. ):
  882. with patch("os.path.isfile", MagicMock(return_value=True)):
  883. self.assertRaises(
  884. SaltCloudConfigError,
  885. salt.config.cloud_config,
  886. PATH,
  887. providers_config_path="bar",
  888. )
  889. def test_cloud_config_deploy_scripts_search_path(self):
  890. """
  891. Tests the contents of the 'deploy_scripts_search_path' tuple to ensure that
  892. the correct deploy search paths are present.
  893. There should be two search paths reported in the tuple: ``/etc/salt/cloud.deploy.d``
  894. and ``<path-to-salt-install>/salt/cloud/deploy``. The first element is usually
  895. ``/etc/salt/cloud.deploy.d``, but sometimes is can be something like
  896. ``/etc/local/salt/cloud.deploy.d``, so we'll only test against the last part of
  897. the path.
  898. """
  899. with patch("os.path.isdir", MagicMock(return_value=True)):
  900. search_paths = salt.config.cloud_config("/etc/salt/cloud").get(
  901. "deploy_scripts_search_path"
  902. )
  903. etc_deploy_path = "/salt/cloud.deploy.d"
  904. deploy_path = "/salt/cloud/deploy"
  905. if salt.utils.platform.is_windows():
  906. etc_deploy_path = "/salt\\cloud.deploy.d"
  907. deploy_path = "\\salt\\cloud\\deploy"
  908. # Check cloud.deploy.d path is the first element in the search_paths tuple
  909. self.assertTrue(search_paths[0].endswith(etc_deploy_path))
  910. # Check the second element in the search_paths tuple
  911. self.assertTrue(search_paths[1].endswith(deploy_path))
  912. # apply_cloud_config tests
  913. def test_apply_cloud_config_no_provider_detail_list(self):
  914. """
  915. Tests when the provider is not contained in a list of details
  916. """
  917. overrides = {"providers": {"foo": [{"bar": "baz"}]}}
  918. self.assertRaises(
  919. SaltCloudConfigError,
  920. salt.config.apply_cloud_config,
  921. overrides,
  922. defaults=DEFAULT,
  923. )
  924. def test_apply_cloud_config_no_provider_detail_dict(self):
  925. """
  926. Tests when the provider is not contained in the details dictionary
  927. """
  928. overrides = {"providers": {"foo": {"bar": "baz"}}}
  929. self.assertRaises(
  930. SaltCloudConfigError,
  931. salt.config.apply_cloud_config,
  932. overrides,
  933. defaults=DEFAULT,
  934. )
  935. def test_apply_cloud_config_success_list(self):
  936. """
  937. Tests success when valid data is passed into the function as a list
  938. """
  939. with patch(
  940. "salt.config.old_to_new",
  941. MagicMock(
  942. return_value={
  943. "default_include": "path/to/some/cloud/conf/file",
  944. "providers": {"foo": {"bar": {"driver": "foo:bar"}}},
  945. }
  946. ),
  947. ):
  948. overrides = {"providers": {"foo": [{"driver": "bar"}]}}
  949. ret = {
  950. "default_include": "path/to/some/cloud/conf/file",
  951. "providers": {"foo": {"bar": {"driver": "foo:bar"}}},
  952. }
  953. self.assertEqual(
  954. salt.config.apply_cloud_config(overrides, defaults=DEFAULT), ret
  955. )
  956. def test_apply_cloud_config_success_dict(self):
  957. """
  958. Tests success when valid data is passed into function as a dictionary
  959. """
  960. with patch(
  961. "salt.config.old_to_new",
  962. MagicMock(
  963. return_value={
  964. "default_include": "path/to/some/cloud/conf/file",
  965. "providers": {"foo": {"bar": {"driver": "foo:bar"}}},
  966. }
  967. ),
  968. ):
  969. overrides = {"providers": {"foo": {"driver": "bar"}}}
  970. ret = {
  971. "default_include": "path/to/some/cloud/conf/file",
  972. "providers": {"foo": {"bar": {"driver": "foo:bar"}}},
  973. }
  974. self.assertEqual(
  975. salt.config.apply_cloud_config(overrides, defaults=DEFAULT), ret
  976. )
  977. # apply_vm_profiles_config tests
  978. def test_apply_vm_profiles_config_bad_profile_format(self):
  979. """
  980. Tests passing in a bad profile format in overrides
  981. """
  982. overrides = {"foo": "bar", "conf_file": PATH}
  983. self.assertRaises(
  984. SaltCloudConfigError,
  985. salt.config.apply_vm_profiles_config,
  986. PATH,
  987. overrides,
  988. defaults=DEFAULT,
  989. )
  990. def test_apply_vm_profiles_config_success(self):
  991. """
  992. Tests passing in valid provider and profile config files successfully
  993. """
  994. providers = {
  995. "test-provider": {
  996. "digitalocean": {"driver": "digitalocean", "profiles": {}}
  997. }
  998. }
  999. overrides = {
  1000. "test-profile": {
  1001. "provider": "test-provider",
  1002. "image": "Ubuntu 12.10 x64",
  1003. "size": "512MB",
  1004. },
  1005. "conf_file": PATH,
  1006. }
  1007. ret = {
  1008. "test-profile": {
  1009. "profile": "test-profile",
  1010. "provider": "test-provider:digitalocean",
  1011. "image": "Ubuntu 12.10 x64",
  1012. "size": "512MB",
  1013. }
  1014. }
  1015. self.assertEqual(
  1016. salt.config.apply_vm_profiles_config(
  1017. providers, overrides, defaults=DEFAULT
  1018. ),
  1019. ret,
  1020. )
  1021. def test_apply_vm_profiles_config_extend_success(self):
  1022. """
  1023. Tests profile extends functionality with valid provider and profile configs
  1024. """
  1025. providers = {"test-config": {"ec2": {"profiles": {}, "driver": "ec2"}}}
  1026. overrides = {
  1027. "Amazon": {"image": "test-image-1", "extends": "dev-instances"},
  1028. "Fedora": {"image": "test-image-2", "extends": "dev-instances"},
  1029. "conf_file": PATH,
  1030. "dev-instances": {"ssh_username": "test_user", "provider": "test-config"},
  1031. }
  1032. ret = {
  1033. "Amazon": {
  1034. "profile": "Amazon",
  1035. "ssh_username": "test_user",
  1036. "image": "test-image-1",
  1037. "provider": "test-config:ec2",
  1038. },
  1039. "Fedora": {
  1040. "profile": "Fedora",
  1041. "ssh_username": "test_user",
  1042. "image": "test-image-2",
  1043. "provider": "test-config:ec2",
  1044. },
  1045. "dev-instances": {
  1046. "profile": "dev-instances",
  1047. "ssh_username": "test_user",
  1048. "provider": "test-config:ec2",
  1049. },
  1050. }
  1051. self.assertEqual(
  1052. salt.config.apply_vm_profiles_config(
  1053. providers, overrides, defaults=DEFAULT
  1054. ),
  1055. ret,
  1056. )
  1057. def test_apply_vm_profiles_config_extend_override_success(self):
  1058. """
  1059. Tests profile extends and recursively merges data elements
  1060. """
  1061. self.maxDiff = None
  1062. providers = {"test-config": {"ec2": {"profiles": {}, "driver": "ec2"}}}
  1063. overrides = {
  1064. "Fedora": {
  1065. "image": "test-image-2",
  1066. "extends": "dev-instances",
  1067. "minion": {"grains": {"stage": "experimental"}},
  1068. },
  1069. "conf_file": PATH,
  1070. "dev-instances": {
  1071. "ssh_username": "test_user",
  1072. "provider": "test-config",
  1073. "minion": {"grains": {"role": "webserver"}},
  1074. },
  1075. }
  1076. ret = {
  1077. "Fedora": {
  1078. "profile": "Fedora",
  1079. "ssh_username": "test_user",
  1080. "image": "test-image-2",
  1081. "minion": {"grains": {"role": "webserver", "stage": "experimental"}},
  1082. "provider": "test-config:ec2",
  1083. },
  1084. "dev-instances": {
  1085. "profile": "dev-instances",
  1086. "ssh_username": "test_user",
  1087. "minion": {"grains": {"role": "webserver"}},
  1088. "provider": "test-config:ec2",
  1089. },
  1090. }
  1091. self.assertEqual(
  1092. salt.config.apply_vm_profiles_config(
  1093. providers, overrides, defaults=DEFAULT
  1094. ),
  1095. ret,
  1096. )
  1097. # apply_cloud_providers_config tests
  1098. def test_apply_cloud_providers_config_same_providers(self):
  1099. """
  1100. Tests when two providers are given with the same provider name
  1101. """
  1102. overrides = {
  1103. "my-dev-envs": [
  1104. {
  1105. "id": "ABCDEFGHIJKLMNOP",
  1106. "key": "supersecretkeysupersecretkey",
  1107. "driver": "ec2",
  1108. },
  1109. {
  1110. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1111. "password": "supersecret",
  1112. "driver": "ec2",
  1113. },
  1114. ],
  1115. "conf_file": PATH,
  1116. }
  1117. self.assertRaises(
  1118. SaltCloudConfigError,
  1119. salt.config.apply_cloud_providers_config,
  1120. overrides,
  1121. DEFAULT,
  1122. )
  1123. def test_apply_cloud_providers_config_extend(self):
  1124. """
  1125. Tests the successful extension of a cloud provider
  1126. """
  1127. overrides = {
  1128. "my-production-envs": [
  1129. {
  1130. "extends": "my-dev-envs:ec2",
  1131. "location": "us-east-1",
  1132. "user": "ec2-user@mycorp.com",
  1133. }
  1134. ],
  1135. "my-dev-envs": [
  1136. {
  1137. "id": "ABCDEFGHIJKLMNOP",
  1138. "user": "user@mycorp.com",
  1139. "location": "ap-southeast-1",
  1140. "key": "supersecretkeysupersecretkey",
  1141. "driver": "ec2",
  1142. },
  1143. {
  1144. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1145. "password": "supersecret",
  1146. "driver": "linode",
  1147. },
  1148. {
  1149. "id": "a-tencentcloud-id",
  1150. "key": "a-tencentcloud-key",
  1151. "location": "ap-guangzhou",
  1152. "driver": "tencentcloud",
  1153. },
  1154. ],
  1155. "conf_file": PATH,
  1156. }
  1157. ret = {
  1158. "my-production-envs": {
  1159. "ec2": {
  1160. "profiles": {},
  1161. "location": "us-east-1",
  1162. "key": "supersecretkeysupersecretkey",
  1163. "driver": "ec2",
  1164. "id": "ABCDEFGHIJKLMNOP",
  1165. "user": "ec2-user@mycorp.com",
  1166. }
  1167. },
  1168. "my-dev-envs": {
  1169. "linode": {
  1170. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1171. "password": "supersecret",
  1172. "profiles": {},
  1173. "driver": "linode",
  1174. },
  1175. "tencentcloud": {
  1176. "id": "a-tencentcloud-id",
  1177. "key": "a-tencentcloud-key",
  1178. "location": "ap-guangzhou",
  1179. "profiles": {},
  1180. "driver": "tencentcloud",
  1181. },
  1182. "ec2": {
  1183. "profiles": {},
  1184. "location": "ap-southeast-1",
  1185. "key": "supersecretkeysupersecretkey",
  1186. "driver": "ec2",
  1187. "id": "ABCDEFGHIJKLMNOP",
  1188. "user": "user@mycorp.com",
  1189. },
  1190. },
  1191. }
  1192. self.assertEqual(
  1193. ret, salt.config.apply_cloud_providers_config(overrides, defaults=DEFAULT)
  1194. )
  1195. def test_apply_cloud_providers_config_extend_multiple(self):
  1196. """
  1197. Tests the successful extension of two cloud providers
  1198. """
  1199. overrides = {
  1200. "my-production-envs": [
  1201. {
  1202. "extends": "my-dev-envs:ec2",
  1203. "location": "us-east-1",
  1204. "user": "ec2-user@mycorp.com",
  1205. },
  1206. {
  1207. "password": "new-password",
  1208. "extends": "my-dev-envs:linode",
  1209. "location": "Salt Lake City",
  1210. },
  1211. {
  1212. "extends": "my-dev-envs:tencentcloud",
  1213. "id": "new-id",
  1214. "key": "new-key",
  1215. "location": "ap-beijing",
  1216. },
  1217. ],
  1218. "my-dev-envs": [
  1219. {
  1220. "id": "ABCDEFGHIJKLMNOP",
  1221. "user": "user@mycorp.com",
  1222. "location": "ap-southeast-1",
  1223. "key": "supersecretkeysupersecretkey",
  1224. "driver": "ec2",
  1225. },
  1226. {
  1227. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1228. "password": "supersecret",
  1229. "driver": "linode",
  1230. },
  1231. {
  1232. "id": "the-tencentcloud-id",
  1233. "location": "ap-beijing",
  1234. "key": "the-tencentcloud-key",
  1235. "driver": "tencentcloud",
  1236. },
  1237. ],
  1238. "conf_file": PATH,
  1239. }
  1240. ret = {
  1241. "my-production-envs": {
  1242. "linode": {
  1243. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1244. "profiles": {},
  1245. "location": "Salt Lake City",
  1246. "driver": "linode",
  1247. "password": "new-password",
  1248. },
  1249. "ec2": {
  1250. "user": "ec2-user@mycorp.com",
  1251. "key": "supersecretkeysupersecretkey",
  1252. "driver": "ec2",
  1253. "id": "ABCDEFGHIJKLMNOP",
  1254. "profiles": {},
  1255. "location": "us-east-1",
  1256. },
  1257. "tencentcloud": {
  1258. "id": "new-id",
  1259. "key": "new-key",
  1260. "location": "ap-beijing",
  1261. "profiles": {},
  1262. "driver": "tencentcloud",
  1263. },
  1264. },
  1265. "my-dev-envs": {
  1266. "linode": {
  1267. "apikey": "abcdefghijklmnopqrstuvwxyz",
  1268. "password": "supersecret",
  1269. "profiles": {},
  1270. "driver": "linode",
  1271. },
  1272. "ec2": {
  1273. "profiles": {},
  1274. "user": "user@mycorp.com",
  1275. "key": "supersecretkeysupersecretkey",
  1276. "driver": "ec2",
  1277. "id": "ABCDEFGHIJKLMNOP",
  1278. "location": "ap-southeast-1",
  1279. },
  1280. "tencentcloud": {
  1281. "id": "the-tencentcloud-id",
  1282. "key": "the-tencentcloud-key",
  1283. "location": "ap-beijing",
  1284. "profiles": {},
  1285. "driver": "tencentcloud",
  1286. },
  1287. },
  1288. }
  1289. self.assertEqual(
  1290. ret, salt.config.apply_cloud_providers_config(overrides, defaults=DEFAULT)
  1291. )
  1292. def test_apply_cloud_providers_config_extends_bad_alias(self):
  1293. """
  1294. Tests when the extension contains an alias not found in providers list
  1295. """
  1296. overrides = {
  1297. "my-production-envs": [
  1298. {
  1299. "extends": "test-alias:ec2",
  1300. "location": "us-east-1",
  1301. "user": "ec2-user@mycorp.com",
  1302. }
  1303. ],
  1304. "my-dev-envs": [
  1305. {
  1306. "id": "ABCDEFGHIJKLMNOP",
  1307. "user": "user@mycorp.com",
  1308. "location": "ap-southeast-1",
  1309. "key": "supersecretkeysupersecretkey",
  1310. "driver": "ec2",
  1311. }
  1312. ],
  1313. "conf_file": PATH,
  1314. }
  1315. self.assertRaises(
  1316. SaltCloudConfigError,
  1317. salt.config.apply_cloud_providers_config,
  1318. overrides,
  1319. DEFAULT,
  1320. )
  1321. def test_apply_cloud_providers_config_extends_bad_provider(self):
  1322. """
  1323. Tests when the extension contains a provider not found in providers list
  1324. """
  1325. overrides = {
  1326. "my-production-envs": [
  1327. {
  1328. "extends": "my-dev-envs:linode",
  1329. "location": "us-east-1",
  1330. "user": "ec2-user@mycorp.com",
  1331. },
  1332. {
  1333. "extends": "my-dev-envs:tencentcloud",
  1334. "location": "ap-shanghai",
  1335. "id": "the-tencentcloud-id",
  1336. },
  1337. ],
  1338. "my-dev-envs": [
  1339. {
  1340. "id": "ABCDEFGHIJKLMNOP",
  1341. "user": "user@mycorp.com",
  1342. "location": "ap-southeast-1",
  1343. "key": "supersecretkeysupersecretkey",
  1344. "driver": "ec2",
  1345. }
  1346. ],
  1347. "conf_file": PATH,
  1348. }
  1349. self.assertRaises(
  1350. SaltCloudConfigError,
  1351. salt.config.apply_cloud_providers_config,
  1352. overrides,
  1353. DEFAULT,
  1354. )
  1355. def test_apply_cloud_providers_config_extends_no_provider(self):
  1356. """
  1357. Tests when no provider is supplied in the extends statement
  1358. """
  1359. overrides = {
  1360. "my-production-envs": [
  1361. {
  1362. "extends": "my-dev-envs",
  1363. "location": "us-east-1",
  1364. "user": "ec2-user@mycorp.com",
  1365. },
  1366. {
  1367. "extends": "my-dev-envs:tencentcloud",
  1368. "location": "ap-shanghai",
  1369. "id": "the-tencentcloud-id",
  1370. },
  1371. ],
  1372. "my-dev-envs": [
  1373. {
  1374. "id": "ABCDEFGHIJKLMNOP",
  1375. "user": "user@mycorp.com",
  1376. "location": "ap-southeast-1",
  1377. "key": "supersecretkeysupersecretkey",
  1378. "driver": "linode",
  1379. }
  1380. ],
  1381. "conf_file": PATH,
  1382. }
  1383. self.assertRaises(
  1384. SaltCloudConfigError,
  1385. salt.config.apply_cloud_providers_config,
  1386. overrides,
  1387. DEFAULT,
  1388. )
  1389. def test_apply_cloud_providers_extends_not_in_providers(self):
  1390. """
  1391. Tests when extends is not in the list of providers
  1392. """
  1393. overrides = {
  1394. "my-production-envs": [
  1395. {
  1396. "extends": "my-dev-envs ec2",
  1397. "location": "us-east-1",
  1398. "user": "ec2-user@mycorp.com",
  1399. }
  1400. ],
  1401. "my-dev-envs": [
  1402. {
  1403. "id": "ABCDEFGHIJKLMNOP",
  1404. "user": "user@mycorp.com",
  1405. "location": "ap-southeast-1",
  1406. "key": "supersecretkeysupersecretkey",
  1407. "driver": "linode",
  1408. },
  1409. {
  1410. "id": "a-tencentcloud-id",
  1411. "key": "a-tencentcloud-key",
  1412. "location": "ap-guangzhou",
  1413. "driver": "tencentcloud",
  1414. },
  1415. ],
  1416. "conf_file": PATH,
  1417. }
  1418. self.assertRaises(
  1419. SaltCloudConfigError,
  1420. salt.config.apply_cloud_providers_config,
  1421. overrides,
  1422. DEFAULT,
  1423. )
  1424. # is_provider_configured tests
  1425. def test_is_provider_configured_no_alias(self):
  1426. """
  1427. Tests when provider alias is not in opts
  1428. """
  1429. opts = {"providers": "test"}
  1430. provider = "foo:bar"
  1431. self.assertFalse(salt.config.is_provider_configured(opts, provider))
  1432. def test_is_provider_configured_no_driver(self):
  1433. """
  1434. Tests when provider driver is not in opts
  1435. """
  1436. opts = {"providers": {"foo": "baz"}}
  1437. provider = "foo:bar"
  1438. self.assertFalse(salt.config.is_provider_configured(opts, provider))
  1439. def test_is_provider_configured_key_is_none(self):
  1440. """
  1441. Tests when a required configuration key is not set
  1442. """
  1443. opts = {"providers": {"foo": {"bar": {"api_key": None}}}}
  1444. provider = "foo:bar"
  1445. self.assertFalse(
  1446. salt.config.is_provider_configured(
  1447. opts, provider, required_keys=("api_key",)
  1448. )
  1449. )
  1450. def test_is_provider_configured_success(self):
  1451. """
  1452. Tests successful cloud provider configuration
  1453. """
  1454. opts = {"providers": {"foo": {"bar": {"api_key": "baz"}}}}
  1455. provider = "foo:bar"
  1456. ret = {"api_key": "baz"}
  1457. self.assertEqual(
  1458. salt.config.is_provider_configured(
  1459. opts, provider, required_keys=("api_key",)
  1460. ),
  1461. ret,
  1462. )
  1463. def test_is_provider_configured_multiple_driver_not_provider(self):
  1464. """
  1465. Tests when the drive is not the same as the provider when
  1466. searching through multiple providers
  1467. """
  1468. opts = {"providers": {"foo": {"bar": {"api_key": "baz"}}}}
  1469. provider = "foo"
  1470. self.assertFalse(salt.config.is_provider_configured(opts, provider))
  1471. def test_is_provider_configured_multiple_key_is_none(self):
  1472. """
  1473. Tests when a required configuration key is not set when
  1474. searching through multiple providers
  1475. """
  1476. opts = {"providers": {"foo": {"bar": {"api_key": None}}}}
  1477. provider = "bar"
  1478. self.assertFalse(
  1479. salt.config.is_provider_configured(
  1480. opts, provider, required_keys=("api_key",)
  1481. )
  1482. )
  1483. def test_is_provider_configured_multiple_success(self):
  1484. """
  1485. Tests successful cloud provider configuration when searching
  1486. through multiple providers
  1487. """
  1488. opts = {"providers": {"foo": {"bar": {"api_key": "baz"}}}}
  1489. provider = "bar"
  1490. ret = {"api_key": "baz"}
  1491. self.assertEqual(
  1492. salt.config.is_provider_configured(
  1493. opts, provider, required_keys=("api_key",)
  1494. ),
  1495. ret,
  1496. )
  1497. # other cloud configuration tests
  1498. @skipIf(
  1499. salt.utils.platform.is_windows(),
  1500. "You can't set an environment dynamically in Windows",
  1501. )
  1502. @with_tempdir()
  1503. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  1504. def test_load_cloud_config_from_environ_var(self, tempdir):
  1505. env_root_dir = os.path.join(tempdir, "foo", "env")
  1506. os.makedirs(env_root_dir)
  1507. env_fpath = os.path.join(env_root_dir, "config-env")
  1508. with salt.utils.files.fopen(env_fpath, "w") as fp_:
  1509. fp_.write("root_dir: {}\n" "log_file: {}\n".format(env_root_dir, env_fpath))
  1510. with patched_environ(SALT_CLOUD_CONFIG=env_fpath):
  1511. # Should load from env variable, not the default configuration file
  1512. config = salt.config.cloud_config("/etc/salt/cloud")
  1513. self.assertEqual(config["log_file"], env_fpath)
  1514. root_dir = os.path.join(tempdir, "foo", "bar")
  1515. os.makedirs(root_dir)
  1516. fpath = os.path.join(root_dir, "config")
  1517. with salt.utils.files.fopen(fpath, "w") as fp_:
  1518. fp_.write("root_dir: {}\n" "log_file: {}\n".format(root_dir, fpath))
  1519. # Let's set the environment variable, yet, since the configuration
  1520. # file path is not the default one, i.e., the user has passed an
  1521. # alternative configuration file form the CLI parser, the
  1522. # environment variable will be ignored.
  1523. with patched_environ(SALT_CLOUD_CONFIG=env_fpath):
  1524. config = salt.config.cloud_config(fpath)
  1525. self.assertEqual(config["log_file"], fpath)
  1526. @with_tempdir()
  1527. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  1528. def test_deploy_search_path_as_string(self, temp_conf_dir):
  1529. config_file_path = os.path.join(temp_conf_dir, "cloud")
  1530. deploy_dir_path = os.path.join(temp_conf_dir, "test-deploy.d")
  1531. for directory in (temp_conf_dir, deploy_dir_path):
  1532. if not os.path.isdir(directory):
  1533. os.makedirs(directory)
  1534. default_config = salt.config.cloud_config(config_file_path)
  1535. default_config["deploy_scripts_search_path"] = deploy_dir_path
  1536. with salt.utils.files.fopen(config_file_path, "w") as cfd:
  1537. salt.utils.yaml.safe_dump(default_config, cfd, default_flow_style=False)
  1538. default_config = salt.config.cloud_config(config_file_path)
  1539. # Our custom deploy scripts path was correctly added to the list
  1540. self.assertIn(deploy_dir_path, default_config["deploy_scripts_search_path"])
  1541. # And it's even the first occurrence as it should
  1542. self.assertEqual(
  1543. deploy_dir_path, default_config["deploy_scripts_search_path"][0]
  1544. )
  1545. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  1546. def test_includes_load(self):
  1547. """
  1548. Tests that cloud.{providers,profiles}.d directories are loaded, even if not
  1549. directly passed in through path
  1550. """
  1551. log.warning("Clound config file path: %s", self.get_config_file_path("cloud"))
  1552. config = salt.config.cloud_config(self.get_config_file_path("cloud"))
  1553. self.assertIn("ec2-config", config["providers"])
  1554. self.assertIn("ec2-test", config["profiles"])
  1555. # <---- Salt Cloud Configuration Tests ---------------------------------------------
  1556. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  1557. def test_include_config_without_errors(self):
  1558. """
  1559. Tests that include_config function returns valid configuration
  1560. """
  1561. include_file = "minion.d/my.conf"
  1562. config_path = "/etc/salt/minion"
  1563. config_opts = {"id": "myminion.example.com"}
  1564. with patch("glob.glob", MagicMock(return_value=include_file)):
  1565. with patch(
  1566. "salt.config._read_conf_file", MagicMock(return_value=config_opts)
  1567. ):
  1568. configuration = salt.config.include_config(
  1569. include_file, config_path, verbose=False
  1570. )
  1571. self.assertEqual(config_opts, configuration)
  1572. def test_include_config_with_errors(self):
  1573. """
  1574. Tests that include_config function returns valid configuration even on errors
  1575. """
  1576. include_file = "minion.d/my.conf"
  1577. config_path = "/etc/salt/minion"
  1578. config_opts = {}
  1579. with patch("glob.glob", MagicMock(return_value=include_file)):
  1580. with patch("salt.config._read_conf_file", _salt_configuration_error):
  1581. configuration = salt.config.include_config(
  1582. include_file, config_path, verbose=False
  1583. )
  1584. self.assertEqual(config_opts, configuration)
  1585. def test_include_config_with_errors_exit(self):
  1586. """
  1587. Tests that include_config exits on errors
  1588. """
  1589. include_file = "minion.d/my.conf"
  1590. config_path = "/etc/salt/minion"
  1591. with patch("glob.glob", MagicMock(return_value=include_file)):
  1592. with patch("salt.config._read_conf_file", _salt_configuration_error):
  1593. with self.assertRaises(SystemExit):
  1594. salt.config.include_config(
  1595. include_file,
  1596. config_path,
  1597. verbose=False,
  1598. exit_on_config_errors=True,
  1599. )
  1600. @staticmethod
  1601. def _get_defaults(**kwargs):
  1602. ret = {
  1603. "saltenv": kwargs.pop("saltenv", None),
  1604. "id": "test",
  1605. "cachedir": "/A",
  1606. "sock_dir": "/B",
  1607. "root_dir": "/C",
  1608. "fileserver_backend": "roots",
  1609. "open_mode": False,
  1610. "auto_accept": False,
  1611. "file_roots": {},
  1612. "pillar_roots": {},
  1613. "file_ignore_glob": [],
  1614. "file_ignore_regex": [],
  1615. "worker_threads": 5,
  1616. "hash_type": "sha256",
  1617. "log_file": "foo.log",
  1618. }
  1619. ret.update(kwargs)
  1620. return ret
  1621. def test_apply_config(self):
  1622. """
  1623. Ensure that the environment and saltenv options work properly
  1624. """
  1625. with patch.object(
  1626. salt.config, "_adjust_log_file_override", Mock()
  1627. ), patch.object(salt.config, "_update_ssl_config", Mock()), patch.object(
  1628. salt.config, "_update_discovery_config", Mock()
  1629. ):
  1630. # MASTER CONFIG
  1631. # Ensure that environment overrides saltenv when saltenv not
  1632. # explicitly passed.
  1633. defaults = self._get_defaults(environment="foo")
  1634. ret = salt.config.apply_master_config(defaults=defaults)
  1635. self.assertEqual(ret["environment"], "foo")
  1636. self.assertEqual(ret["saltenv"], "foo")
  1637. # Ensure that environment overrides saltenv when saltenv not
  1638. # explicitly passed.
  1639. defaults = self._get_defaults(environment="foo", saltenv="bar")
  1640. ret = salt.config.apply_master_config(defaults=defaults)
  1641. self.assertEqual(ret["environment"], "bar")
  1642. self.assertEqual(ret["saltenv"], "bar")
  1643. # If environment was not explicitly set, it should not be in the
  1644. # opts at all.
  1645. defaults = self._get_defaults()
  1646. ret = salt.config.apply_master_config(defaults=defaults)
  1647. self.assertNotIn("environment", ret)
  1648. self.assertEqual(ret["saltenv"], None)
  1649. # Same test as above but with saltenv explicitly set
  1650. defaults = self._get_defaults(saltenv="foo")
  1651. ret = salt.config.apply_master_config(defaults=defaults)
  1652. self.assertNotIn("environment", ret)
  1653. self.assertEqual(ret["saltenv"], "foo")
  1654. # MINION CONFIG
  1655. # Ensure that environment overrides saltenv when saltenv not
  1656. # explicitly passed.
  1657. defaults = self._get_defaults(environment="foo")
  1658. ret = salt.config.apply_minion_config(defaults=defaults)
  1659. self.assertEqual(ret["environment"], "foo")
  1660. self.assertEqual(ret["saltenv"], "foo")
  1661. # Ensure that environment overrides saltenv when saltenv not
  1662. # explicitly passed.
  1663. defaults = self._get_defaults(environment="foo", saltenv="bar")
  1664. ret = salt.config.apply_minion_config(defaults=defaults)
  1665. self.assertEqual(ret["environment"], "bar")
  1666. self.assertEqual(ret["saltenv"], "bar")
  1667. # If environment was not explicitly set, it should not be in the
  1668. # opts at all.
  1669. defaults = self._get_defaults()
  1670. ret = salt.config.apply_minion_config(defaults=defaults)
  1671. self.assertNotIn("environment", ret)
  1672. self.assertEqual(ret["saltenv"], None)
  1673. # Same test as above but with saltenv explicitly set
  1674. defaults = self._get_defaults(saltenv="foo")
  1675. ret = salt.config.apply_minion_config(defaults=defaults)
  1676. self.assertNotIn("environment", ret)
  1677. self.assertEqual(ret["saltenv"], "foo")
  1678. class APIConfigTestCase(DefaultConfigsBase, TestCase):
  1679. """
  1680. TestCase for the api_config function in salt.config.__init__.py
  1681. """
  1682. def setUp(self):
  1683. # Copy DEFAULT_API_OPTS to restore after the test
  1684. self.default_api_opts = salt.config.DEFAULT_API_OPTS.copy()
  1685. def tearDown(self):
  1686. # Reset DEFAULT_API_OPTS settings as to not interfere with other unit tests
  1687. salt.config.DEFAULT_API_OPTS = self.default_api_opts
  1688. def test_api_config_log_file_values(self):
  1689. """
  1690. Tests the opts value of the 'log_file' after running through the
  1691. various default dict updates. 'log_file' should be updated to match
  1692. the DEFAULT_API_OPTS 'api_logfile' value.
  1693. """
  1694. with patch(
  1695. "salt.config.client_config",
  1696. MagicMock(return_value=self.mock_master_default_opts),
  1697. ):
  1698. expected = "{0}/var/log/salt/api".format(
  1699. RUNTIME_VARS.TMP_ROOT_DIR if RUNTIME_VARS.TMP_ROOT_DIR != "/" else ""
  1700. )
  1701. if salt.utils.platform.is_windows():
  1702. expected = "{}\\var\\log\\salt\\api".format(RUNTIME_VARS.TMP_ROOT_DIR)
  1703. ret = salt.config.api_config("/some/fake/path")
  1704. self.assertEqual(ret["log_file"], expected)
  1705. def test_api_config_pidfile_values(self):
  1706. """
  1707. Tests the opts value of the 'pidfile' after running through the
  1708. various default dict updates. 'pidfile' should be updated to match
  1709. the DEFAULT_API_OPTS 'api_pidfile' value.
  1710. """
  1711. with patch(
  1712. "salt.config.client_config",
  1713. MagicMock(return_value=self.mock_master_default_opts),
  1714. ):
  1715. expected = "{0}/var/run/salt-api.pid".format(
  1716. RUNTIME_VARS.TMP_ROOT_DIR if RUNTIME_VARS.TMP_ROOT_DIR != "/" else ""
  1717. )
  1718. if salt.utils.platform.is_windows():
  1719. expected = "{}\\var\\run\\salt-api.pid".format(
  1720. RUNTIME_VARS.TMP_ROOT_DIR
  1721. )
  1722. ret = salt.config.api_config("/some/fake/path")
  1723. self.assertEqual(ret["pidfile"], expected)
  1724. def test_master_config_file_overrides_defaults(self):
  1725. """
  1726. Tests the opts value of the api config values after running through the
  1727. various default dict updates that should be overridden by settings in
  1728. the user's master config file.
  1729. """
  1730. foo_dir = os.path.join(RUNTIME_VARS.TMP_ROOT_DIR, "foo/bar/baz")
  1731. hello_dir = os.path.join(RUNTIME_VARS.TMP_ROOT_DIR, "hello/world")
  1732. if salt.utils.platform.is_windows():
  1733. foo_dir = "c:\\{}".format(foo_dir.replace("/", "\\"))
  1734. hello_dir = "c:\\{}".format(hello_dir.replace("/", "\\"))
  1735. mock_master_config = {
  1736. "api_pidfile": foo_dir,
  1737. "api_logfile": hello_dir,
  1738. "rest_timeout": 5,
  1739. }
  1740. mock_master_config.update(self.mock_master_default_opts.copy())
  1741. with patch(
  1742. "salt.config.client_config", MagicMock(return_value=mock_master_config)
  1743. ):
  1744. ret = salt.config.api_config("/some/fake/path")
  1745. self.assertEqual(ret["rest_timeout"], 5)
  1746. self.assertEqual(ret["api_pidfile"], foo_dir)
  1747. self.assertEqual(ret["pidfile"], foo_dir)
  1748. self.assertEqual(ret["api_logfile"], hello_dir)
  1749. self.assertEqual(ret["log_file"], hello_dir)
  1750. def test_api_config_prepend_root_dirs_return(self):
  1751. """
  1752. Tests the opts value of the api_logfile, log_file, api_pidfile, and pidfile
  1753. when a custom root directory is used. This ensures that each of these
  1754. values is present in the list of opts keys that should have the root_dir
  1755. prepended when the api_config function returns the opts dictionary.
  1756. """
  1757. mock_log = "/mock/root/var/log/salt/api"
  1758. mock_pid = "/mock/root/var/run/salt-api.pid"
  1759. mock_master_config = self.mock_master_default_opts.copy()
  1760. mock_master_config["root_dir"] = "/mock/root/"
  1761. if salt.utils.platform.is_windows():
  1762. mock_log = "c:\\mock\\root\\var\\log\\salt\\api"
  1763. mock_pid = "c:\\mock\\root\\var\\run\\salt-api.pid"
  1764. mock_master_config["root_dir"] = "c:\\mock\\root"
  1765. with patch(
  1766. "salt.config.client_config", MagicMock(return_value=mock_master_config)
  1767. ):
  1768. ret = salt.config.api_config("/some/fake/path")
  1769. self.assertEqual(ret["api_logfile"], mock_log)
  1770. self.assertEqual(ret["log_file"], mock_log)
  1771. self.assertEqual(ret["api_pidfile"], mock_pid)
  1772. self.assertEqual(ret["pidfile"], mock_pid)