test_config.py 66 KB

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