1
0

test_config.py 66 KB

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