ya 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. #!/usr/bin/env sh
  2. # Shell commands follow
  3. # Next line is bilingual: it starts a comment in Python, but do nothing in shell
  4. """:"
  5. # Find a suitable python interpreter
  6. for cmd in python3 python; do
  7. command -v > /dev/null $cmd && exec `command -v $cmd` $0 "$@"
  8. done
  9. echo "Python interpreter is not found in this system, please, install python or contact DEVTOOLSSUPPORT" >2
  10. exit 2
  11. ":"""
  12. # Previous line is bilingual: it ends a comment in Python, but do nothing in shell
  13. # Shell commands end here
  14. # Python script follows
  15. import os
  16. import sys
  17. import platform
  18. import json
  19. URLS = ['https://proxy.sandbox.yandex-team.ru/4135847037', 'https://storage.yandex-team.ru/get-devtools/1880306/e919b9bbf280e2b72c4418f089c2d6d2/by_platform.json']
  20. MD5 = 'e919b9bbf280e2b72c4418f089c2d6d2'
  21. URLS3 = ['https://proxy.sandbox.yandex-team.ru/4135876990', 'https://storage.yandex-team.ru/get-devtools/1931696/a4ac6942c49c796c1676dc80fd6fc984/by_platform.json']
  22. MD53 = 'a4ac6942c49c796c1676dc80fd6fc984'
  23. DEFAULT_PY_VER = 2
  24. RETRIES = 5
  25. HASH_PREFIX = 10
  26. PY3_HANDLERS = [
  27. "ya3bin0", "ya3bin3", # handers for tests
  28. "krevedko",
  29. "curl", "nvim", "gdb", "emacs", "grep", "jstyle", "nile", "sed", "vim",
  30. ]
  31. PY2_HANDLERS = ["ya2bin0", "ya2bin2"]
  32. EXPERIMENTAL_PY3_HANDLERS = []
  33. def create_dirs(path):
  34. try:
  35. os.makedirs(path)
  36. except OSError as e:
  37. import errno
  38. if e.errno != errno.EEXIST:
  39. raise
  40. return path
  41. def home_dir():
  42. # Do not trust $HOME, as it is unreliable in certain environments
  43. # Temporarily delete os.environ["HOME"] to force reading current home directory from /etc/passwd
  44. home_from_env = os.environ.pop("HOME", None)
  45. try:
  46. home_from_passwd = os.path.expanduser("~")
  47. if os.path.isabs(home_from_passwd):
  48. # This home dir is valid, prefer it over $HOME
  49. return home_from_passwd
  50. else:
  51. # When python is built with musl (this is quire weird though),
  52. # only users from /etc/passwd will be properly resolved,
  53. # as musl does not have nss module for LDAP integration.
  54. return home_from_env
  55. finally:
  56. if home_from_env is not None:
  57. os.environ["HOME"] = home_from_env
  58. def misc_root():
  59. return create_dirs(os.getenv('YA_CACHE_DIR') or os.path.join(home_dir(), '.ya'))
  60. def tool_root():
  61. return create_dirs(os.getenv('YA_CACHE_DIR_TOOLS') or os.path.join(misc_root(), 'tools'))
  62. def ya_token():
  63. def get_token_from_file():
  64. try:
  65. with open(os.environ.get('YA_TOKEN_PATH', os.path.join(home_dir(), '.ya_token')), 'r') as f:
  66. return f.read().strip()
  67. except:
  68. pass
  69. return os.getenv('YA_TOKEN') or get_token_from_file()
  70. TOOLS_DIR = tool_root()
  71. def uniq(size=6):
  72. import string
  73. import random
  74. return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size))
  75. _ssl_is_tuned = False
  76. def _tune_ssl():
  77. global _ssl_is_tuned
  78. if _ssl_is_tuned:
  79. return
  80. try:
  81. import ssl
  82. ssl._create_default_https_context = ssl._create_unverified_context
  83. except AttributeError:
  84. pass
  85. try:
  86. import urllib3
  87. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  88. except (AttributeError, ImportError):
  89. pass
  90. _ssl_is_tuned = True
  91. def _fetch(url, into):
  92. import hashlib
  93. _tune_ssl()
  94. try:
  95. from urllib2 import urlopen
  96. from urllib2 import Request
  97. from urlparse import urlparse
  98. except ImportError:
  99. from urllib.request import urlopen
  100. from urllib.request import Request
  101. from urllib.parse import urlparse
  102. request = Request(str(url))
  103. request.add_header('User-Agent', 'ya-bootstrap')
  104. if urlparse(url).netloc == 'proxy.sandbox.yandex-team.ru':
  105. token = ya_token()
  106. if token:
  107. request.add_header('Authorization', 'OAuth {}'.format(token))
  108. md5 = hashlib.md5()
  109. sys.stderr.write('Downloading %s ' % url)
  110. sys.stderr.flush()
  111. conn = urlopen(request, timeout=10)
  112. sys.stderr.write('[')
  113. sys.stderr.flush()
  114. try:
  115. with open(into, 'wb') as f:
  116. while True:
  117. block = conn.read(1024 * 1024)
  118. sys.stderr.write('.')
  119. sys.stderr.flush()
  120. if block:
  121. md5.update(block)
  122. f.write(block)
  123. else:
  124. break
  125. return md5.hexdigest()
  126. finally:
  127. sys.stderr.write('] ')
  128. sys.stderr.flush()
  129. def _atomic_fetch(url, into, md5):
  130. tmp_dest = into + '.' + uniq()
  131. try:
  132. real_md5 = _fetch(url, tmp_dest)
  133. if real_md5 != md5:
  134. raise Exception('MD5 mismatched: %s differs from %s' % (real_md5, md5))
  135. os.rename(tmp_dest, into)
  136. sys.stderr.write('OK\n')
  137. except Exception as e:
  138. sys.stderr.write('ERROR: ' + str(e) + '\n')
  139. raise
  140. finally:
  141. try:
  142. os.remove(tmp_dest)
  143. except OSError:
  144. pass
  145. def _extract(path, into):
  146. import tarfile
  147. tar = tarfile.open(path, errorlevel=2)
  148. # tar.extractall() will try to set file ownership according to the attributes stored in the archive
  149. # by calling TarFile.chown() method.
  150. # As this information is hardly relevant to the point of deployment / extraction,
  151. # it will just fail (python2) if ya is executed with root euid, or silently set non-existent numeric owner (python3)
  152. # to the files being extracted.
  153. # mock it with noop to retain current user ownership.
  154. tar.chown = lambda *args, **kwargs: None
  155. tar.extractall(path=into)
  156. tar.close()
  157. def _get(urls, md5):
  158. dest_path = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX])
  159. if not os.path.exists(dest_path):
  160. for iter in range(RETRIES):
  161. try:
  162. _atomic_fetch(urls[iter % len(urls)], dest_path, md5)
  163. break
  164. except Exception:
  165. if iter + 1 == RETRIES:
  166. raise
  167. else:
  168. import time
  169. time.sleep(iter)
  170. return dest_path
  171. def _get_dir(urls, md5, ya_name):
  172. dest_dir = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX] + '_d')
  173. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  174. return dest_dir
  175. try:
  176. packed_path = _get(urls, md5)
  177. except Exception:
  178. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  179. return dest_dir
  180. raise
  181. tmp_dir = dest_dir + '.' + uniq()
  182. try:
  183. try:
  184. _extract(packed_path, tmp_dir)
  185. except Exception:
  186. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  187. return dest_dir
  188. raise
  189. try:
  190. os.rename(tmp_dir, dest_dir)
  191. except OSError as e:
  192. import errno
  193. if e.errno != errno.ENOTEMPTY:
  194. raise
  195. return dest_dir
  196. finally:
  197. import shutil
  198. shutil.rmtree(tmp_dir, ignore_errors=True)
  199. try:
  200. os.remove(packed_path)
  201. except Exception:
  202. pass
  203. def _mine_arc_root():
  204. return os.path.dirname(os.path.realpath(__file__))
  205. def _parse_arguments():
  206. use_python = None
  207. use_python_set_force = False
  208. print_sandbox_id = False
  209. result_args = list(sys.argv[1:])
  210. handler = None
  211. if len(sys.argv) > 1:
  212. for index, arg in enumerate(sys.argv[1:]):
  213. if arg == "-3" or arg == "-2":
  214. if arg == "-3":
  215. new_value = 3
  216. elif arg == "-2":
  217. new_value = 2
  218. else:
  219. raise NotImplementedError("Unknown argument: {}".format(arg))
  220. if use_python is not None and use_python != new_value:
  221. sys.stderr.write("You can use only python2 (-2) OR python3 (-3) -based ya-bin, not both\n")
  222. exit(2)
  223. use_python = new_value
  224. use_python_set_force = True
  225. elif arg.startswith("--print-sandbox-id="):
  226. if print_sandbox_id:
  227. sys.stderr.write("You can print only one sandbox id at a time")
  228. exit(2)
  229. print_sandbox_id = arg.split('=')[1]
  230. else:
  231. # Do not try to parse remaining part of command
  232. result_args = result_args[index:]
  233. break
  234. # All ya script specific arguments found, search for handler
  235. skippable_flags = ('--error-file',)
  236. skip_next = False
  237. for arg in result_args:
  238. if not arg.startswith("-") and not skip_next:
  239. handler = arg
  240. break
  241. skip_next = arg in skippable_flags
  242. ENV_TRUE = ('yes', '1')
  243. py3_handlers_disabled = os.environ.get('YA_DISABLE_PY3_HANDLERS') in ENV_TRUE
  244. if py3_handlers_disabled:
  245. use_python = 2
  246. use_python_set_force = True # Prevent ya-bin respawn
  247. elif use_python == 3:
  248. if not print_sandbox_id:
  249. sys.stderr.write("!! python3-based ya-bin will be used, "
  250. "be prepared for some strange effects, "
  251. "don't be ashamed to write in DEVTOOLSSUPPORT about it\n")
  252. pass
  253. elif use_python == 2:
  254. pass
  255. elif handler in PY2_HANDLERS:
  256. use_python = 2
  257. elif handler in PY3_HANDLERS:
  258. use_python = 3
  259. else:
  260. use_python = 23 # ya-bin/3 makes a decision
  261. if not py3_handlers_disabled and use_python != 3:
  262. ya_experimental = os.environ.get("YA_EXPERIMENTAL") in ENV_TRUE
  263. if ya_experimental and handler in EXPERIMENTAL_PY3_HANDLERS:
  264. sys.stderr.write("!! python3-based ya-bin will be used because of:\n"
  265. " * You enable `YA_EXPERIMENTAL` environment variable\n"
  266. " * Handler `{}` in the list of experimental python3-compatible handlers"
  267. "\n".format(handler))
  268. use_python = 3
  269. if use_python == 2:
  270. urls, md5 = URLS, MD5
  271. elif use_python == 3:
  272. urls, md5 = URLS3, MD53
  273. elif use_python == 23:
  274. if DEFAULT_PY_VER == 2:
  275. urls, md5 = URLS, MD5
  276. elif DEFAULT_PY_VER == 3:
  277. urls, md5 = URLS3, MD53
  278. else:
  279. raise NotImplementedError("Unknown default python version: {}".format(DEFAULT_PY_VER))
  280. else:
  281. raise NotImplementedError("Unknown python version: {}".format(use_python))
  282. return md5, print_sandbox_id, result_args, urls, use_python, use_python_set_force
  283. def main():
  284. if not os.path.exists(TOOLS_DIR):
  285. os.makedirs(TOOLS_DIR)
  286. md5, print_sandbox_id, result_args, urls, use_python, use_python_set_force = _parse_arguments()
  287. with open(_get(urls, md5), 'r') as fp:
  288. meta = json.load(fp)['data']
  289. my_platform = platform.system().lower()
  290. my_machine = platform.machine().lower()
  291. if my_platform == 'linux':
  292. if 'ppc64le' in platform.platform():
  293. my_platform = 'linux-ppc64le'
  294. elif 'aarch64' in platform.platform():
  295. my_platform = 'linux-aarch64'
  296. else:
  297. my_platform = 'linux_musl'
  298. if my_platform == 'darwin' and my_machine == 'arm64':
  299. my_platform = 'darwin-arm64'
  300. def _platform_key(target_platform):
  301. """ match by max prefix length, prefer shortest """
  302. def _key_for_platform(platform):
  303. return len(os.path.commonprefix([target_platform, platform])), -len(platform)
  304. return _key_for_platform
  305. best_key = max(meta.keys(), key=_platform_key(my_platform))
  306. value = meta[best_key]
  307. if print_sandbox_id:
  308. target = print_sandbox_id
  309. best_target = max(meta.keys(), key=_platform_key(target))
  310. sys.stdout.write(str(meta[best_target]['resource_id']) + '\n')
  311. exit(0)
  312. ya_name = {'win32': 'ya-bin.exe', 'win32-clang-cl': 'ya-bin.exe'}.get(best_key, 'ya-bin') # XXX
  313. ya_dir = _get_dir(value['urls'], value['md5'], ya_name)
  314. # Popen `args` must have `str` type
  315. ya_path = str(os.path.join(ya_dir, ya_name))
  316. env = os.environ.copy()
  317. if 'YA_SOURCE_ROOT' not in env:
  318. src_root = _mine_arc_root()
  319. if src_root is not None:
  320. env['YA_SOURCE_ROOT'] = src_root
  321. # For more info see YT-14105
  322. for env_name in [
  323. 'LD_PRELOAD',
  324. 'Y_PYTHON_SOURCE_ROOT',
  325. ]:
  326. if env_name in os.environ:
  327. sys.stderr.write("Warn: {}='{}' is specified and may affect the correct operation of the ya\n".format(env_name, env[env_name]))
  328. env['YA_PYVER_REQUIRE'] = str(use_python)
  329. if use_python_set_force:
  330. env['YA_PYVER_SET_FORCED'] = 'yes'
  331. if os.name == 'nt':
  332. import subprocess
  333. p = subprocess.Popen([ya_path] + result_args, env=env)
  334. p.wait()
  335. sys.exit(p.returncode)
  336. else:
  337. os.execve(ya_path, [ya_path] + result_args, env)
  338. if __name__ == '__main__':
  339. try:
  340. main()
  341. except Exception as e:
  342. sys.stderr.write('ERROR: ' + str(e) + '\n')
  343. from traceback import format_exc
  344. sys.stderr.write(format_exc() + "\n")
  345. sys.exit(1)