ya 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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": "45c63c225f789d33a465ae3d5b64f7ef",
  32. "urls": [
  33. f"{REGISTRY_ENDPOINT}/6178064410"
  34. ]
  35. },
  36. "darwin-arm64": {
  37. "md5": "e6f6dbc072ff1872a9d5fb9324ea1d31",
  38. "urls": [
  39. f"{REGISTRY_ENDPOINT}/6178063973"
  40. ]
  41. },
  42. "linux-aarch64": {
  43. "md5": "ad86306e4e3658cd8cfc95292d7b5a10",
  44. "urls": [
  45. f"{REGISTRY_ENDPOINT}/6178063478"
  46. ]
  47. },
  48. "win32-clang-cl": {
  49. "md5": "f4df6cde99415f82f3ec5827918b65e4",
  50. "urls": [
  51. f"{REGISTRY_ENDPOINT}/6178065184"
  52. ]
  53. },
  54. "linux": {
  55. "md5": "38099bfe05628c5a677631730558333a",
  56. "urls": [
  57. f"{REGISTRY_ENDPOINT}/6178066131"
  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. tar.extractall(path=into)
  183. tar.close()
  184. def _get(urls, md5):
  185. dest_path = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX])
  186. if not os.path.exists(dest_path):
  187. for iter in range(RETRIES):
  188. try:
  189. _atomic_fetch(urls[iter % len(urls)], dest_path, md5)
  190. break
  191. except Exception:
  192. if iter + 1 == RETRIES:
  193. raise
  194. else:
  195. time.sleep(iter)
  196. return dest_path
  197. def _get_dir(urls, md5, ya_name):
  198. dest_dir = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX] + '_d')
  199. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  200. return dest_dir
  201. try:
  202. packed_path = _get(urls, md5)
  203. except Exception:
  204. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  205. return dest_dir
  206. raise
  207. add_stage_start_to_environ('ya-script-extract')
  208. tmp_dir = dest_dir + '.' + uniq()
  209. try:
  210. try:
  211. _extract(packed_path, tmp_dir)
  212. except Exception:
  213. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  214. return dest_dir
  215. raise
  216. try:
  217. os.rename(tmp_dir, dest_dir)
  218. except OSError as e:
  219. import errno
  220. if e.errno != errno.ENOTEMPTY:
  221. raise
  222. return dest_dir
  223. finally:
  224. import shutil
  225. shutil.rmtree(tmp_dir, ignore_errors=True)
  226. try:
  227. os.remove(packed_path)
  228. except Exception:
  229. pass
  230. def _mine_repo_root():
  231. # We think that this script is located in the root of the repo.
  232. return os.path.dirname(os.path.realpath(__file__))
  233. def main():
  234. if not os.path.exists(TOOLS_DIR):
  235. os.makedirs(TOOLS_DIR)
  236. result_args = sys.argv[1:]
  237. meta = PLATFORM_MAP['data']
  238. my_platform = platform.system().lower()
  239. my_machine = platform.machine().lower()
  240. if my_platform == 'linux':
  241. if 'ppc64le' in platform.platform():
  242. my_platform = 'linux-ppc64le'
  243. elif 'aarch64' in platform.platform():
  244. my_platform = 'linux-aarch64'
  245. else:
  246. my_platform = 'linux_musl'
  247. if my_platform == 'darwin' and my_machine == 'arm64':
  248. my_platform = 'darwin-arm64'
  249. def _platform_key(target_platform):
  250. """match by max prefix length, prefer shortest"""
  251. def _key_for_platform(platform):
  252. return len(os.path.commonprefix([target_platform, platform])), -len(platform)
  253. return _key_for_platform
  254. best_key = max(meta.keys(), key=_platform_key(my_platform))
  255. value = meta[best_key]
  256. ya_name = {'win32': 'ya-bin.exe', 'win32-clang-cl': 'ya-bin.exe'}.get(best_key, 'ya-bin') # XXX
  257. ya_dir = _get_dir(value['urls'], value['md5'], ya_name)
  258. add_stage_start_to_environ('ya-script-prepare')
  259. # Popen `args` must have `str` type
  260. ya_path = str(os.path.join(ya_dir, ya_name))
  261. env = os.environ.copy()
  262. if 'YA_SOURCE_ROOT' not in env:
  263. src_root = _mine_repo_root()
  264. if src_root is not None:
  265. env['YA_SOURCE_ROOT'] = src_root
  266. # Disable respawn for opensource/ya
  267. if __file__.endswith('ya/opensource/ya'):
  268. env['YA_NO_RESPAWN'] = os.environ.get('YA_NO_RESPAWN', '1')
  269. for env_name in [
  270. 'LD_PRELOAD',
  271. 'Y_PYTHON_SOURCE_ROOT',
  272. ]:
  273. if env_name in os.environ:
  274. sys.stderr.write(
  275. "Warn: {}='{}' is specified and may affect the correct operation of the ya\n".format(
  276. env_name, env[env_name]
  277. )
  278. )
  279. if os.name == 'nt':
  280. import subprocess
  281. p = subprocess.Popen([ya_path] + result_args, env=env)
  282. p.wait()
  283. sys.exit(p.returncode)
  284. else:
  285. os.execve(ya_path, [ya_path] + result_args, env)
  286. if __name__ == '__main__':
  287. try:
  288. main()
  289. except Exception as e:
  290. sys.stderr.write('ERROR: ' + str(e) + '\n')
  291. from traceback import format_exc
  292. sys.stderr.write(format_exc() + "\n")
  293. sys.exit(1)