test_fileclient.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for the salt fileclient
  4. '''
  5. # Import Python libs
  6. from __future__ import absolute_import
  7. import errno
  8. import logging
  9. import os
  10. import shutil
  11. # Import Salt Testing libs
  12. from tests.support.runtests import RUNTIME_VARS
  13. from tests.integration import AdaptedConfigurationTestCaseMixin
  14. from tests.support.mixins import LoaderModuleMockMixin
  15. from tests.support.mock import patch, Mock, MagicMock, NO_MOCK, NO_MOCK_REASON
  16. from tests.support.unit import TestCase, skipIf
  17. # Import Salt libs
  18. import salt.utils.files
  19. from salt.ext.six.moves import range
  20. from salt import fileclient
  21. from salt.ext import six
  22. log = logging.getLogger(__name__)
  23. class FileclientTestCase(TestCase):
  24. '''
  25. Fileclient test
  26. '''
  27. opts = {
  28. 'extension_modules': '',
  29. 'cachedir': '/__test__',
  30. }
  31. def _fake_makedir(self, num=errno.EEXIST):
  32. def _side_effect(*args, **kwargs):
  33. raise OSError(num, 'Errno {0}'.format(num))
  34. return Mock(side_effect=_side_effect)
  35. def test_cache_skips_makedirs_on_race_condition(self):
  36. '''
  37. If cache contains already a directory, do not raise an exception.
  38. '''
  39. with patch('os.path.isfile', lambda prm: False):
  40. for exists in range(2):
  41. with patch('os.makedirs', self._fake_makedir()):
  42. with fileclient.Client(self.opts)._cache_loc('testfile') as c_ref_itr:
  43. assert c_ref_itr == os.sep + os.sep.join(['__test__', 'files', 'base', 'testfile'])
  44. def test_cache_raises_exception_on_non_eexist_ioerror(self):
  45. '''
  46. If makedirs raises other than EEXIST errno, an exception should be raised.
  47. '''
  48. with patch('os.path.isfile', lambda prm: False):
  49. with patch('os.makedirs', self._fake_makedir(num=errno.EROFS)):
  50. with self.assertRaises(OSError):
  51. with fileclient.Client(self.opts)._cache_loc('testfile') as c_ref_itr:
  52. assert c_ref_itr == '/__test__/files/base/testfile'
  53. def test_extrn_path_with_long_filename(self):
  54. safe_file_name = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/' + ('A' * 254), 'base'))[-1]
  55. assert safe_file_name == 'A' * 254
  56. oversized_file_name = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/' + ('A' * 255), 'base'))[-1]
  57. assert len(oversized_file_name) < 256
  58. assert oversized_file_name != 'A' * 255
  59. oversized_file_with_query_params = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/file?' + ('A' * 255), 'base'))[-1]
  60. assert len(oversized_file_with_query_params) < 256
  61. SALTENVS = ('base', 'dev')
  62. SUBDIR = 'subdir'
  63. SUBDIR_FILES = ('foo.txt', 'bar.txt', 'baz.txt')
  64. def _get_file_roots(fs_root):
  65. return dict(
  66. [(x, [os.path.join(fs_root, x)]) for x in SALTENVS]
  67. )
  68. @skipIf(NO_MOCK, NO_MOCK_REASON)
  69. class FileClientTest(TestCase, AdaptedConfigurationTestCaseMixin, LoaderModuleMockMixin):
  70. def setup_loader_modules(self):
  71. FS_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_fs_root')
  72. CACHE_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_cache_root')
  73. MOCKED_OPTS = {
  74. 'file_roots': _get_file_roots(FS_ROOT),
  75. 'fileserver_backend': ['roots'],
  76. 'cachedir': CACHE_ROOT,
  77. 'file_client': 'local',
  78. }
  79. self.addCleanup(shutil.rmtree, FS_ROOT, ignore_errors=True)
  80. self.addCleanup(shutil.rmtree, CACHE_ROOT, ignore_errors=True)
  81. return {fileclient: {'__opts__': MOCKED_OPTS}}
  82. def setUp(self):
  83. self.file_client = fileclient.Client(self.master_opts)
  84. def tearDown(self):
  85. del self.file_client
  86. def test_file_list_emptydirs(self):
  87. '''
  88. Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
  89. '''
  90. with self.assertRaises(NotImplementedError):
  91. self.file_client.file_list_emptydirs()
  92. def test_get_file(self):
  93. '''
  94. Ensure that the fileclient class won't allow a direct call to get_file()
  95. '''
  96. with self.assertRaises(NotImplementedError):
  97. self.file_client.get_file(None)
  98. def test_get_file_client(self):
  99. minion_opts = self.get_temp_config('minion')
  100. minion_opts['file_client'] = 'remote'
  101. with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
  102. ret = fileclient.get_file_client(minion_opts)
  103. self.assertEqual('remote_client', ret)
  104. @skipIf(NO_MOCK, NO_MOCK_REASON)
  105. class FileclientCacheTest(TestCase, AdaptedConfigurationTestCaseMixin, LoaderModuleMockMixin):
  106. '''
  107. Tests for the fileclient caching. The LocalClient is the only thing we can
  108. test as it is the only way we can mock the fileclient (the tests run from
  109. the minion process, so the master cannot be mocked from test code).
  110. '''
  111. def setup_loader_modules(self):
  112. self.FS_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_fs_root')
  113. self.CACHE_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_cache_root')
  114. self.MOCKED_OPTS = {
  115. 'file_roots': _get_file_roots(self.FS_ROOT),
  116. 'fileserver_backend': ['roots'],
  117. 'cachedir': self.CACHE_ROOT,
  118. 'file_client': 'local',
  119. }
  120. self.addCleanup(shutil.rmtree, self.FS_ROOT, ignore_errors=True)
  121. self.addCleanup(shutil.rmtree, self.CACHE_ROOT, ignore_errors=True)
  122. return {fileclient: {'__opts__': self.MOCKED_OPTS}}
  123. def setUp(self):
  124. '''
  125. No need to add a dummy foo.txt to muddy up the github repo, just make
  126. our own fileserver root on-the-fly.
  127. '''
  128. def _new_dir(path):
  129. '''
  130. Add a new dir at ``path`` using os.makedirs. If the directory
  131. already exists, remove it recursively and then try to create it
  132. again.
  133. '''
  134. try:
  135. os.makedirs(path)
  136. except OSError as exc:
  137. if exc.errno == errno.EEXIST:
  138. # Just in case a previous test was interrupted, remove the
  139. # directory and try adding it again.
  140. shutil.rmtree(path)
  141. os.makedirs(path)
  142. else:
  143. raise
  144. # Crete the FS_ROOT
  145. for saltenv in SALTENVS:
  146. saltenv_root = os.path.join(self.FS_ROOT, saltenv)
  147. # Make sure we have a fresh root dir for this saltenv
  148. _new_dir(saltenv_root)
  149. path = os.path.join(saltenv_root, 'foo.txt')
  150. with salt.utils.files.fopen(path, 'w') as fp_:
  151. fp_.write(
  152. 'This is a test file in the \'{0}\' saltenv.\n'
  153. .format(saltenv)
  154. )
  155. subdir_abspath = os.path.join(saltenv_root, SUBDIR)
  156. os.makedirs(subdir_abspath)
  157. for subdir_file in SUBDIR_FILES:
  158. path = os.path.join(subdir_abspath, subdir_file)
  159. with salt.utils.files.fopen(path, 'w') as fp_:
  160. fp_.write(
  161. 'This is file \'{0}\' in subdir \'{1} from saltenv '
  162. '\'{2}\''.format(subdir_file, SUBDIR, saltenv)
  163. )
  164. # Create the CACHE_ROOT
  165. _new_dir(self.CACHE_ROOT)
  166. def test_cache_dir(self):
  167. '''
  168. Ensure entire directory is cached to correct location
  169. '''
  170. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  171. patched_opts.update(self.MOCKED_OPTS)
  172. with patch.dict(fileclient.__opts__, patched_opts):
  173. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  174. for saltenv in SALTENVS:
  175. self.assertTrue(
  176. client.cache_dir(
  177. 'salt://{0}'.format(SUBDIR),
  178. saltenv,
  179. cachedir=None
  180. )
  181. )
  182. for subdir_file in SUBDIR_FILES:
  183. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  184. 'files',
  185. saltenv,
  186. SUBDIR,
  187. subdir_file)
  188. # Double check that the content of the cached file
  189. # identifies it as being from the correct saltenv. The
  190. # setUp function creates the file with the name of the
  191. # saltenv mentioned in the file, so a simple 'in' check is
  192. # sufficient here. If opening the file raises an exception,
  193. # this is a problem, so we are not catching the exception
  194. # and letting it be raised so that the test fails.
  195. with salt.utils.files.fopen(cache_loc) as fp_:
  196. content = fp_.read()
  197. log.debug('cache_loc = %s', cache_loc)
  198. log.debug('content = %s', content)
  199. self.assertTrue(subdir_file in content)
  200. self.assertTrue(SUBDIR in content)
  201. self.assertTrue(saltenv in content)
  202. def test_cache_dir_with_alternate_cachedir_and_absolute_path(self):
  203. '''
  204. Ensure entire directory is cached to correct location when an alternate
  205. cachedir is specified and that cachedir is an absolute path
  206. '''
  207. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  208. patched_opts.update(self.MOCKED_OPTS)
  209. alt_cachedir = os.path.join(RUNTIME_VARS.TMP, 'abs_cachedir')
  210. with patch.dict(fileclient.__opts__, patched_opts):
  211. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  212. for saltenv in SALTENVS:
  213. self.assertTrue(
  214. client.cache_dir(
  215. 'salt://{0}'.format(SUBDIR),
  216. saltenv,
  217. cachedir=alt_cachedir
  218. )
  219. )
  220. for subdir_file in SUBDIR_FILES:
  221. cache_loc = os.path.join(alt_cachedir,
  222. 'files',
  223. saltenv,
  224. SUBDIR,
  225. subdir_file)
  226. # Double check that the content of the cached file
  227. # identifies it as being from the correct saltenv. The
  228. # setUp function creates the file with the name of the
  229. # saltenv mentioned in the file, so a simple 'in' check is
  230. # sufficient here. If opening the file raises an exception,
  231. # this is a problem, so we are not catching the exception
  232. # and letting it be raised so that the test fails.
  233. with salt.utils.files.fopen(cache_loc) as fp_:
  234. content = fp_.read()
  235. log.debug('cache_loc = %s', cache_loc)
  236. log.debug('content = %s', content)
  237. self.assertTrue(subdir_file in content)
  238. self.assertTrue(SUBDIR in content)
  239. self.assertTrue(saltenv in content)
  240. def test_cache_dir_with_alternate_cachedir_and_relative_path(self):
  241. '''
  242. Ensure entire directory is cached to correct location when an alternate
  243. cachedir is specified and that cachedir is a relative path
  244. '''
  245. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  246. patched_opts.update(self.MOCKED_OPTS)
  247. alt_cachedir = 'foo'
  248. with patch.dict(fileclient.__opts__, patched_opts):
  249. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  250. for saltenv in SALTENVS:
  251. self.assertTrue(
  252. client.cache_dir(
  253. 'salt://{0}'.format(SUBDIR),
  254. saltenv,
  255. cachedir=alt_cachedir
  256. )
  257. )
  258. for subdir_file in SUBDIR_FILES:
  259. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  260. alt_cachedir,
  261. 'files',
  262. saltenv,
  263. SUBDIR,
  264. subdir_file)
  265. # Double check that the content of the cached file
  266. # identifies it as being from the correct saltenv. The
  267. # setUp function creates the file with the name of the
  268. # saltenv mentioned in the file, so a simple 'in' check is
  269. # sufficient here. If opening the file raises an exception,
  270. # this is a problem, so we are not catching the exception
  271. # and letting it be raised so that the test fails.
  272. with salt.utils.files.fopen(cache_loc) as fp_:
  273. content = fp_.read()
  274. log.debug('cache_loc = %s', cache_loc)
  275. log.debug('content = %s', content)
  276. self.assertTrue(subdir_file in content)
  277. self.assertTrue(SUBDIR in content)
  278. self.assertTrue(saltenv in content)
  279. def test_cache_file(self):
  280. '''
  281. Ensure file is cached to correct location
  282. '''
  283. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  284. patched_opts.update(self.MOCKED_OPTS)
  285. with patch.dict(fileclient.__opts__, patched_opts):
  286. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  287. for saltenv in SALTENVS:
  288. self.assertTrue(
  289. client.cache_file('salt://foo.txt', saltenv, cachedir=None)
  290. )
  291. cache_loc = os.path.join(
  292. fileclient.__opts__['cachedir'], 'files', saltenv, 'foo.txt')
  293. # Double check that the content of the cached file identifies
  294. # it as being from the correct saltenv. The setUp function
  295. # creates the file with the name of the saltenv mentioned in
  296. # the file, so a simple 'in' check is sufficient here. If
  297. # opening the file raises an exception, this is a problem, so
  298. # we are not catching the exception and letting it be raised so
  299. # that the test fails.
  300. with salt.utils.files.fopen(cache_loc) as fp_:
  301. content = fp_.read()
  302. log.debug('cache_loc = %s', cache_loc)
  303. log.debug('content = %s', content)
  304. self.assertTrue(saltenv in content)
  305. def test_cache_file_with_alternate_cachedir_and_absolute_path(self):
  306. '''
  307. Ensure file is cached to correct location when an alternate cachedir is
  308. specified and that cachedir is an absolute path
  309. '''
  310. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  311. patched_opts.update(self.MOCKED_OPTS)
  312. alt_cachedir = os.path.join(RUNTIME_VARS.TMP, 'abs_cachedir')
  313. with patch.dict(fileclient.__opts__, patched_opts):
  314. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  315. for saltenv in SALTENVS:
  316. self.assertTrue(
  317. client.cache_file('salt://foo.txt',
  318. saltenv,
  319. cachedir=alt_cachedir)
  320. )
  321. cache_loc = os.path.join(alt_cachedir,
  322. 'files',
  323. saltenv,
  324. 'foo.txt')
  325. # Double check that the content of the cached file identifies
  326. # it as being from the correct saltenv. The setUp function
  327. # creates the file with the name of the saltenv mentioned in
  328. # the file, so a simple 'in' check is sufficient here. If
  329. # opening the file raises an exception, this is a problem, so
  330. # we are not catching the exception and letting it be raised so
  331. # that the test fails.
  332. with salt.utils.files.fopen(cache_loc) as fp_:
  333. content = fp_.read()
  334. log.debug('cache_loc = %s', cache_loc)
  335. log.debug('content = %s', content)
  336. self.assertTrue(saltenv in content)
  337. def test_cache_file_with_alternate_cachedir_and_relative_path(self):
  338. '''
  339. Ensure file is cached to correct location when an alternate cachedir is
  340. specified and that cachedir is a relative path
  341. '''
  342. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  343. patched_opts.update(self.MOCKED_OPTS)
  344. alt_cachedir = 'foo'
  345. with patch.dict(fileclient.__opts__, patched_opts):
  346. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  347. for saltenv in SALTENVS:
  348. self.assertTrue(
  349. client.cache_file('salt://foo.txt',
  350. saltenv,
  351. cachedir=alt_cachedir)
  352. )
  353. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  354. alt_cachedir,
  355. 'files',
  356. saltenv,
  357. 'foo.txt')
  358. # Double check that the content of the cached file identifies
  359. # it as being from the correct saltenv. The setUp function
  360. # creates the file with the name of the saltenv mentioned in
  361. # the file, so a simple 'in' check is sufficient here. If
  362. # opening the file raises an exception, this is a problem, so
  363. # we are not catching the exception and letting it be raised so
  364. # that the test fails.
  365. with salt.utils.files.fopen(cache_loc) as fp_:
  366. content = fp_.read()
  367. log.debug('cache_loc = %s', cache_loc)
  368. log.debug('content = %s', content)
  369. self.assertTrue(saltenv in content)
  370. def test_cache_dest(self):
  371. '''
  372. Tests functionality for cache_dest
  373. '''
  374. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  375. patched_opts.update(self.MOCKED_OPTS)
  376. relpath = 'foo.com/bar.txt'
  377. cachedir = self.minion_opts['cachedir']
  378. def _external(saltenv='base'):
  379. return salt.utils.path.join(
  380. patched_opts['cachedir'],
  381. 'extrn_files',
  382. saltenv,
  383. relpath)
  384. def _salt(saltenv='base'):
  385. return salt.utils.path.join(
  386. patched_opts['cachedir'],
  387. 'files',
  388. saltenv,
  389. relpath)
  390. def _check(ret, expected):
  391. assert ret == expected, '{0} != {1}'.format(ret, expected)
  392. with patch.dict(fileclient.__opts__, patched_opts):
  393. client = fileclient.get_file_client(
  394. fileclient.__opts__, pillar=False)
  395. _check(client.cache_dest('https://' + relpath),
  396. _external())
  397. _check(client.cache_dest('https://' + relpath, 'dev'),
  398. _external('dev'))
  399. _check(client.cache_dest('salt://' + relpath),
  400. _salt())
  401. _check(client.cache_dest('salt://' + relpath, 'dev'),
  402. _salt('dev'))
  403. _check(client.cache_dest('salt://' + relpath + '?saltenv=dev'),
  404. _salt('dev'))
  405. _check('/foo/bar', '/foo/bar')