gitfs.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. """
  2. Base classes for gitfs/git_pillar integration tests
  3. """
  4. import errno
  5. import logging
  6. import os
  7. import shutil
  8. import tempfile
  9. import textwrap
  10. import attr
  11. import pytest
  12. import salt.utils.files
  13. import salt.utils.path
  14. import salt.utils.platform
  15. import salt.utils.yaml
  16. from salt.fileserver import gitfs
  17. from salt.pillar import git_pillar
  18. from salt.utils.immutabletypes import freeze
  19. from saltfactories.factories.base import DaemonFactory
  20. from saltfactories.factories.daemons.sshd import SshdDaemonFactory as _SshdDaemonFactory
  21. from saltfactories.utils.ports import get_unused_localhost_port
  22. from tests.support.case import ModuleCase
  23. from tests.support.helpers import patched_environ, requires_system_grains
  24. from tests.support.mixins import LoaderModuleMockMixin
  25. from tests.support.mock import patch
  26. from tests.support.runtests import RUNTIME_VARS
  27. log = logging.getLogger(__name__)
  28. USERNAME = "gitpillaruser"
  29. PASSWORD = "saltrules"
  30. _OPTS = freeze(
  31. {
  32. "__role": "minion",
  33. "environment": None,
  34. "pillarenv": None,
  35. "hash_type": "sha256",
  36. "file_roots": {},
  37. "state_top": "top.sls",
  38. "state_top_saltenv": None,
  39. "renderer": "yaml_jinja",
  40. "renderer_whitelist": [],
  41. "renderer_blacklist": [],
  42. "pillar_merge_lists": False,
  43. "git_pillar_base": "master",
  44. "git_pillar_branch": "master",
  45. "git_pillar_env": "",
  46. "git_pillar_fallback": "",
  47. "git_pillar_root": "",
  48. "git_pillar_ssl_verify": True,
  49. "git_pillar_global_lock": True,
  50. "git_pillar_user": "",
  51. "git_pillar_password": "",
  52. "git_pillar_insecure_auth": False,
  53. "git_pillar_privkey": "",
  54. "git_pillar_pubkey": "",
  55. "git_pillar_passphrase": "",
  56. "git_pillar_refspecs": [
  57. "+refs/heads/*:refs/remotes/origin/*",
  58. "+refs/tags/*:refs/tags/*",
  59. ],
  60. "git_pillar_includes": True,
  61. }
  62. )
  63. class SshdDaemonFactory(_SshdDaemonFactory):
  64. def apply_pre_start_states(self, salt_call_cli, testclass, username):
  65. if self.listen_port in self.check_ports:
  66. self.check_ports.remove(self.listen_port)
  67. if self.listen_port in self.listen_ports:
  68. self.listen_ports.remove(self.listen_port)
  69. self.listen_port = get_unused_localhost_port()
  70. self.check_ports.append(self.listen_port)
  71. self.listen_ports.append(self.listen_port)
  72. url = "ssh://{username}@127.0.0.1:{port}/~/repo.git".format(
  73. username=testclass.username, port=self.listen_port
  74. )
  75. url_extra_repo = "ssh://{username}@127.0.0.1:{port}/~/extra_repo.git".format(
  76. username=testclass.username, port=self.listen_port
  77. )
  78. home = "/root/.ssh"
  79. testclass.ext_opts = {
  80. "url": url,
  81. "url_extra_repo": url_extra_repo,
  82. "privkey_nopass": os.path.join(home, testclass.id_rsa_nopass),
  83. "pubkey_nopass": os.path.join(home, testclass.id_rsa_nopass + ".pub"),
  84. "privkey_withpass": os.path.join(home, testclass.id_rsa_withpass),
  85. "pubkey_withpass": os.path.join(home, testclass.id_rsa_withpass + ".pub"),
  86. "passphrase": testclass.passphrase,
  87. }
  88. ret = salt_call_cli.run(
  89. "state.apply",
  90. mods="git_pillar.ssh",
  91. pillar={
  92. "git_pillar": {
  93. "git_ssh": testclass.git_ssh,
  94. "id_rsa_nopass": testclass.id_rsa_nopass,
  95. "id_rsa_withpass": testclass.id_rsa_withpass,
  96. "sshd_bin": self.get_script_path(),
  97. "sshd_port": self.listen_port,
  98. "sshd_config_dir": str(self.config_dir),
  99. "master_user": username,
  100. "user": testclass.username,
  101. }
  102. },
  103. _timeout=240,
  104. )
  105. if ret.exitcode != 0:
  106. pytest.fail("Failed to apply the 'git_pillar.ssh' state")
  107. if next(iter(ret.json.values()))["result"] is not True:
  108. pytest.fail("Failed to apply the 'git_pillar.ssh' state")
  109. def set_known_host(self, salt_call_cli, username):
  110. ret = salt_call_cli.run(
  111. "ssh.set_known_host",
  112. user=username,
  113. hostname="127.0.0.1",
  114. port=self.listen_port,
  115. enc="ssh-rsa",
  116. fingerprint="fd:6f:7f:5d:06:6b:f2:06:0d:26:93:9e:5a:b5:19:46",
  117. hash_known_hosts=False,
  118. fingerprint_hash_type="md5",
  119. )
  120. if ret.exitcode != 0:
  121. pytest.fail("Failed to run 'ssh.set_known_host'")
  122. if "error" in ret.json:
  123. pytest.fail("Failed to run 'ssh.set_known_host'")
  124. @attr.s(kw_only=True, slots=True)
  125. class UwsgiDaemon(DaemonFactory):
  126. config_dir = attr.ib()
  127. listen_port = attr.ib(default=attr.Factory(get_unused_localhost_port))
  128. def __attrs_post_init__(self):
  129. if self.check_ports is None:
  130. self.check_ports = []
  131. self.check_ports.append(self.listen_port)
  132. super().__attrs_post_init__()
  133. def get_base_script_args(self):
  134. """
  135. Returns any additional arguments to pass to the CLI script
  136. """
  137. return ["--yaml", os.path.join(self.config_dir, "uwsgi.yml")]
  138. def apply_pre_start_states(self, salt_call_cli, testclass, root_dir):
  139. if self.listen_port in self.check_ports:
  140. self.check_ports.remove(self.listen_port)
  141. if self.listen_port in self.listen_ports:
  142. self.listen_ports.remove(self.listen_port)
  143. self.listen_port = get_unused_localhost_port()
  144. self.check_ports.append(self.listen_port)
  145. self.listen_ports.append(self.listen_port)
  146. config_dir = os.path.join(root_dir, "config")
  147. git_dir = os.path.join(root_dir, "git")
  148. testclass.repo_dir = repo_dir = os.path.join(git_dir, "repos")
  149. venv_dir = os.path.join(root_dir, "venv")
  150. uwsgi_bin = os.path.join(venv_dir, "bin", "uwsgi")
  151. pillar = {
  152. "git_pillar": {
  153. "config_dir": config_dir,
  154. "git_dir": git_dir,
  155. "venv_dir": venv_dir,
  156. "root_dir": root_dir,
  157. "uwsgi_port": self.listen_port,
  158. }
  159. }
  160. # Different libexec dir for git backend on Debian and FreeBSD-based systems
  161. if salt.utils.platform.is_freebsd():
  162. git_core = "/usr/local/libexec/git-core"
  163. else:
  164. git_core = "/usr/libexec/git-core"
  165. if not os.path.exists(git_core):
  166. git_core = "/usr/lib/git-core"
  167. if not os.path.exists(git_core):
  168. pytest.fail(
  169. "{} not found. Either git is not installed, or the test "
  170. "class needs to be updated.".format(git_core)
  171. )
  172. pillar["git_pillar"]["git-http-backend"] = os.path.join(
  173. git_core, "git-http-backend"
  174. )
  175. ret = salt_call_cli.run(
  176. "state.apply", mods="git_pillar.http.uwsgi", pillar=pillar, _timeout=120
  177. )
  178. if ret.exitcode != 0:
  179. pytest.fail("Failed to apply the 'git_pillar.http.uwsgi' state")
  180. if next(iter(ret.json.values()))["result"] is not True:
  181. pytest.fail("Failed to apply the 'git_pillar.http.uwsgi' state")
  182. @attr.s(kw_only=True, slots=True)
  183. class NginxDaemon(DaemonFactory):
  184. config_dir = attr.ib()
  185. uwsgi_port = attr.ib()
  186. listen_port = attr.ib(default=attr.Factory(get_unused_localhost_port))
  187. def __attrs_post_init__(self):
  188. if self.check_ports is None:
  189. self.check_ports = []
  190. self.check_ports.append(self.listen_port)
  191. super().__attrs_post_init__()
  192. def get_base_script_args(self):
  193. """
  194. Returns any additional arguments to pass to the CLI script
  195. """
  196. return ["-c", os.path.join(self.config_dir, "nginx.conf")]
  197. def apply_pre_start_states(self, salt_call_cli, testclass, root_dir):
  198. if self.listen_port in self.check_ports:
  199. self.check_ports.remove(self.listen_port)
  200. if self.listen_port in self.listen_ports:
  201. self.listen_ports.remove(self.listen_port)
  202. self.listen_port = get_unused_localhost_port()
  203. self.check_ports.append(self.listen_port)
  204. self.listen_ports.append(self.listen_port)
  205. config_dir = os.path.join(root_dir, "config")
  206. git_dir = os.path.join(root_dir, "git")
  207. url = "http://127.0.0.1:{port}/repo.git".format(port=self.listen_port)
  208. url_extra_repo = "http://127.0.0.1:{port}/extra_repo.git".format(
  209. port=self.listen_port
  210. )
  211. ext_opts = {"url": url, "url_extra_repo": url_extra_repo}
  212. # Add auth params if present (if so this will trigger the spawned
  213. # server to turn on HTTP basic auth).
  214. for credential_param in ("user", "password"):
  215. if hasattr(testclass, credential_param):
  216. ext_opts[credential_param] = getattr(testclass, credential_param)
  217. testclass.ext_opts = ext_opts
  218. testclass.nginx_port = self.listen_port
  219. auth_enabled = hasattr(testclass, "username") and hasattr(testclass, "password")
  220. pillar = {
  221. "git_pillar": {
  222. "config_dir": config_dir,
  223. "git_dir": git_dir,
  224. "uwsgi_port": self.uwsgi_port,
  225. "nginx_port": self.listen_port,
  226. "auth_enabled": auth_enabled,
  227. }
  228. }
  229. ret = salt_call_cli.run(
  230. "state.apply", mods="git_pillar.http.nginx", pillar=pillar
  231. )
  232. if ret.exitcode != 0:
  233. pytest.fail("Failed to apply the 'git_pillar.http.nginx' state")
  234. if next(iter(ret.json.values()))["result"] is not True:
  235. pytest.fail("Failed to apply the 'git_pillar.http.nginx' state")
  236. @pytest.fixture(scope="class")
  237. def ssh_pillar_tests_prep(request, salt_master, salt_minion):
  238. """
  239. Stand up an SSHD server to serve up git repos for tests.
  240. """
  241. salt_call_cli = salt_minion.get_salt_call_cli()
  242. sshd_bin = salt.utils.path.which("sshd")
  243. sshd_config_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  244. sshd_proc = SshdDaemonFactory(
  245. cli_script_name=sshd_bin,
  246. config_dir=sshd_config_dir,
  247. start_timeout=120,
  248. display_name=request.cls.__name__,
  249. )
  250. sshd_proc.register_before_start_callback(
  251. sshd_proc.apply_pre_start_states,
  252. salt_call_cli=salt_call_cli,
  253. testclass=request.cls,
  254. username=salt_master.config["user"],
  255. )
  256. sshd_proc.register_after_start_callback(
  257. sshd_proc.set_known_host,
  258. salt_call_cli=salt_call_cli,
  259. username=salt_master.config["user"],
  260. )
  261. try:
  262. sshd_proc.start()
  263. yield
  264. finally:
  265. request.cls.ext_opts = None
  266. salt_call_cli.run(
  267. "state.single", "user.absent", name=request.cls.username, purge=True
  268. )
  269. shutil.rmtree(sshd_config_dir, ignore_errors=True)
  270. ssh_dir = os.path.expanduser("~/.ssh")
  271. for filename in (
  272. request.cls.id_rsa_nopass,
  273. request.cls.id_rsa_nopass + ".pub",
  274. request.cls.id_rsa_withpass,
  275. request.cls.id_rsa_withpass + ".pub",
  276. request.cls.git_ssh,
  277. ):
  278. try:
  279. os.remove(os.path.join(ssh_dir, filename))
  280. except OSError as exc:
  281. if exc.errno != errno.ENOENT:
  282. raise
  283. sshd_proc.terminate()
  284. @pytest.fixture(scope="class")
  285. def webserver_pillar_tests_prep(request, salt_master, salt_minion):
  286. """
  287. Stand up an nginx + uWSGI + git-http-backend webserver to
  288. serve up git repos for tests.
  289. """
  290. salt_call_cli = salt_minion.get_salt_call_cli()
  291. root_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  292. config_dir = os.path.join(root_dir, "config")
  293. venv_dir = os.path.join(root_dir, "venv")
  294. uwsgi_bin = os.path.join(venv_dir, "bin", "uwsgi")
  295. uwsgi_proc = nginx_proc = None
  296. try:
  297. uwsgi_proc = UwsgiDaemon(
  298. cli_script_name=uwsgi_bin,
  299. config_dir=config_dir,
  300. start_timeout=120,
  301. display_name=request.cls.__name__,
  302. )
  303. uwsgi_proc.register_before_start_callback(
  304. uwsgi_proc.apply_pre_start_states,
  305. salt_call_cli=salt_call_cli,
  306. testclass=request.cls,
  307. root_dir=root_dir,
  308. )
  309. uwsgi_proc.start()
  310. nginx_proc = NginxDaemon(
  311. cli_script_name="nginx",
  312. config_dir=config_dir,
  313. start_timeout=120,
  314. uwsgi_port=uwsgi_proc.listen_port,
  315. display_name=request.cls.__name__,
  316. )
  317. nginx_proc.register_before_start_callback(
  318. nginx_proc.apply_pre_start_states,
  319. salt_call_cli=salt_call_cli,
  320. testclass=request.cls,
  321. root_dir=root_dir,
  322. )
  323. nginx_proc.start()
  324. yield
  325. finally:
  326. request.cls.repo_dir = request.cls.ext_opts = request.cls.nginx_port = None
  327. if uwsgi_proc:
  328. uwsgi_proc.terminate()
  329. if nginx_proc:
  330. nginx_proc.terminate()
  331. shutil.rmtree(root_dir, ignore_errors=True)
  332. @pytest.fixture(scope="class")
  333. def webserver_pillar_tests_prep_authenticated(request, webserver_pillar_tests_prep):
  334. url = "http://{username}:{password}@127.0.0.1:{port}/repo.git".format(
  335. username=request.cls.username,
  336. password=request.cls.password,
  337. port=request.cls.nginx_port,
  338. )
  339. url_extra_repo = "http://{username}:{password}@127.0.0.1:{port}/extra_repo.git".format(
  340. username=request.cls.username,
  341. password=request.cls.password,
  342. port=request.cls.nginx_port,
  343. )
  344. request.cls.ext_opts["url"] = url
  345. request.cls.ext_opts["url_extra_repo"] = url_extra_repo
  346. request.cls.ext_opts["username"] = request.cls.username
  347. request.cls.ext_opts["password"] = request.cls.password
  348. class GitTestBase(ModuleCase):
  349. """
  350. Base class for all gitfs/git_pillar tests.
  351. """
  352. maxDiff = None
  353. git_opts = '-c user.name="Foo Bar" -c user.email=foo@bar.com'
  354. def make_repo(self, root_dir, user="root"):
  355. raise NotImplementedError()
  356. class GitFSTestBase(GitTestBase, LoaderModuleMockMixin):
  357. """
  358. Base class for all gitfs tests
  359. """
  360. @requires_system_grains
  361. def setup_loader_modules(self, grains): # pylint: disable=W0221
  362. return {gitfs: {"__opts__": _OPTS.copy(), "__grains__": grains}}
  363. def make_repo(self, root_dir, user="root"):
  364. raise NotImplementedError()
  365. class GitPillarTestBase(GitTestBase, LoaderModuleMockMixin):
  366. """
  367. Base class for all git_pillar tests
  368. """
  369. bare_repo = bare_repo_backup = bare_extra_repo = bare_extra_repo_backup = None
  370. admin_repo = admin_repo_backup = admin_extra_repo = admin_extra_repo_backup = None
  371. @requires_system_grains
  372. def setup_loader_modules(self, grains): # pylint: disable=W0221
  373. return {git_pillar: {"__opts__": _OPTS.copy(), "__grains__": grains}}
  374. def get_pillar(self, ext_pillar_conf):
  375. """
  376. Run git_pillar with the specified configuration
  377. """
  378. cachedir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  379. self.addCleanup(shutil.rmtree, cachedir, ignore_errors=True)
  380. ext_pillar_opts = {"optimization_order": [0, 1, 2]}
  381. ext_pillar_opts.update(
  382. salt.utils.yaml.safe_load(
  383. ext_pillar_conf.format(
  384. cachedir=cachedir,
  385. extmods=os.path.join(cachedir, "extmods"),
  386. **self.ext_opts
  387. )
  388. )
  389. )
  390. with patch.dict(git_pillar.__opts__, ext_pillar_opts):
  391. return git_pillar.ext_pillar(
  392. "minion", {}, *ext_pillar_opts["ext_pillar"][0]["git"]
  393. )
  394. def make_repo(self, root_dir, user="root"):
  395. log.info("Creating test Git repo....")
  396. self.bare_repo = os.path.join(root_dir, "repo.git")
  397. self.bare_repo_backup = "{}.backup".format(self.bare_repo)
  398. self.admin_repo = os.path.join(root_dir, "admin")
  399. self.admin_repo_backup = "{}.backup".format(self.admin_repo)
  400. for dirname in (self.bare_repo, self.admin_repo):
  401. shutil.rmtree(dirname, ignore_errors=True)
  402. if os.path.exists(self.bare_repo_backup) and os.path.exists(
  403. self.admin_repo_backup
  404. ):
  405. shutil.copytree(self.bare_repo_backup, self.bare_repo)
  406. shutil.copytree(self.admin_repo_backup, self.admin_repo)
  407. return
  408. # Create bare repo
  409. self.run_function("git.init", [self.bare_repo], user=user, bare=True)
  410. # Clone bare repo
  411. self.run_function("git.clone", [self.admin_repo], url=self.bare_repo, user=user)
  412. def _push(branch, message):
  413. self.run_function("git.add", [self.admin_repo, "."], user=user)
  414. self.run_function(
  415. "git.commit",
  416. [self.admin_repo, message],
  417. user=user,
  418. git_opts=self.git_opts,
  419. )
  420. self.run_function(
  421. "git.push", [self.admin_repo], remote="origin", ref=branch, user=user,
  422. )
  423. with salt.utils.files.fopen(
  424. os.path.join(self.admin_repo, "top.sls"), "w"
  425. ) as fp_:
  426. fp_.write(
  427. textwrap.dedent(
  428. """\
  429. base:
  430. '*':
  431. - foo
  432. """
  433. )
  434. )
  435. with salt.utils.files.fopen(
  436. os.path.join(self.admin_repo, "foo.sls"), "w"
  437. ) as fp_:
  438. fp_.write(
  439. textwrap.dedent(
  440. """\
  441. branch: master
  442. mylist:
  443. - master
  444. mydict:
  445. master: True
  446. nested_list:
  447. - master
  448. nested_dict:
  449. master: True
  450. """
  451. )
  452. )
  453. # Add another file to be referenced using git_pillar_includes
  454. with salt.utils.files.fopen(
  455. os.path.join(self.admin_repo, "bar.sls"), "w"
  456. ) as fp_:
  457. fp_.write("included_pillar: True\n")
  458. # Add another file in subdir
  459. os.mkdir(os.path.join(self.admin_repo, "subdir"))
  460. with salt.utils.files.fopen(
  461. os.path.join(self.admin_repo, "subdir", "bar.sls"), "w"
  462. ) as fp_:
  463. fp_.write("from_subdir: True\n")
  464. _push("master", "initial commit")
  465. # Do the same with different values for "dev" branch
  466. self.run_function("git.checkout", [self.admin_repo], user=user, opts="-b dev")
  467. # The bar.sls shouldn't be in any branch but master
  468. self.run_function("git.rm", [self.admin_repo, "bar.sls"], user=user)
  469. with salt.utils.files.fopen(
  470. os.path.join(self.admin_repo, "top.sls"), "w"
  471. ) as fp_:
  472. fp_.write(
  473. textwrap.dedent(
  474. """\
  475. dev:
  476. '*':
  477. - foo
  478. """
  479. )
  480. )
  481. with salt.utils.files.fopen(
  482. os.path.join(self.admin_repo, "foo.sls"), "w"
  483. ) as fp_:
  484. fp_.write(
  485. textwrap.dedent(
  486. """\
  487. branch: dev
  488. mylist:
  489. - dev
  490. mydict:
  491. dev: True
  492. nested_list:
  493. - dev
  494. nested_dict:
  495. dev: True
  496. """
  497. )
  498. )
  499. _push("dev", "add dev branch")
  500. # Create just a top file in a separate repo, to be mapped to the base
  501. # env and referenced using git_pillar_includes
  502. self.run_function(
  503. "git.checkout", [self.admin_repo], user=user, opts="-b top_only"
  504. )
  505. # The top.sls should be the only file in this branch
  506. self.run_function(
  507. "git.rm",
  508. [self.admin_repo, "foo.sls", os.path.join("subdir", "bar.sls")],
  509. user=user,
  510. )
  511. with salt.utils.files.fopen(
  512. os.path.join(self.admin_repo, "top.sls"), "w"
  513. ) as fp_:
  514. fp_.write(
  515. textwrap.dedent(
  516. """\
  517. base:
  518. '*':
  519. - bar
  520. """
  521. )
  522. )
  523. _push("top_only", "add top_only branch")
  524. # Create just another top file in a separate repo, to be mapped to the base
  525. # env and including mounted.bar
  526. self.run_function(
  527. "git.checkout", [self.admin_repo], user=user, opts="-b top_mounted"
  528. )
  529. # The top.sls should be the only file in this branch
  530. with salt.utils.files.fopen(
  531. os.path.join(self.admin_repo, "top.sls"), "w"
  532. ) as fp_:
  533. fp_.write(
  534. textwrap.dedent(
  535. """\
  536. base:
  537. '*':
  538. - mounted.bar
  539. """
  540. )
  541. )
  542. _push("top_mounted", "add top_mounted branch")
  543. shutil.copytree(self.bare_repo, self.bare_repo_backup)
  544. shutil.copytree(self.admin_repo, self.admin_repo_backup)
  545. log.info("Test Git repo created.")
  546. def make_extra_repo(self, root_dir, user="root"):
  547. log.info("Creating extra test Git repo....")
  548. self.bare_extra_repo = os.path.join(root_dir, "extra_repo.git")
  549. self.bare_extra_repo_backup = "{}.backup".format(self.bare_extra_repo)
  550. self.admin_extra_repo = os.path.join(root_dir, "admin_extra")
  551. self.admin_extra_repo_backup = "{}.backup".format(self.admin_extra_repo)
  552. for dirname in (self.bare_extra_repo, self.admin_extra_repo):
  553. shutil.rmtree(dirname, ignore_errors=True)
  554. if os.path.exists(self.bare_extra_repo_backup) and os.path.exists(
  555. self.admin_extra_repo_backup
  556. ):
  557. shutil.copytree(self.bare_extra_repo_backup, self.bare_extra_repo)
  558. shutil.copytree(self.admin_extra_repo_backup, self.admin_extra_repo)
  559. return
  560. # Create bare extra repo
  561. self.run_function("git.init", [self.bare_extra_repo], user=user, bare=True)
  562. # Clone bare repo
  563. self.run_function(
  564. "git.clone", [self.admin_extra_repo], url=self.bare_extra_repo, user=user
  565. )
  566. def _push(branch, message):
  567. self.run_function("git.add", [self.admin_extra_repo, "."], user=user)
  568. self.run_function(
  569. "git.commit",
  570. [self.admin_extra_repo, message],
  571. user=user,
  572. git_opts=self.git_opts,
  573. )
  574. self.run_function(
  575. "git.push",
  576. [self.admin_extra_repo],
  577. remote="origin",
  578. ref=branch,
  579. user=user,
  580. )
  581. with salt.utils.files.fopen(
  582. os.path.join(self.admin_extra_repo, "top.sls"), "w"
  583. ) as fp_:
  584. fp_.write(
  585. textwrap.dedent(
  586. """\
  587. "{{saltenv}}":
  588. '*':
  589. - motd
  590. - nowhere.foo
  591. """
  592. )
  593. )
  594. with salt.utils.files.fopen(
  595. os.path.join(self.admin_extra_repo, "motd.sls"), "w"
  596. ) as fp_:
  597. fp_.write(
  598. textwrap.dedent(
  599. """\
  600. motd: The force will be with you. Always.
  601. """
  602. )
  603. )
  604. _push("master", "initial commit")
  605. shutil.copytree(self.bare_extra_repo, self.bare_extra_repo_backup)
  606. shutil.copytree(self.admin_extra_repo, self.admin_extra_repo_backup)
  607. log.info("Extra test Git repo created.")
  608. @classmethod
  609. def tearDownClass(cls):
  610. super().tearDownClass()
  611. for dirname in (
  612. cls.admin_repo,
  613. cls.admin_repo_backup,
  614. cls.admin_extra_repo,
  615. cls.admin_extra_repo_backup,
  616. cls.bare_repo,
  617. cls.bare_repo_backup,
  618. cls.bare_extra_repo,
  619. cls.bare_extra_repo_backup,
  620. ):
  621. if dirname is not None:
  622. shutil.rmtree(dirname, ignore_errors=True)
  623. class GitPillarSSHTestBase(GitPillarTestBase):
  624. """
  625. Base class for GitPython and Pygit2 SSH tests
  626. """
  627. id_rsa_nopass = id_rsa_withpass = None
  628. git_ssh = "/tmp/git_ssh"
  629. def setUp(self):
  630. """
  631. Create the SSH server and user, and create the git repo
  632. """
  633. log.info("%s.setUp() started...", self.__class__.__name__)
  634. super().setUp()
  635. root_dir = os.path.expanduser("~{}".format(self.username))
  636. if root_dir.startswith("~"):
  637. raise AssertionError(
  638. "Unable to resolve homedir for user '{}'".format(self.username)
  639. )
  640. self.make_repo(root_dir, user=self.username)
  641. self.make_extra_repo(root_dir, user=self.username)
  642. log.info("%s.setUp() complete.", self.__class__.__name__)
  643. def get_pillar(self, ext_pillar_conf):
  644. """
  645. Wrap the parent class' get_pillar() func in logic that temporarily
  646. changes the GIT_SSH to use our custom script, ensuring that the
  647. passphraselsess key is used to auth without needing to modify the root
  648. user's ssh config file.
  649. """
  650. with patched_environ(GIT_SSH=self.git_ssh):
  651. return super().get_pillar(ext_pillar_conf)
  652. class GitPillarHTTPTestBase(GitPillarTestBase):
  653. """
  654. Base class for GitPython and Pygit2 HTTP tests
  655. """
  656. def setUp(self):
  657. """
  658. Create and start the webserver, and create the git repo
  659. """
  660. log.info("%s.setUp() started...", self.__class__.__name__)
  661. super().setUp()
  662. self.make_repo(self.repo_dir)
  663. self.make_extra_repo(self.repo_dir)
  664. log.info("%s.setUp() complete", self.__class__.__name__)