test_config.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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
  616. the minion id. Lowercase does not operate on a static `id: KING_BOB`
  617. setting, or a cached id.
  618. '''
  619. minion_config = os.path.join(tempdir, 'minion')
  620. with salt.utils.files.fopen(minion_config, 'w') as fp_:
  621. fp_.write(textwrap.dedent('''\
  622. id_function:
  623. test.echo:
  624. text: KING_BOB
  625. minion_id_caching: False
  626. minion_id_lowercase: True
  627. '''))
  628. config = sconfig.minion_config(minion_config) # Load the configuration
  629. self.assertEqual(config['minion_id_caching'], False) # Check the configuration
  630. self.assertEqual(config['minion_id_lowercase'], True) # Check the configuration
  631. self.assertEqual(config['id'], 'king_bob')
  632. @with_tempdir()
  633. def test_backend_rename(self, tempdir):
  634. '''
  635. This tests that we successfully rename git, hg, svn, and minion to
  636. gitfs, hgfs, svnfs, and minionfs in the master and minion opts.
  637. '''
  638. fpath = salt.utils.files.mkstemp(dir=tempdir)
  639. with salt.utils.files.fopen(fpath, 'w') as fp_:
  640. fp_.write(textwrap.dedent('''\
  641. fileserver_backend:
  642. - roots
  643. - git
  644. - hg
  645. - svn
  646. - minion
  647. '''))
  648. master_config = sconfig.master_config(fpath)
  649. minion_config = sconfig.minion_config(fpath)
  650. expected = ['roots', 'gitfs', 'hgfs', 'svnfs', 'minionfs']
  651. self.assertEqual(master_config['fileserver_backend'], expected)
  652. self.assertEqual(minion_config['fileserver_backend'], expected)
  653. def test_syndic_config(self):
  654. syndic_conf_path = self.get_config_file_path('syndic')
  655. minion_conf_path = self.get_config_file_path('minion')
  656. syndic_opts = sconfig.syndic_config(
  657. syndic_conf_path, minion_conf_path
  658. )
  659. syndic_opts.update(salt.minion.resolve_dns(syndic_opts))
  660. root_dir = syndic_opts['root_dir']
  661. # id & pki dir are shared & so configured on the minion side
  662. self.assertEqual(syndic_opts['id'], 'minion')
  663. self.assertEqual(syndic_opts['pki_dir'], os.path.join(root_dir, 'pki'))
  664. # the rest is configured master side
  665. self.assertIn(syndic_opts['master_uri'], ['tcp://127.0.0.1:54506', 'tcp://[::1]:54506'])
  666. self.assertEqual(syndic_opts['master_port'], 54506)
  667. self.assertIn(syndic_opts['master_ip'], ['127.0.0.1', '[::1]'])
  668. self.assertEqual(syndic_opts['master'], 'localhost')
  669. self.assertEqual(syndic_opts['sock_dir'], os.path.join(root_dir, 'minion_sock'))
  670. self.assertEqual(syndic_opts['cachedir'], os.path.join(root_dir, 'cache'))
  671. self.assertEqual(syndic_opts['log_file'], os.path.join(root_dir, 'syndic.log'))
  672. self.assertEqual(syndic_opts['pidfile'], os.path.join(root_dir, 'syndic.pid'))
  673. # Show that the options of localclient that repub to local master
  674. # are not merged with syndic ones
  675. self.assertEqual(syndic_opts['_master_conf_file'], minion_conf_path)
  676. self.assertEqual(syndic_opts['_minion_conf_file'], syndic_conf_path)
  677. @with_tempfile()
  678. def _get_tally(self, fpath, conf_func):
  679. '''
  680. This ensures that any strings which are loaded are unicode strings
  681. '''
  682. tally = {}
  683. def _count_strings(config):
  684. if isinstance(config, dict):
  685. for key, val in six.iteritems(config):
  686. log.debug('counting strings in dict key: %s', key)
  687. log.debug('counting strings in dict val: %s', val)
  688. _count_strings(key)
  689. _count_strings(val)
  690. elif isinstance(config, list):
  691. log.debug('counting strings in list: %s', config)
  692. for item in config:
  693. _count_strings(item)
  694. else:
  695. if isinstance(config, six.string_types):
  696. if isinstance(config, six.text_type):
  697. tally['unicode'] = tally.get('unicode', 0) + 1
  698. else:
  699. # We will never reach this on PY3
  700. tally.setdefault('non_unicode', []).append(config)
  701. with salt.utils.files.fopen(fpath, 'w') as wfh:
  702. wfh.write(textwrap.dedent('''
  703. foo: bar
  704. mylist:
  705. - somestring
  706. - 9
  707. - 123.456
  708. - True
  709. - nested:
  710. - key: val
  711. - nestedlist:
  712. - foo
  713. - bar
  714. - baz
  715. mydict:
  716. - somestring: 9
  717. - 123.456: 789
  718. - True: False
  719. - nested:
  720. - key: val
  721. - nestedlist:
  722. - foo
  723. - bar
  724. - baz'''))
  725. if conf_func is sconfig.master_config:
  726. wfh.write('\n\n')
  727. wfh.write(textwrap.dedent('''
  728. rest_cherrypy:
  729. port: 8000
  730. disable_ssl: True
  731. app_path: /beacon_demo
  732. app: /srv/web/html/index.html
  733. static: /srv/web/static'''))
  734. config = conf_func(fpath)
  735. _count_strings(config)
  736. return tally
  737. def test_conf_file_strings_are_unicode_for_master(self):
  738. '''
  739. This ensures that any strings which are loaded are unicode strings
  740. '''
  741. tally = self._get_tally(sconfig.master_config) # pylint: disable=no-value-for-parameter
  742. non_unicode = tally.get('non_unicode', [])
  743. self.assertEqual(len(non_unicode), 8 if six.PY2 else 0, non_unicode)
  744. self.assertTrue(tally['unicode'] > 0)
  745. def test_conf_file_strings_are_unicode_for_minion(self):
  746. '''
  747. This ensures that any strings which are loaded are unicode strings
  748. '''
  749. tally = self._get_tally(sconfig.minion_config) # pylint: disable=no-value-for-parameter
  750. non_unicode = tally.get('non_unicode', [])
  751. self.assertEqual(len(non_unicode), 0, non_unicode)
  752. self.assertTrue(tally['unicode'] > 0)
  753. # <---- Salt Cloud Configuration Tests ---------------------------------------------
  754. # cloud_config tests
  755. @skipIf(NO_MOCK, NO_MOCK_REASON)
  756. def test_cloud_config_double_master_path(self):
  757. '''
  758. Tests passing in master_config_path and master_config kwargs.
  759. '''
  760. with patch('salt.config.load_config', MagicMock(return_value={})):
  761. self.assertRaises(SaltCloudConfigError, sconfig.cloud_config, PATH,
  762. master_config_path='foo', master_config='bar')
  763. @skipIf(NO_MOCK, NO_MOCK_REASON)
  764. def test_cloud_config_double_providers_path(self):
  765. '''
  766. Tests passing in providers_config_path and providers_config kwargs.
  767. '''
  768. with patch('salt.config.load_config', MagicMock(return_value={})):
  769. self.assertRaises(SaltCloudConfigError, sconfig.cloud_config, PATH,
  770. providers_config_path='foo', providers_config='bar')
  771. @skipIf(NO_MOCK, NO_MOCK_REASON)
  772. def test_cloud_config_double_profiles_path(self):
  773. '''
  774. Tests passing in profiles_config_path and profiles_config kwargs.
  775. '''
  776. with patch('salt.config.load_config', MagicMock(return_value={})):
  777. self.assertRaises(SaltCloudConfigError, sconfig.cloud_config, PATH,
  778. profiles_config_path='foo', profiles_config='bar')
  779. @skipIf(NO_MOCK, NO_MOCK_REASON)
  780. def test_cloud_config_providers_in_opts(self):
  781. '''
  782. Tests mixing old cloud providers with pre-configured providers configurations
  783. using the providers_config kwarg
  784. '''
  785. with patch('salt.config.load_config', MagicMock(return_value={})):
  786. with patch('salt.config.apply_cloud_config',
  787. MagicMock(return_value={'providers': 'foo'})):
  788. self.assertRaises(SaltCloudConfigError, sconfig.cloud_config, PATH,
  789. providers_config='bar')
  790. @skipIf(NO_MOCK, NO_MOCK_REASON)
  791. def test_cloud_config_providers_in_opts_path(self):
  792. '''
  793. Tests mixing old cloud providers with pre-configured providers configurations
  794. using the providers_config_path kwarg
  795. '''
  796. with patch('salt.config.load_config', MagicMock(return_value={})):
  797. with patch('salt.config.apply_cloud_config',
  798. MagicMock(return_value={'providers': 'foo'})):
  799. with patch('os.path.isfile', MagicMock(return_value=True)):
  800. self.assertRaises(SaltCloudConfigError, sconfig.cloud_config, PATH,
  801. providers_config_path='bar')
  802. @skipIf(NO_MOCK, NO_MOCK_REASON)
  803. def test_cloud_config_deploy_scripts_search_path(self):
  804. '''
  805. Tests the contents of the 'deploy_scripts_search_path' tuple to ensure that
  806. the correct deploy search paths are present.
  807. There should be two search paths reported in the tuple: ``/etc/salt/cloud.deploy.d``
  808. and ``<path-to-salt-install>/salt/cloud/deploy``. The first element is usually
  809. ``/etc/salt/cloud.deploy.d``, but sometimes is can be something like
  810. ``/etc/local/salt/cloud.deploy.d``, so we'll only test against the last part of
  811. the path.
  812. '''
  813. with patch('os.path.isdir', MagicMock(return_value=True)):
  814. search_paths = sconfig.cloud_config('/etc/salt/cloud').get('deploy_scripts_search_path')
  815. etc_deploy_path = '/salt/cloud.deploy.d'
  816. deploy_path = '/salt/cloud/deploy'
  817. if salt.utils.platform.is_windows():
  818. etc_deploy_path = '/salt\\cloud.deploy.d'
  819. deploy_path = '\\salt\\cloud\\deploy'
  820. # Check cloud.deploy.d path is the first element in the search_paths tuple
  821. self.assertTrue(search_paths[0].endswith(etc_deploy_path))
  822. # Check the second element in the search_paths tuple
  823. self.assertTrue(search_paths[1].endswith(deploy_path))
  824. # apply_cloud_config tests
  825. def test_apply_cloud_config_no_provider_detail_list(self):
  826. '''
  827. Tests when the provider is not contained in a list of details
  828. '''
  829. overrides = {'providers': {'foo': [{'bar': 'baz'}]}}
  830. self.assertRaises(SaltCloudConfigError, sconfig.apply_cloud_config,
  831. overrides, defaults=DEFAULT)
  832. def test_apply_cloud_config_no_provider_detail_dict(self):
  833. '''
  834. Tests when the provider is not contained in the details dictionary
  835. '''
  836. overrides = {'providers': {'foo': {'bar': 'baz'}}}
  837. self.assertRaises(SaltCloudConfigError, sconfig.apply_cloud_config,
  838. overrides, defaults=DEFAULT)
  839. @skipIf(NO_MOCK, NO_MOCK_REASON)
  840. def test_apply_cloud_config_success_list(self):
  841. '''
  842. Tests success when valid data is passed into the function as a list
  843. '''
  844. with patch('salt.config.old_to_new',
  845. MagicMock(return_value={'default_include': 'path/to/some/cloud/conf/file',
  846. 'providers': {
  847. 'foo': {
  848. 'bar': {
  849. 'driver': 'foo:bar'}}}})):
  850. overrides = {'providers': {'foo': [{'driver': 'bar'}]}}
  851. ret = {'default_include': 'path/to/some/cloud/conf/file',
  852. 'providers': {'foo': {'bar': {'driver': 'foo:bar'}}}}
  853. self.assertEqual(sconfig.apply_cloud_config(overrides, defaults=DEFAULT), ret)
  854. @skipIf(NO_MOCK, NO_MOCK_REASON)
  855. def test_apply_cloud_config_success_dict(self):
  856. '''
  857. Tests success when valid data is passed into function as a dictionary
  858. '''
  859. with patch('salt.config.old_to_new',
  860. MagicMock(return_value={'default_include': 'path/to/some/cloud/conf/file',
  861. 'providers': {
  862. 'foo': {
  863. 'bar': {
  864. 'driver': 'foo:bar'}}}})):
  865. overrides = {'providers': {'foo': {'driver': 'bar'}}}
  866. ret = {'default_include': 'path/to/some/cloud/conf/file',
  867. 'providers': {'foo': {'bar': {'driver': 'foo:bar'}}}}
  868. self.assertEqual(sconfig.apply_cloud_config(overrides, defaults=DEFAULT), ret)
  869. # apply_vm_profiles_config tests
  870. def test_apply_vm_profiles_config_bad_profile_format(self):
  871. '''
  872. Tests passing in a bad profile format in overrides
  873. '''
  874. overrides = {'foo': 'bar', 'conf_file': PATH}
  875. self.assertRaises(SaltCloudConfigError, sconfig.apply_vm_profiles_config,
  876. PATH, overrides, defaults=DEFAULT)
  877. def test_apply_vm_profiles_config_success(self):
  878. '''
  879. Tests passing in valid provider and profile config files successfully
  880. '''
  881. providers = {'test-provider':
  882. {'digitalocean':
  883. {'driver': 'digitalocean', 'profiles': {}}}}
  884. overrides = {'test-profile':
  885. {'provider': 'test-provider',
  886. 'image': 'Ubuntu 12.10 x64',
  887. 'size': '512MB'},
  888. 'conf_file': PATH}
  889. ret = {'test-profile':
  890. {'profile': 'test-profile',
  891. 'provider': 'test-provider:digitalocean',
  892. 'image': 'Ubuntu 12.10 x64',
  893. 'size': '512MB'}}
  894. self.assertEqual(sconfig.apply_vm_profiles_config(providers,
  895. overrides,
  896. defaults=DEFAULT), ret)
  897. def test_apply_vm_profiles_config_extend_success(self):
  898. '''
  899. Tests profile extends functionality with valid provider and profile configs
  900. '''
  901. providers = {'test-config': {'ec2': {'profiles': {}, 'driver': 'ec2'}}}
  902. overrides = {'Amazon': {'image': 'test-image-1',
  903. 'extends': 'dev-instances'},
  904. 'Fedora': {'image': 'test-image-2',
  905. 'extends': 'dev-instances'},
  906. 'conf_file': PATH,
  907. 'dev-instances': {'ssh_username': 'test_user',
  908. 'provider': 'test-config'}}
  909. ret = {'Amazon': {'profile': 'Amazon',
  910. 'ssh_username': 'test_user',
  911. 'image': 'test-image-1',
  912. 'provider': 'test-config:ec2'},
  913. 'Fedora': {'profile': 'Fedora',
  914. 'ssh_username': 'test_user',
  915. 'image': 'test-image-2',
  916. 'provider': 'test-config:ec2'},
  917. 'dev-instances': {'profile': 'dev-instances',
  918. 'ssh_username': 'test_user',
  919. 'provider': 'test-config:ec2'}}
  920. self.assertEqual(sconfig.apply_vm_profiles_config(providers,
  921. overrides,
  922. defaults=DEFAULT), ret)
  923. def test_apply_vm_profiles_config_extend_override_success(self):
  924. '''
  925. Tests profile extends and recursively merges data elements
  926. '''
  927. self.maxDiff = None
  928. providers = {'test-config': {'ec2': {'profiles': {}, 'driver': 'ec2'}}}
  929. overrides = {'Fedora': {'image': 'test-image-2',
  930. 'extends': 'dev-instances',
  931. 'minion': {'grains': {'stage': 'experimental'}}},
  932. 'conf_file': PATH,
  933. 'dev-instances': {'ssh_username': 'test_user',
  934. 'provider': 'test-config',
  935. 'minion': {'grains': {'role': 'webserver'}}}}
  936. ret = {'Fedora': {'profile': 'Fedora',
  937. 'ssh_username': 'test_user',
  938. 'image': 'test-image-2',
  939. 'minion': {'grains': {'role': 'webserver',
  940. 'stage': 'experimental'}},
  941. 'provider': 'test-config:ec2'},
  942. 'dev-instances': {'profile': 'dev-instances',
  943. 'ssh_username': 'test_user',
  944. 'minion': {'grains': {'role': 'webserver'}},
  945. 'provider': 'test-config:ec2'}}
  946. self.assertEqual(sconfig.apply_vm_profiles_config(providers,
  947. overrides,
  948. defaults=DEFAULT), ret)
  949. # apply_cloud_providers_config tests
  950. def test_apply_cloud_providers_config_same_providers(self):
  951. '''
  952. Tests when two providers are given with the same provider name
  953. '''
  954. overrides = {'my-dev-envs':
  955. [{'id': 'ABCDEFGHIJKLMNOP',
  956. 'key': 'supersecretkeysupersecretkey',
  957. 'driver': 'ec2'},
  958. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  959. 'password': 'supersecret',
  960. 'driver': 'ec2'}],
  961. 'conf_file': PATH}
  962. self.assertRaises(SaltCloudConfigError,
  963. sconfig.apply_cloud_providers_config,
  964. overrides,
  965. DEFAULT)
  966. def test_apply_cloud_providers_config_extend(self):
  967. '''
  968. Tests the successful extension of a cloud provider
  969. '''
  970. overrides = {'my-production-envs':
  971. [{'extends': 'my-dev-envs:ec2',
  972. 'location': 'us-east-1',
  973. 'user': 'ec2-user@mycorp.com'
  974. }],
  975. 'my-dev-envs':
  976. [{'id': 'ABCDEFGHIJKLMNOP',
  977. 'user': 'user@mycorp.com',
  978. 'location': 'ap-southeast-1',
  979. 'key': 'supersecretkeysupersecretkey',
  980. 'driver': 'ec2'
  981. },
  982. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  983. 'password': 'supersecret',
  984. 'driver': 'linode'
  985. }],
  986. 'conf_file': PATH}
  987. ret = {'my-production-envs':
  988. {'ec2':
  989. {'profiles': {},
  990. 'location': 'us-east-1',
  991. 'key': 'supersecretkeysupersecretkey',
  992. 'driver': 'ec2',
  993. 'id': 'ABCDEFGHIJKLMNOP',
  994. 'user': 'ec2-user@mycorp.com'}},
  995. 'my-dev-envs':
  996. {'linode':
  997. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  998. 'password': 'supersecret',
  999. 'profiles': {},
  1000. 'driver': 'linode'},
  1001. 'ec2':
  1002. {'profiles': {},
  1003. 'location': 'ap-southeast-1',
  1004. 'key': 'supersecretkeysupersecretkey',
  1005. 'driver': 'ec2',
  1006. 'id': 'ABCDEFGHIJKLMNOP',
  1007. 'user': 'user@mycorp.com'}}}
  1008. self.assertEqual(ret,
  1009. sconfig.apply_cloud_providers_config(
  1010. overrides,
  1011. defaults=DEFAULT))
  1012. def test_apply_cloud_providers_config_extend_multiple(self):
  1013. '''
  1014. Tests the successful extension of two cloud providers
  1015. '''
  1016. overrides = {'my-production-envs':
  1017. [{'extends': 'my-dev-envs:ec2',
  1018. 'location': 'us-east-1',
  1019. 'user': 'ec2-user@mycorp.com'},
  1020. {'password': 'new-password',
  1021. 'extends': 'my-dev-envs:linode',
  1022. 'location': 'Salt Lake City'
  1023. }],
  1024. 'my-dev-envs':
  1025. [{'id': 'ABCDEFGHIJKLMNOP',
  1026. 'user': 'user@mycorp.com',
  1027. 'location': 'ap-southeast-1',
  1028. 'key': 'supersecretkeysupersecretkey',
  1029. 'driver': 'ec2'},
  1030. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  1031. 'password': 'supersecret',
  1032. 'driver': 'linode'}],
  1033. 'conf_file': PATH}
  1034. ret = {'my-production-envs':
  1035. {'linode':
  1036. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  1037. 'profiles': {},
  1038. 'location': 'Salt Lake City',
  1039. 'driver': 'linode',
  1040. 'password': 'new-password'},
  1041. 'ec2':
  1042. {'user': 'ec2-user@mycorp.com',
  1043. 'key': 'supersecretkeysupersecretkey',
  1044. 'driver': 'ec2',
  1045. 'id': 'ABCDEFGHIJKLMNOP',
  1046. 'profiles': {},
  1047. 'location': 'us-east-1'}},
  1048. 'my-dev-envs':
  1049. {'linode':
  1050. {'apikey': 'abcdefghijklmnopqrstuvwxyz',
  1051. 'password': 'supersecret',
  1052. 'profiles': {},
  1053. 'driver': 'linode'},
  1054. 'ec2':
  1055. {'profiles': {},
  1056. 'user': 'user@mycorp.com',
  1057. 'key': 'supersecretkeysupersecretkey',
  1058. 'driver': 'ec2',
  1059. 'id': 'ABCDEFGHIJKLMNOP',
  1060. 'location': 'ap-southeast-1'}}}
  1061. self.assertEqual(ret, sconfig.apply_cloud_providers_config(
  1062. overrides,
  1063. defaults=DEFAULT))
  1064. def test_apply_cloud_providers_config_extends_bad_alias(self):
  1065. '''
  1066. Tests when the extension contains an alias not found in providers list
  1067. '''
  1068. overrides = {'my-production-envs':
  1069. [{'extends': 'test-alias:ec2',
  1070. 'location': 'us-east-1',
  1071. 'user': 'ec2-user@mycorp.com'}],
  1072. 'my-dev-envs':
  1073. [{'id': 'ABCDEFGHIJKLMNOP',
  1074. 'user': 'user@mycorp.com',
  1075. 'location': 'ap-southeast-1',
  1076. 'key': 'supersecretkeysupersecretkey',
  1077. 'driver': 'ec2'}],
  1078. 'conf_file': PATH}
  1079. self.assertRaises(SaltCloudConfigError,
  1080. sconfig.apply_cloud_providers_config,
  1081. overrides,
  1082. DEFAULT)
  1083. def test_apply_cloud_providers_config_extends_bad_provider(self):
  1084. '''
  1085. Tests when the extension contains a provider not found in providers list
  1086. '''
  1087. overrides = {'my-production-envs':
  1088. [{'extends': 'my-dev-envs:linode',
  1089. 'location': 'us-east-1',
  1090. 'user': 'ec2-user@mycorp.com'}],
  1091. 'my-dev-envs':
  1092. [{'id': 'ABCDEFGHIJKLMNOP',
  1093. 'user': 'user@mycorp.com',
  1094. 'location': 'ap-southeast-1',
  1095. 'key': 'supersecretkeysupersecretkey',
  1096. 'driver': 'ec2'}],
  1097. 'conf_file': PATH}
  1098. self.assertRaises(SaltCloudConfigError,
  1099. sconfig.apply_cloud_providers_config,
  1100. overrides,
  1101. DEFAULT)
  1102. def test_apply_cloud_providers_config_extends_no_provider(self):
  1103. '''
  1104. Tests when no provider is supplied in the extends statement
  1105. '''
  1106. overrides = {'my-production-envs':
  1107. [{'extends': 'my-dev-envs',
  1108. 'location': 'us-east-1',
  1109. 'user': 'ec2-user@mycorp.com'}],
  1110. 'my-dev-envs':
  1111. [{'id': 'ABCDEFGHIJKLMNOP',
  1112. 'user': 'user@mycorp.com',
  1113. 'location': 'ap-southeast-1',
  1114. 'key': 'supersecretkeysupersecretkey',
  1115. 'driver': 'linode'}],
  1116. 'conf_file': PATH}
  1117. self.assertRaises(SaltCloudConfigError,
  1118. sconfig.apply_cloud_providers_config,
  1119. overrides,
  1120. DEFAULT)
  1121. def test_apply_cloud_providers_extends_not_in_providers(self):
  1122. '''
  1123. Tests when extends is not in the list of providers
  1124. '''
  1125. overrides = {'my-production-envs':
  1126. [{'extends': 'my-dev-envs ec2',
  1127. 'location': 'us-east-1',
  1128. 'user': 'ec2-user@mycorp.com'}],
  1129. 'my-dev-envs':
  1130. [{'id': 'ABCDEFGHIJKLMNOP',
  1131. 'user': 'user@mycorp.com',
  1132. 'location': 'ap-southeast-1',
  1133. 'key': 'supersecretkeysupersecretkey',
  1134. 'driver': 'linode'}],
  1135. 'conf_file': PATH}
  1136. self.assertRaises(SaltCloudConfigError,
  1137. sconfig.apply_cloud_providers_config,
  1138. overrides,
  1139. DEFAULT)
  1140. # is_provider_configured tests
  1141. def test_is_provider_configured_no_alias(self):
  1142. '''
  1143. Tests when provider alias is not in opts
  1144. '''
  1145. opts = {'providers': 'test'}
  1146. provider = 'foo:bar'
  1147. self.assertFalse(sconfig.is_provider_configured(opts, provider))
  1148. def test_is_provider_configured_no_driver(self):
  1149. '''
  1150. Tests when provider driver is not in opts
  1151. '''
  1152. opts = {'providers': {'foo': 'baz'}}
  1153. provider = 'foo:bar'
  1154. self.assertFalse(sconfig.is_provider_configured(opts, provider))
  1155. def test_is_provider_configured_key_is_none(self):
  1156. '''
  1157. Tests when a required configuration key is not set
  1158. '''
  1159. opts = {'providers': {'foo': {'bar': {'api_key': None}}}}
  1160. provider = 'foo:bar'
  1161. self.assertFalse(
  1162. sconfig.is_provider_configured(opts,
  1163. provider,
  1164. required_keys=('api_key',)))
  1165. def test_is_provider_configured_success(self):
  1166. '''
  1167. Tests successful cloud provider configuration
  1168. '''
  1169. opts = {'providers': {'foo': {'bar': {'api_key': 'baz'}}}}
  1170. provider = 'foo:bar'
  1171. ret = {'api_key': 'baz'}
  1172. self.assertEqual(
  1173. sconfig.is_provider_configured(opts,
  1174. provider,
  1175. required_keys=('api_key',)), ret)
  1176. def test_is_provider_configured_multiple_driver_not_provider(self):
  1177. '''
  1178. Tests when the drive is not the same as the provider when
  1179. searching through multiple providers
  1180. '''
  1181. opts = {'providers': {'foo': {'bar': {'api_key': 'baz'}}}}
  1182. provider = 'foo'
  1183. self.assertFalse(sconfig.is_provider_configured(opts, provider))
  1184. def test_is_provider_configured_multiple_key_is_none(self):
  1185. '''
  1186. Tests when a required configuration key is not set when
  1187. searching through multiple providers
  1188. '''
  1189. opts = {'providers': {'foo': {'bar': {'api_key': None}}}}
  1190. provider = 'bar'
  1191. self.assertFalse(
  1192. sconfig.is_provider_configured(opts,
  1193. provider,
  1194. required_keys=('api_key',)))
  1195. def test_is_provider_configured_multiple_success(self):
  1196. '''
  1197. Tests successful cloud provider configuration when searching
  1198. through multiple providers
  1199. '''
  1200. opts = {'providers': {'foo': {'bar': {'api_key': 'baz'}}}}
  1201. provider = 'bar'
  1202. ret = {'api_key': 'baz'}
  1203. self.assertEqual(
  1204. sconfig.is_provider_configured(opts,
  1205. provider,
  1206. required_keys=('api_key',)), ret)
  1207. # other cloud configuration tests
  1208. @skipIf(
  1209. salt.utils.platform.is_windows(),
  1210. 'You can\'t set an environment dynamically in Windows')
  1211. @with_tempdir()
  1212. def test_load_cloud_config_from_environ_var(self, tempdir):
  1213. original_environ = os.environ.copy()
  1214. try:
  1215. env_root_dir = os.path.join(tempdir, 'foo', 'env')
  1216. os.makedirs(env_root_dir)
  1217. env_fpath = os.path.join(env_root_dir, 'config-env')
  1218. with salt.utils.files.fopen(env_fpath, 'w') as fp_:
  1219. fp_.write(
  1220. 'root_dir: {0}\n'
  1221. 'log_file: {1}\n'.format(env_root_dir, env_fpath)
  1222. )
  1223. os.environ['SALT_CLOUD_CONFIG'] = env_fpath
  1224. # Should load from env variable, not the default configuration file
  1225. config = sconfig.cloud_config('/etc/salt/cloud')
  1226. self.assertEqual(config['log_file'], env_fpath)
  1227. os.environ.clear()
  1228. os.environ.update(original_environ)
  1229. root_dir = os.path.join(tempdir, 'foo', 'bar')
  1230. os.makedirs(root_dir)
  1231. fpath = os.path.join(root_dir, 'config')
  1232. with salt.utils.files.fopen(fpath, 'w') as fp_:
  1233. fp_.write(
  1234. 'root_dir: {0}\n'
  1235. 'log_file: {1}\n'.format(root_dir, fpath)
  1236. )
  1237. # Let's set the environment variable, yet, since the configuration
  1238. # file path is not the default one, i.e., the user has passed an
  1239. # alternative configuration file form the CLI parser, the
  1240. # environment variable will be ignored.
  1241. os.environ['SALT_CLOUD_CONFIG'] = env_fpath
  1242. config = sconfig.cloud_config(fpath)
  1243. self.assertEqual(config['log_file'], fpath)
  1244. finally:
  1245. # Reset the environ
  1246. os.environ.clear()
  1247. os.environ.update(original_environ)
  1248. @with_tempdir()
  1249. def test_deploy_search_path_as_string(self, temp_conf_dir):
  1250. config_file_path = os.path.join(temp_conf_dir, 'cloud')
  1251. deploy_dir_path = os.path.join(temp_conf_dir, 'test-deploy.d')
  1252. for directory in (temp_conf_dir, deploy_dir_path):
  1253. if not os.path.isdir(directory):
  1254. os.makedirs(directory)
  1255. default_config = sconfig.cloud_config(config_file_path)
  1256. default_config['deploy_scripts_search_path'] = deploy_dir_path
  1257. with salt.utils.files.fopen(config_file_path, 'w') as cfd:
  1258. salt.utils.yaml.safe_dump(default_config, cfd, default_flow_style=False)
  1259. default_config = sconfig.cloud_config(config_file_path)
  1260. # Our custom deploy scripts path was correctly added to the list
  1261. self.assertIn(
  1262. deploy_dir_path,
  1263. default_config['deploy_scripts_search_path']
  1264. )
  1265. # And it's even the first occurrence as it should
  1266. self.assertEqual(
  1267. deploy_dir_path,
  1268. default_config['deploy_scripts_search_path'][0]
  1269. )
  1270. def test_includes_load(self):
  1271. '''
  1272. Tests that cloud.{providers,profiles}.d directories are loaded, even if not
  1273. directly passed in through path
  1274. '''
  1275. config = sconfig.cloud_config(self.get_config_file_path('cloud'))
  1276. self.assertIn('ec2-config', config['providers'])
  1277. self.assertIn('ec2-test', config['profiles'])
  1278. # <---- Salt Cloud Configuration Tests ---------------------------------------------
  1279. @skipIf(NO_MOCK, NO_MOCK_REASON)
  1280. def test_include_config_without_errors(self):
  1281. '''
  1282. Tests that include_config function returns valid configuration
  1283. '''
  1284. include_file = 'minion.d/my.conf'
  1285. config_path = '/etc/salt/minion'
  1286. config_opts = {'id': 'myminion.example.com'}
  1287. with patch('glob.glob', MagicMock(return_value=include_file)):
  1288. with patch('salt.config._read_conf_file', MagicMock(return_value=config_opts)):
  1289. configuration = sconfig.include_config(include_file, config_path, verbose=False)
  1290. self.assertEqual(config_opts, configuration)
  1291. @skipIf(NO_MOCK, NO_MOCK_REASON)
  1292. def test_include_config_with_errors(self):
  1293. '''
  1294. Tests that include_config function returns valid configuration even on errors
  1295. '''
  1296. include_file = 'minion.d/my.conf'
  1297. config_path = '/etc/salt/minion'
  1298. config_opts = {}
  1299. with patch('glob.glob', MagicMock(return_value=include_file)):
  1300. with patch('salt.config._read_conf_file', _salt_configuration_error):
  1301. configuration = sconfig.include_config(include_file, config_path, verbose=False)
  1302. self.assertEqual(config_opts, configuration)
  1303. @skipIf(NO_MOCK, NO_MOCK_REASON)
  1304. def test_include_config_with_errors_exit(self):
  1305. '''
  1306. Tests that include_config exits on errors
  1307. '''
  1308. include_file = 'minion.d/my.conf'
  1309. config_path = '/etc/salt/minion'
  1310. with patch('glob.glob', MagicMock(return_value=include_file)):
  1311. with patch('salt.config._read_conf_file', _salt_configuration_error):
  1312. with self.assertRaises(SystemExit):
  1313. sconfig.include_config(include_file,
  1314. config_path,
  1315. verbose=False,
  1316. exit_on_config_errors=True)
  1317. @staticmethod
  1318. def _get_defaults(**kwargs):
  1319. ret = {
  1320. 'saltenv': kwargs.pop('saltenv', None),
  1321. 'id': 'test',
  1322. 'cachedir': '/A',
  1323. 'sock_dir': '/B',
  1324. 'root_dir': '/C',
  1325. 'fileserver_backend': 'roots',
  1326. 'open_mode': False,
  1327. 'auto_accept': False,
  1328. 'file_roots': {},
  1329. 'pillar_roots': {},
  1330. 'file_ignore_glob': [],
  1331. 'file_ignore_regex': [],
  1332. 'worker_threads': 5,
  1333. 'hash_type': 'sha256',
  1334. 'log_file': 'foo.log',
  1335. }
  1336. ret.update(kwargs)
  1337. return ret
  1338. @skipIf(NO_MOCK, NO_MOCK_REASON)
  1339. def test_apply_config(self):
  1340. '''
  1341. Ensure that the environment and saltenv options work properly
  1342. '''
  1343. with patch.object(sconfig, '_adjust_log_file_override', Mock()), \
  1344. patch.object(sconfig, '_update_ssl_config', Mock()), \
  1345. patch.object(sconfig, '_update_discovery_config', Mock()):
  1346. # MASTER CONFIG
  1347. # Ensure that environment overrides saltenv when saltenv not
  1348. # explicitly passed.
  1349. defaults = self._get_defaults(environment='foo')
  1350. ret = sconfig.apply_master_config(defaults=defaults)
  1351. self.assertEqual(ret['environment'], 'foo')
  1352. self.assertEqual(ret['saltenv'], 'foo')
  1353. # Ensure that environment overrides saltenv when saltenv not
  1354. # explicitly passed.
  1355. defaults = self._get_defaults(environment='foo', saltenv='bar')
  1356. ret = sconfig.apply_master_config(defaults=defaults)
  1357. self.assertEqual(ret['environment'], 'bar')
  1358. self.assertEqual(ret['saltenv'], 'bar')
  1359. # If environment was not explicitly set, it should not be in the
  1360. # opts at all.
  1361. defaults = self._get_defaults()
  1362. ret = sconfig.apply_master_config(defaults=defaults)
  1363. self.assertNotIn('environment', ret)
  1364. self.assertEqual(ret['saltenv'], None)
  1365. # Same test as above but with saltenv explicitly set
  1366. defaults = self._get_defaults(saltenv='foo')
  1367. ret = sconfig.apply_master_config(defaults=defaults)
  1368. self.assertNotIn('environment', ret)
  1369. self.assertEqual(ret['saltenv'], 'foo')
  1370. # MINION CONFIG
  1371. # Ensure that environment overrides saltenv when saltenv not
  1372. # explicitly passed.
  1373. defaults = self._get_defaults(environment='foo')
  1374. ret = sconfig.apply_minion_config(defaults=defaults)
  1375. self.assertEqual(ret['environment'], 'foo')
  1376. self.assertEqual(ret['saltenv'], 'foo')
  1377. # Ensure that environment overrides saltenv when saltenv not
  1378. # explicitly passed.
  1379. defaults = self._get_defaults(environment='foo', saltenv='bar')
  1380. ret = sconfig.apply_minion_config(defaults=defaults)
  1381. self.assertEqual(ret['environment'], 'bar')
  1382. self.assertEqual(ret['saltenv'], 'bar')
  1383. # If environment was not explicitly set, it should not be in the
  1384. # opts at all.
  1385. defaults = self._get_defaults()
  1386. ret = sconfig.apply_minion_config(defaults=defaults)
  1387. self.assertNotIn('environment', ret)
  1388. self.assertEqual(ret['saltenv'], None)
  1389. # Same test as above but with saltenv explicitly set
  1390. defaults = self._get_defaults(saltenv='foo')
  1391. ret = sconfig.apply_minion_config(defaults=defaults)
  1392. self.assertNotIn('environment', ret)
  1393. self.assertEqual(ret['saltenv'], 'foo')
  1394. @skipIf(NO_MOCK, NO_MOCK_REASON)
  1395. class APIConfigTestCase(TestCase):
  1396. '''
  1397. TestCase for the api_config function in salt.config.__init__.py
  1398. '''
  1399. def setUp(self):
  1400. # Copy DEFAULT_API_OPTS to restore after the test
  1401. self.default_api_opts = salt.config.DEFAULT_API_OPTS.copy()
  1402. def tearDown(self):
  1403. # Reset DEFAULT_API_OPTS settings as to not interfere with other unit tests
  1404. salt.config.DEFAULT_API_OPTS = self.default_api_opts
  1405. def test_api_config_log_file_values(self):
  1406. '''
  1407. Tests the opts value of the 'log_file' after running through the
  1408. various default dict updates. 'log_file' should be updated to match
  1409. the DEFAULT_API_OPTS 'api_logfile' value.
  1410. '''
  1411. with patch('salt.config.client_config', MagicMock(return_value=MOCK_MASTER_DEFAULT_OPTS)):
  1412. expected = '{0}/var/log/salt/api'.format(
  1413. salt.syspaths.ROOT_DIR if salt.syspaths.ROOT_DIR != '/' else '')
  1414. if salt.utils.platform.is_windows():
  1415. expected = '{0}\\var\\log\\salt\\api'.format(
  1416. salt.syspaths.ROOT_DIR)
  1417. ret = salt.config.api_config('/some/fake/path')
  1418. self.assertEqual(ret['log_file'], expected)
  1419. def test_api_config_pidfile_values(self):
  1420. '''
  1421. Tests the opts value of the 'pidfile' after running through the
  1422. various default dict updates. 'pidfile' should be updated to match
  1423. the DEFAULT_API_OPTS 'api_pidfile' value.
  1424. '''
  1425. with patch('salt.config.client_config', MagicMock(return_value=MOCK_MASTER_DEFAULT_OPTS)):
  1426. expected = '{0}/var/run/salt-api.pid'.format(
  1427. salt.syspaths.ROOT_DIR if salt.syspaths.ROOT_DIR != '/' else '')
  1428. if salt.utils.platform.is_windows():
  1429. expected = '{0}\\var\\run\\salt-api.pid'.format(
  1430. salt.syspaths.ROOT_DIR)
  1431. ret = salt.config.api_config('/some/fake/path')
  1432. self.assertEqual(ret['pidfile'], expected)
  1433. @destructiveTest
  1434. def test_master_config_file_overrides_defaults(self):
  1435. '''
  1436. Tests the opts value of the api config values after running through the
  1437. various default dict updates that should be overridden by settings in
  1438. the user's master config file.
  1439. '''
  1440. foo_dir = '/foo/bar/baz'
  1441. hello_dir = '/hello/world'
  1442. if salt.utils.platform.is_windows():
  1443. foo_dir = 'c:\\foo\\bar\\baz'
  1444. hello_dir = 'c:\\hello\\world'
  1445. mock_master_config = {
  1446. 'api_pidfile': foo_dir,
  1447. 'api_logfile': hello_dir,
  1448. 'rest_timeout': 5
  1449. }
  1450. mock_master_config.update(MOCK_MASTER_DEFAULT_OPTS.copy())
  1451. with patch('salt.config.client_config',
  1452. MagicMock(return_value=mock_master_config)):
  1453. ret = salt.config.api_config('/some/fake/path')
  1454. self.assertEqual(ret['rest_timeout'], 5)
  1455. self.assertEqual(ret['api_pidfile'], foo_dir)
  1456. self.assertEqual(ret['pidfile'], foo_dir)
  1457. self.assertEqual(ret['api_logfile'], hello_dir)
  1458. self.assertEqual(ret['log_file'], hello_dir)
  1459. @destructiveTest
  1460. def test_api_config_prepend_root_dirs_return(self):
  1461. '''
  1462. Tests the opts value of the api_logfile, log_file, api_pidfile, and pidfile
  1463. when a custom root directory is used. This ensures that each of these
  1464. values is present in the list of opts keys that should have the root_dir
  1465. prepended when the api_config function returns the opts dictionary.
  1466. '''
  1467. mock_log = '/mock/root/var/log/salt/api'
  1468. mock_pid = '/mock/root/var/run/salt-api.pid'
  1469. mock_master_config = MOCK_MASTER_DEFAULT_OPTS.copy()
  1470. mock_master_config['root_dir'] = '/mock/root/'
  1471. if salt.utils.platform.is_windows():
  1472. mock_log = 'c:\\mock\\root\\var\\log\\salt\\api'
  1473. mock_pid = 'c:\\mock\\root\\var\\run\\salt-api.pid'
  1474. mock_master_config['root_dir'] = 'c:\\mock\\root'
  1475. with patch('salt.config.client_config',
  1476. MagicMock(return_value=mock_master_config)):
  1477. ret = salt.config.api_config('/some/fake/path')
  1478. self.assertEqual(ret['api_logfile'], mock_log)
  1479. self.assertEqual(ret['log_file'], mock_log)
  1480. self.assertEqual(ret['api_pidfile'], mock_pid)
  1481. self.assertEqual(ret['pidfile'], mock_pid)