ya 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #!/usr/bin/env sh
  2. # Please, keep this script in sync with arcadia/ya
  3. # Shell commands follow
  4. # Next line is bilingual: it starts a comment in Python, but do nothing in shell
  5. """:"
  6. # Find a suitable python interpreter
  7. for cmd in python3 python; do
  8. command -v > /dev/null $cmd && exec "$(command -v $cmd)" "$0" "$@"
  9. done
  10. echo "Python interpreter is not found in this system, please, install python" >&2
  11. exit 2
  12. ":"""
  13. # Previous line is bilingual: it ends a comment in Python, but do nothing in shell
  14. # Shell commands end here
  15. # Python script follows
  16. import os
  17. import sys
  18. import platform
  19. import time
  20. def add_stage_start_to_environ(stage_name):
  21. stages = os.environ.get('YA_STAGES', '')
  22. os.environ['YA_STAGES'] = stages + (':' if stages else '') + '{}@{}'.format(stage_name, time.time())
  23. RETRIES = 5
  24. HASH_PREFIX = 10
  25. REGISTRY_ENDPOINT = os.environ.get("YA_REGISTRY_ENDPOINT", "https://devtools-registry.s3.yandex.net")
  26. # Please do not change this dict, it is updated automatically
  27. # Start of mapping
  28. PLATFORM_MAP = {
  29. "data": {
  30. "darwin": {
  31. "md5": "30753e1e963294aea53e996de03fe594",
  32. "urls": [
  33. f"{REGISTRY_ENDPOINT}/7480268068"
  34. ]
  35. },
  36. "darwin-arm64": {
  37. "md5": "9840300edca2c0472f065b4381bf8514",
  38. "urls": [
  39. f"{REGISTRY_ENDPOINT}/7480267883"
  40. ]
  41. },
  42. "linux-aarch64": {
  43. "md5": "30e1cbcaa713ac733c213acd9d9b0c6c",
  44. "urls": [
  45. f"{REGISTRY_ENDPOINT}/7480267499"
  46. ]
  47. },
  48. "win32-clang-cl": {
  49. "md5": "e05b7f61829dd97d995411fb8d49bad7",
  50. "urls": [
  51. f"{REGISTRY_ENDPOINT}/7480268240"
  52. ]
  53. },
  54. "linux": {
  55. "md5": "a6139abb9c40c7a76b147f5bbde59bd3",
  56. "urls": [
  57. f"{REGISTRY_ENDPOINT}/7480268480"
  58. ]
  59. }
  60. }
  61. } # End of mapping
  62. add_stage_start_to_environ('ya-script-initialization')
  63. def create_dirs(path):
  64. try:
  65. os.makedirs(path)
  66. except OSError as e:
  67. import errno
  68. if e.errno != errno.EEXIST:
  69. raise
  70. return path
  71. def home_dir():
  72. # Do not trust $HOME, as it is unreliable in certain environments
  73. # Temporarily delete os.environ["HOME"] to force reading current home directory from /etc/passwd
  74. home_from_env = os.environ.pop("HOME", None)
  75. try:
  76. home_from_passwd = os.path.expanduser("~")
  77. if os.path.isabs(home_from_passwd):
  78. # This home dir is valid, prefer it over $HOME
  79. return home_from_passwd
  80. else:
  81. # When python is built with musl (this is quire weird though),
  82. # only users from /etc/passwd will be properly resolved,
  83. # as musl does not have nss module for LDAP integration.
  84. return home_from_env
  85. finally:
  86. if home_from_env is not None:
  87. os.environ["HOME"] = home_from_env
  88. def misc_root():
  89. return create_dirs(os.getenv('YA_CACHE_DIR') or os.path.join(home_dir(), '.ya'))
  90. def tool_root():
  91. return create_dirs(os.getenv('YA_CACHE_DIR_TOOLS') or os.path.join(misc_root(), 'tools'))
  92. # TODO: remove when switched to S3, won't be needed in OSS
  93. def ya_token():
  94. def get_token_from_file():
  95. try:
  96. with open(os.environ.get('YA_TOKEN_PATH', os.path.join(home_dir(), '.ya_token')), 'r') as f:
  97. return f.read().strip()
  98. except:
  99. pass
  100. return os.getenv('YA_TOKEN') or get_token_from_file()
  101. TOOLS_DIR = tool_root()
  102. def uniq(size=6):
  103. import string
  104. import random
  105. return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size))
  106. _ssl_is_tuned = False
  107. def _tune_ssl():
  108. global _ssl_is_tuned
  109. if _ssl_is_tuned:
  110. return
  111. try:
  112. import ssl
  113. ssl._create_default_https_context = ssl._create_unverified_context
  114. except AttributeError:
  115. pass
  116. try:
  117. import urllib3
  118. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  119. except (AttributeError, ImportError):
  120. pass
  121. _ssl_is_tuned = True
  122. def _fetch(url, into):
  123. import hashlib
  124. _tune_ssl()
  125. add_stage_start_to_environ('ya-script-download')
  126. from urllib.request import urlopen
  127. from urllib.request import Request
  128. from urllib.parse import urlparse
  129. request = Request(str(url))
  130. # TODO: Remove when switched to S3 distribution
  131. request.add_header('User-Agent', 'ya-bootstrap')
  132. token = ya_token()
  133. if token:
  134. request.add_header('Authorization', 'OAuth {}'.format(token))
  135. md5 = hashlib.md5()
  136. sys.stderr.write('Downloading %s ' % url)
  137. sys.stderr.flush()
  138. conn = urlopen(request, timeout=10)
  139. sys.stderr.write('[')
  140. sys.stderr.flush()
  141. try:
  142. with open(into, 'wb') as f:
  143. while True:
  144. block = conn.read(1024 * 1024)
  145. sys.stderr.write('.')
  146. sys.stderr.flush()
  147. if block:
  148. md5.update(block)
  149. f.write(block)
  150. else:
  151. break
  152. return md5.hexdigest()
  153. finally:
  154. sys.stderr.write('] ')
  155. sys.stderr.flush()
  156. def _atomic_fetch(url, into, md5):
  157. tmp_dest = into + '.' + uniq()
  158. try:
  159. real_md5 = _fetch(url, tmp_dest)
  160. if real_md5 != md5:
  161. raise Exception('MD5 mismatched: %s differs from %s' % (real_md5, md5))
  162. os.rename(tmp_dest, into)
  163. sys.stderr.write('OK\n')
  164. except Exception as e:
  165. sys.stderr.write('ERROR: ' + str(e) + '\n')
  166. raise
  167. finally:
  168. try:
  169. os.remove(tmp_dest)
  170. except OSError:
  171. pass
  172. def _extract(path, into):
  173. import tarfile
  174. tar = tarfile.open(path, errorlevel=2)
  175. # tar.extractall() will try to set file ownership according to the attributes stored in the archive
  176. # by calling TarFile.chown() method.
  177. # As this information is hardly relevant to the point of deployment / extraction,
  178. # it will just fail (python2) if ya is executed with root euid, or silently set non-existent numeric owner (python3)
  179. # to the files being extracted.
  180. # mock it with noop to retain current user ownership.
  181. tar.chown = lambda *args, **kwargs: None
  182. if sys.version_info >= (3, 12):
  183. tar.extractall(path=into, filter='data')
  184. else:
  185. tar.extractall(path=into)
  186. tar.close()
  187. def _get(urls, md5):
  188. dest_path = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX])
  189. if not os.path.exists(dest_path):
  190. for iter in range(RETRIES):
  191. try:
  192. _atomic_fetch(urls[iter % len(urls)], dest_path, md5)
  193. break
  194. except Exception:
  195. if iter + 1 == RETRIES:
  196. raise
  197. else:
  198. time.sleep(iter)
  199. return dest_path
  200. def _get_dir(urls, md5, ya_name):
  201. dest_dir = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX] + '_d')
  202. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  203. return dest_dir
  204. try:
  205. packed_path = _get(urls, md5)
  206. except Exception:
  207. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  208. return dest_dir
  209. raise
  210. add_stage_start_to_environ('ya-script-extract')
  211. tmp_dir = dest_dir + '.' + uniq()
  212. try:
  213. try:
  214. _extract(packed_path, tmp_dir)
  215. except Exception:
  216. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  217. return dest_dir
  218. raise
  219. try:
  220. os.rename(tmp_dir, dest_dir)
  221. except OSError as e:
  222. import errno
  223. if e.errno != errno.ENOTEMPTY:
  224. raise
  225. return dest_dir
  226. finally:
  227. import shutil
  228. shutil.rmtree(tmp_dir, ignore_errors=True)
  229. try:
  230. os.remove(packed_path)
  231. except Exception:
  232. pass
  233. def _mine_repo_root():
  234. # We think that this script is located in the root of the repo.
  235. return os.path.dirname(os.path.realpath(__file__))
  236. def main():
  237. if not os.path.exists(TOOLS_DIR):
  238. os.makedirs(TOOLS_DIR)
  239. result_args = sys.argv[1:]
  240. meta = PLATFORM_MAP['data']
  241. my_platform = platform.system().lower()
  242. my_machine = platform.machine().lower()
  243. if my_platform == 'linux':
  244. if 'ppc64le' in platform.platform():
  245. my_platform = 'linux-ppc64le'
  246. elif 'aarch64' in platform.platform():
  247. my_platform = 'linux-aarch64'
  248. else:
  249. my_platform = 'linux_musl'
  250. if my_platform == 'darwin' and my_machine == 'arm64':
  251. my_platform = 'darwin-arm64'
  252. def _platform_key(target_platform):
  253. """match by max prefix length, prefer shortest"""
  254. def _key_for_platform(platform):
  255. return len(os.path.commonprefix([target_platform, platform])), -len(platform)
  256. return _key_for_platform
  257. best_key = max(meta.keys(), key=_platform_key(my_platform))
  258. value = meta[best_key]
  259. ya_name = {'win32': 'ya-bin.exe', 'win32-clang-cl': 'ya-bin.exe'}.get(best_key, 'ya-bin') # XXX
  260. ya_dir = _get_dir(value['urls'], value['md5'], ya_name)
  261. add_stage_start_to_environ('ya-script-prepare')
  262. # Popen `args` must have `str` type
  263. ya_path = str(os.path.join(ya_dir, ya_name))
  264. env = os.environ.copy()
  265. if 'YA_SOURCE_ROOT' not in env:
  266. src_root = _mine_repo_root()
  267. if src_root is not None:
  268. env['YA_SOURCE_ROOT'] = src_root
  269. # Disable respawn for opensource/ya
  270. if __file__.endswith('ya/opensource/ya'):
  271. env['YA_NO_RESPAWN'] = os.environ.get('YA_NO_RESPAWN', '1')
  272. for env_name in [
  273. 'LD_PRELOAD',
  274. 'Y_PYTHON_SOURCE_ROOT',
  275. ]:
  276. if env_name in os.environ:
  277. sys.stderr.write(
  278. "Warn: {}='{}' is specified and may affect the correct operation of the ya\n".format(
  279. env_name, env[env_name]
  280. )
  281. )
  282. if os.name == 'nt':
  283. import subprocess
  284. p = subprocess.Popen([ya_path] + result_args, env=env)
  285. p.wait()
  286. sys.exit(p.returncode)
  287. else:
  288. os.execve(ya_path, [ya_path] + result_args, env)
  289. if __name__ == '__main__':
  290. try:
  291. main()
  292. except Exception as e:
  293. sys.stderr.write('ERROR: ' + str(e) + '\n')
  294. from traceback import format_exc
  295. sys.stderr.write(format_exc() + "\n")
  296. sys.exit(1)