test_config.py 67 KB

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