1
0

test_config.py 72 KB

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