sync.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. from __future__ import annotations
  2. import importlib.metadata
  3. import os
  4. import shlex
  5. import subprocess
  6. from devenv import constants
  7. from devenv.lib import colima, config, fs, limactl, proc, venv
  8. # TODO: need to replace this with a nicer process executor in devenv.lib
  9. def run_procs(
  10. repo: str,
  11. reporoot: str,
  12. venv_path: str,
  13. _procs: tuple[tuple[str, tuple[str, ...], dict[str, str]], ...],
  14. verbose: bool = False,
  15. ) -> bool:
  16. procs: list[tuple[str, tuple[str, ...], subprocess.Popen[bytes]]] = []
  17. stdout = subprocess.PIPE if not verbose else None
  18. stderr = subprocess.STDOUT if not verbose else None
  19. for name, cmd, extra_env in _procs:
  20. print(f"⏳ {name}")
  21. if constants.DEBUG:
  22. proc.xtrace(cmd)
  23. env = {
  24. **constants.user_environ,
  25. **proc.base_env,
  26. "VIRTUAL_ENV": venv_path,
  27. "PATH": f"{venv_path}/bin:{reporoot}/.devenv/bin:{proc.base_path}",
  28. }
  29. if extra_env:
  30. env = {**env, **extra_env}
  31. procs.append(
  32. (
  33. name,
  34. cmd,
  35. subprocess.Popen(
  36. cmd,
  37. stdout=stdout,
  38. stderr=stderr,
  39. env=env,
  40. cwd=reporoot,
  41. ),
  42. )
  43. )
  44. all_good = True
  45. for name, final_cmd, p in procs:
  46. out, _ = p.communicate()
  47. if p.returncode != 0:
  48. all_good = False
  49. out_str = f"Output:\n{out.decode()}" if not verbose else ""
  50. print(
  51. f"""
  52. ❌ {name}
  53. failed command (code {p.returncode}):
  54. {shlex.join(final_cmd)}
  55. {out_str}
  56. """
  57. )
  58. else:
  59. print(f"✅ {name}")
  60. return all_good
  61. # Temporary, see https://github.com/getsentry/sentry/pull/78881
  62. def check_minimum_version(minimum_version: str):
  63. version = importlib.metadata.version("sentry-devenv")
  64. parsed_version = tuple(map(int, version.split(".")))
  65. parsed_minimum_version = tuple(map(int, minimum_version.split(".")))
  66. if parsed_version < parsed_minimum_version:
  67. raise SystemExit(
  68. f"""
  69. Hi! To reduce potential breakage we've defined a minimum
  70. devenv version ({minimum_version}) to run sync.
  71. Please run the following to update your global devenv to the minimum:
  72. {constants.root}/venv/bin/pip install -U 'sentry-devenv=={minimum_version}'
  73. Then, use it to run sync this one time.
  74. {constants.root}/bin/devenv sync
  75. """
  76. )
  77. def main(context: dict[str, str]) -> int:
  78. check_minimum_version("1.13.0")
  79. repo = context["repo"]
  80. reporoot = context["reporoot"]
  81. repo_config = config.get_config(f"{reporoot}/devenv/config.ini")
  82. # TODO: context["verbose"]
  83. verbose = os.environ.get("SENTRY_DEVENV_VERBOSE") is not None
  84. FRONTEND_ONLY = os.environ.get("SENTRY_DEVENV_FRONTEND_ONLY") is not None
  85. USE_NEW_DEVSERVICES = os.environ.get("USE_NEW_DEVSERVICES") == "1"
  86. from devenv.lib import node
  87. node.install(
  88. repo_config["node"]["version"],
  89. repo_config["node"][constants.SYSTEM_MACHINE],
  90. repo_config["node"][f"{constants.SYSTEM_MACHINE}_sha256"],
  91. reporoot,
  92. )
  93. node.install_yarn(repo_config["node"]["yarn_version"], reporoot)
  94. # no more imports from devenv past this point! if the venv is recreated
  95. # then we won't have access to devenv libs until it gets reinstalled
  96. # venv's still needed for frontend because repo-local devenv and pre-commit
  97. # exist inside it
  98. venv_dir, python_version, requirements, editable_paths, bins = venv.get(reporoot, repo)
  99. url, sha256 = config.get_python(reporoot, python_version)
  100. print(f"ensuring {repo} venv at {venv_dir}...")
  101. venv.ensure(venv_dir, python_version, url, sha256)
  102. if constants.DARWIN:
  103. colima.install(
  104. repo_config["colima"]["version"],
  105. repo_config["colima"][constants.SYSTEM_MACHINE],
  106. repo_config["colima"][f"{constants.SYSTEM_MACHINE}_sha256"],
  107. reporoot,
  108. )
  109. limactl.install(
  110. repo_config["lima"]["version"],
  111. repo_config["lima"][constants.SYSTEM_MACHINE],
  112. repo_config["lima"][f"{constants.SYSTEM_MACHINE}_sha256"],
  113. reporoot,
  114. )
  115. if not run_procs(
  116. repo,
  117. reporoot,
  118. venv_dir,
  119. (
  120. # TODO: devenv should provide a job runner (jobs run in parallel, tasks run sequentially)
  121. (
  122. "python dependencies (1/4)",
  123. (
  124. # upgrading pip first
  125. "pip",
  126. "install",
  127. "--constraint",
  128. "requirements-dev-frozen.txt",
  129. "pip",
  130. ),
  131. {},
  132. ),
  133. ),
  134. verbose,
  135. ):
  136. return 1
  137. if not run_procs(
  138. repo,
  139. reporoot,
  140. venv_dir,
  141. (
  142. (
  143. # Spreading out the network load by installing js,
  144. # then py in the next batch.
  145. "javascript dependencies (1/1)",
  146. (
  147. "yarn",
  148. "install",
  149. "--frozen-lockfile",
  150. "--no-progress",
  151. "--non-interactive",
  152. ),
  153. {
  154. "NODE_ENV": "development",
  155. },
  156. ),
  157. (
  158. "python dependencies (2/4)",
  159. (
  160. "pip",
  161. "uninstall",
  162. "-qqy",
  163. "djangorestframework-stubs",
  164. "django-stubs",
  165. ),
  166. {},
  167. ),
  168. ),
  169. verbose,
  170. ):
  171. return 1
  172. if not run_procs(
  173. repo,
  174. reporoot,
  175. venv_dir,
  176. (
  177. # could opt out of syncing python if FRONTEND_ONLY but only if repo-local devenv
  178. # and pre-commit were moved to inside devenv and not the sentry venv
  179. (
  180. "python dependencies (3/4)",
  181. (
  182. "pip",
  183. "install",
  184. "--constraint",
  185. "requirements-dev-frozen.txt",
  186. "-r",
  187. "requirements-dev-frozen.txt",
  188. ),
  189. {},
  190. ),
  191. ),
  192. verbose,
  193. ):
  194. return 1
  195. if not run_procs(
  196. repo,
  197. reporoot,
  198. venv_dir,
  199. (
  200. (
  201. "python dependencies (4/4)",
  202. ("python3", "-m", "tools.fast_editable", "--path", "."),
  203. {},
  204. ),
  205. ("pre-commit dependencies", ("pre-commit", "install", "--install-hooks", "-f"), {}),
  206. ),
  207. verbose,
  208. ):
  209. return 1
  210. fs.ensure_symlink("../../config/hooks/post-merge", f"{reporoot}/.git/hooks/post-merge")
  211. if not os.path.exists(f"{constants.home}/.sentry/config.yml") or not os.path.exists(
  212. f"{constants.home}/.sentry/sentry.conf.py"
  213. ):
  214. proc.run((f"{venv_dir}/bin/sentry", "init", "--dev"))
  215. # Frontend engineers don't necessarily always have devservices running and
  216. # can configure to skip them to save on local resources
  217. if FRONTEND_ONLY:
  218. print("Skipping python migrations since SENTRY_DEVENV_FRONTEND_ONLY is set.")
  219. return 0
  220. if USE_NEW_DEVSERVICES:
  221. # Ensure old sentry devservices is not being used, otherwise ports will conflict
  222. proc.run(
  223. (
  224. f"{venv_dir}/bin/{repo}",
  225. "devservices",
  226. "down",
  227. ),
  228. pathprepend=f"{reporoot}/.devenv/bin",
  229. exit=True,
  230. )
  231. proc.run(
  232. (f"{venv_dir}/bin/devservices", "up", "--mode", "migrations"),
  233. pathprepend=f"{reporoot}/.devenv/bin",
  234. exit=True,
  235. )
  236. else:
  237. # TODO: check healthchecks for redis and postgres to short circuit this
  238. proc.run(
  239. (
  240. f"{venv_dir}/bin/{repo}",
  241. "devservices",
  242. "up",
  243. "redis",
  244. "postgres",
  245. ),
  246. pathprepend=f"{reporoot}/.devenv/bin",
  247. exit=True,
  248. )
  249. if not run_procs(
  250. repo,
  251. reporoot,
  252. venv_dir,
  253. (
  254. (
  255. "python migrations",
  256. ("make", "apply-migrations"),
  257. {},
  258. ),
  259. ),
  260. verbose,
  261. ):
  262. return 1
  263. postgres_container = (
  264. "sentry_postgres" if os.environ.get("USE_NEW_DEVSERVICES") != "1" else "sentry-postgres-1"
  265. )
  266. # faster prerequisite check than starting up sentry and running createuser idempotently
  267. stdout = proc.run(
  268. (
  269. "docker",
  270. "exec",
  271. postgres_container,
  272. "psql",
  273. "sentry",
  274. "postgres",
  275. "-t",
  276. "-c",
  277. "select exists (select from auth_user where email = 'admin@sentry.io')",
  278. ),
  279. stdout=True,
  280. )
  281. if stdout != "t":
  282. proc.run(
  283. (
  284. f"{venv_dir}/bin/sentry",
  285. "createuser",
  286. "--superuser",
  287. "--email",
  288. "admin@sentry.io",
  289. "--password",
  290. "admin",
  291. "--no-input",
  292. )
  293. )
  294. return 0