ya 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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/4910542326', 'https://storage.yandex-team.ru/get-devtools/1942671/64e25bd1bfaf98ac60ca046793bd2100/by_platform.json']
  20. MD5 = '64e25bd1bfaf98ac60ca046793bd2100'
  21. URLS3 = ['https://proxy.sandbox.yandex-team.ru/4910548121', 'https://storage.yandex-team.ru/get-devtools/1809005/bb466a0bd1bc53f76e2db2ef0dbbac06/by_platform.json']
  22. MD53 = 'bb466a0bd1bc53f76e2db2ef0dbbac06'
  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. "py23_utils",
  31. 'ydb',
  32. 'upload', 'download', 'paste', 'whoami',
  33. }
  34. PY2_HANDLERS = {
  35. "ya2bin0", "ya2bin2",
  36. }
  37. EXPERIMENTAL_PY3_HANDLERS = set()
  38. DEVTOOLS_PY3_HANDLERS = set()
  39. def is_devtools():
  40. # type: () -> bool
  41. devtools_users = {'tldr', 'yetty', 'prettyboy', 'neksard', 'ival83', 'mikhnenko', 'aokhotin', 'somov', 'shadchin', 'albazh', 'grasscat', 'nogert', 'jolex007', 'aakuz', 'aripinen', 'sudilovskiy', 'tutelka', 'tutelka', 'vlasovskikh', 'vlasovskikh', 'and42', 'say', 'rudeshko', 'pg', 'artanis', 'hiddenpath', 'hiddenpath', 'khoden', 'bulatkhr', 'v-korovin', 'viknet', 'saxumcordis', 'vpozdyayev', 'vturov', 'vturov', 'vlad-savinov', 'slava', 'miripiruni', 'trushkin', 'griddic', 'ligreen', 'zaverden', 'kirpadmitriy', 'dmitko', 'dldmitry', 'lix0', 'yak-dmitriy', 'dankolesnikov', 'keepitsimple', 'workfork', 'vania-pooh', 'ilezhankin', 'igorart', 'thevery', 'ilia-vashurov', 'iaz1607', 'il2kondr4', 'ilyasiluyanov', 'trofimenkov', 'kirkharitonov', 'korum', 'tilacyn', 'maratik', 'miroslav2', 'spasitel', 'nslus', 'nsamokhin', 'r2d2', 'zhukoff-pavel', 'r-vetrov', 'gotocoding', 'svkov42', 'sabevzenko', 'belesev', 'svidyuk', 'snermolaev', 'spreis', 's-repalov', 'golovin-stan', 'ilikepugs', 'tekireeva', 'zumra6a', 'sareyu', 'thegeorg', 'snowball'}
  42. user = os.environ.get('USER')
  43. return bool(user and user in devtools_users)
  44. def create_dirs(path):
  45. try:
  46. os.makedirs(path)
  47. except OSError as e:
  48. import errno
  49. if e.errno != errno.EEXIST:
  50. raise
  51. return path
  52. def home_dir():
  53. # Do not trust $HOME, as it is unreliable in certain environments
  54. # Temporarily delete os.environ["HOME"] to force reading current home directory from /etc/passwd
  55. home_from_env = os.environ.pop("HOME", None)
  56. try:
  57. home_from_passwd = os.path.expanduser("~")
  58. if os.path.isabs(home_from_passwd):
  59. # This home dir is valid, prefer it over $HOME
  60. return home_from_passwd
  61. else:
  62. # When python is built with musl (this is quire weird though),
  63. # only users from /etc/passwd will be properly resolved,
  64. # as musl does not have nss module for LDAP integration.
  65. return home_from_env
  66. finally:
  67. if home_from_env is not None:
  68. os.environ["HOME"] = home_from_env
  69. def misc_root():
  70. return create_dirs(os.getenv('YA_CACHE_DIR') or os.path.join(home_dir(), '.ya'))
  71. def tool_root():
  72. return create_dirs(os.getenv('YA_CACHE_DIR_TOOLS') or os.path.join(misc_root(), 'tools'))
  73. def ya_token():
  74. def get_token_from_file():
  75. try:
  76. with open(os.environ.get('YA_TOKEN_PATH', os.path.join(home_dir(), '.ya_token')), 'r') as f:
  77. return f.read().strip()
  78. except:
  79. pass
  80. return os.getenv('YA_TOKEN') or get_token_from_file()
  81. TOOLS_DIR = tool_root()
  82. def uniq(size=6):
  83. import string
  84. import random
  85. return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size))
  86. _ssl_is_tuned = False
  87. def _tune_ssl():
  88. global _ssl_is_tuned
  89. if _ssl_is_tuned:
  90. return
  91. try:
  92. import ssl
  93. ssl._create_default_https_context = ssl._create_unverified_context
  94. except AttributeError:
  95. pass
  96. try:
  97. import urllib3
  98. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  99. except (AttributeError, ImportError):
  100. pass
  101. _ssl_is_tuned = True
  102. def _fetch(url, into):
  103. import hashlib
  104. _tune_ssl()
  105. try:
  106. from urllib2 import urlopen
  107. from urllib2 import Request
  108. from urlparse import urlparse
  109. except ImportError:
  110. from urllib.request import urlopen
  111. from urllib.request import Request
  112. from urllib.parse import urlparse
  113. request = Request(str(url))
  114. request.add_header('User-Agent', 'ya-bootstrap')
  115. if urlparse(url).netloc == 'proxy.sandbox.yandex-team.ru':
  116. token = ya_token()
  117. if token:
  118. request.add_header('Authorization', 'OAuth {}'.format(token))
  119. md5 = hashlib.md5()
  120. sys.stderr.write('Downloading %s ' % url)
  121. sys.stderr.flush()
  122. conn = urlopen(request, timeout=10)
  123. sys.stderr.write('[')
  124. sys.stderr.flush()
  125. try:
  126. with open(into, 'wb') as f:
  127. while True:
  128. block = conn.read(1024 * 1024)
  129. sys.stderr.write('.')
  130. sys.stderr.flush()
  131. if block:
  132. md5.update(block)
  133. f.write(block)
  134. else:
  135. break
  136. return md5.hexdigest()
  137. finally:
  138. sys.stderr.write('] ')
  139. sys.stderr.flush()
  140. def _atomic_fetch(url, into, md5):
  141. tmp_dest = into + '.' + uniq()
  142. try:
  143. real_md5 = _fetch(url, tmp_dest)
  144. if real_md5 != md5:
  145. raise Exception('MD5 mismatched: %s differs from %s' % (real_md5, md5))
  146. os.rename(tmp_dest, into)
  147. sys.stderr.write('OK\n')
  148. except Exception as e:
  149. sys.stderr.write('ERROR: ' + str(e) + '\n')
  150. raise
  151. finally:
  152. try:
  153. os.remove(tmp_dest)
  154. except OSError:
  155. pass
  156. def _extract(path, into):
  157. import tarfile
  158. tar = tarfile.open(path, errorlevel=2)
  159. # tar.extractall() will try to set file ownership according to the attributes stored in the archive
  160. # by calling TarFile.chown() method.
  161. # As this information is hardly relevant to the point of deployment / extraction,
  162. # it will just fail (python2) if ya is executed with root euid, or silently set non-existent numeric owner (python3)
  163. # to the files being extracted.
  164. # mock it with noop to retain current user ownership.
  165. tar.chown = lambda *args, **kwargs: None
  166. tar.extractall(path=into)
  167. tar.close()
  168. def _get(urls, md5):
  169. dest_path = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX])
  170. if not os.path.exists(dest_path):
  171. for iter in range(RETRIES):
  172. try:
  173. _atomic_fetch(urls[iter % len(urls)], dest_path, md5)
  174. break
  175. except Exception:
  176. if iter + 1 == RETRIES:
  177. raise
  178. else:
  179. import time
  180. time.sleep(iter)
  181. return dest_path
  182. def _get_dir(urls, md5, ya_name):
  183. dest_dir = os.path.join(TOOLS_DIR, md5[:HASH_PREFIX] + '_d')
  184. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  185. return dest_dir
  186. try:
  187. packed_path = _get(urls, md5)
  188. except Exception:
  189. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  190. return dest_dir
  191. raise
  192. tmp_dir = dest_dir + '.' + uniq()
  193. try:
  194. try:
  195. _extract(packed_path, tmp_dir)
  196. except Exception:
  197. if os.path.isfile(os.path.join(dest_dir, ya_name)):
  198. return dest_dir
  199. raise
  200. try:
  201. os.rename(tmp_dir, dest_dir)
  202. except OSError as e:
  203. import errno
  204. if e.errno != errno.ENOTEMPTY:
  205. raise
  206. return dest_dir
  207. finally:
  208. import shutil
  209. shutil.rmtree(tmp_dir, ignore_errors=True)
  210. try:
  211. os.remove(packed_path)
  212. except Exception:
  213. pass
  214. def _mine_arc_root():
  215. return os.path.dirname(os.path.realpath(__file__))
  216. def _parse_arguments():
  217. use_python = None
  218. use_python_set_force = False
  219. print_sandbox_id = False
  220. result_args = list(sys.argv[1:])
  221. handler = None
  222. if len(sys.argv) > 1:
  223. for index, arg in enumerate(sys.argv[1:]):
  224. if arg == "-3" or arg == "-2":
  225. if arg == "-3":
  226. new_value = 3
  227. elif arg == "-2":
  228. new_value = 2
  229. else:
  230. raise NotImplementedError("Unknown argument: {}".format(arg))
  231. if use_python is not None and use_python != new_value:
  232. sys.stderr.write("You can use only python2 (-2) OR python3 (-3) -based ya-bin, not both\n")
  233. exit(2)
  234. use_python = new_value
  235. use_python_set_force = True
  236. elif arg.startswith("--print-sandbox-id="):
  237. if print_sandbox_id:
  238. sys.stderr.write("You can print only one sandbox id at a time")
  239. exit(2)
  240. print_sandbox_id = arg.split('=')[1]
  241. else:
  242. # Do not try to parse remaining part of command
  243. result_args = result_args[index:]
  244. break
  245. # All ya script specific arguments found, search for handler
  246. skippable_flags = ('--error-file',)
  247. skip_next = False
  248. for arg in result_args:
  249. if not arg.startswith("-") and not skip_next:
  250. handler = arg
  251. break
  252. skip_next = arg in skippable_flags
  253. ENV_TRUE = ('yes', '1')
  254. py3_handlers_disabled = os.environ.get('YA_DISABLE_PY3_HANDLERS') in ENV_TRUE
  255. if py3_handlers_disabled:
  256. use_python = 2
  257. use_python_set_force = True # Prevent ya-bin respawn
  258. elif use_python == 3:
  259. if not print_sandbox_id:
  260. # will be shown only if user set `-3` by force
  261. sys.stderr.write("!! python3-based ya-bin will be used, "
  262. "be prepared for some strange effects, "
  263. "don't be ashamed to write in DEVTOOLSSUPPORT about it\n")
  264. pass
  265. elif use_python == 2:
  266. pass
  267. elif handler in PY2_HANDLERS:
  268. use_python = 2
  269. elif handler in PY3_HANDLERS:
  270. use_python = 3
  271. else:
  272. use_python = 23 # ya-bin/3 makes a decision
  273. if not use_python_set_force and not py3_handlers_disabled and use_python != 3:
  274. # User didn't set python version by force, didn't disable it, handler is under python2, so lets check experiments
  275. ya_experimental = os.environ.get("YA_EXPERIMENTAL") in ENV_TRUE
  276. if ya_experimental and handler in EXPERIMENTAL_PY3_HANDLERS:
  277. sys.stderr.write("!! python3-based ya-bin will be used because of:\n"
  278. " * You enable `YA_EXPERIMENTAL` environment variable\n"
  279. " * Handler `{}` in the list of experimental python3-compatible handlers\n"
  280. "".format(handler))
  281. use_python = 3
  282. elif is_devtools() and handler in DEVTOOLS_PY3_HANDLERS:
  283. sys.stderr.write("!! python3-based ya-bin will be used because of:\n"
  284. " * You are member of DEVTOOLS (it's just list of logins in `ya` script)\n"
  285. " * Handler `{}` in the list of experimental python3-compatible handlers for DEVTOOLS members\n"
  286. "".format(handler) )
  287. use_python = 3
  288. if use_python == 2:
  289. urls, md5 = URLS, MD5
  290. elif use_python == 3:
  291. urls, md5 = URLS3, MD53
  292. elif use_python == 23:
  293. if DEFAULT_PY_VER == 2:
  294. urls, md5 = URLS, MD5
  295. elif DEFAULT_PY_VER == 3:
  296. urls, md5 = URLS3, MD53
  297. else:
  298. raise NotImplementedError("Unknown default python version: {}".format(DEFAULT_PY_VER))
  299. else:
  300. raise NotImplementedError("Unknown python version: {}".format(use_python))
  301. return md5, print_sandbox_id, result_args, urls, use_python, use_python_set_force
  302. def main():
  303. if not os.path.exists(TOOLS_DIR):
  304. os.makedirs(TOOLS_DIR)
  305. md5, print_sandbox_id, result_args, urls, use_python, use_python_set_force = _parse_arguments()
  306. with open(_get(urls, md5), 'r') as fp:
  307. meta = json.load(fp)['data']
  308. my_platform = platform.system().lower()
  309. my_machine = platform.machine().lower()
  310. if my_platform == 'linux':
  311. if 'ppc64le' in platform.platform():
  312. my_platform = 'linux-ppc64le'
  313. elif 'aarch64' in platform.platform():
  314. my_platform = 'linux-aarch64'
  315. else:
  316. my_platform = 'linux_musl'
  317. if my_platform == 'darwin' and my_machine == 'arm64':
  318. my_platform = 'darwin-arm64'
  319. def _platform_key(target_platform):
  320. """ match by max prefix length, prefer shortest """
  321. def _key_for_platform(platform):
  322. return len(os.path.commonprefix([target_platform, platform])), -len(platform)
  323. return _key_for_platform
  324. best_key = max(meta.keys(), key=_platform_key(my_platform))
  325. value = meta[best_key]
  326. if print_sandbox_id:
  327. target = print_sandbox_id
  328. best_target = max(meta.keys(), key=_platform_key(target))
  329. sys.stdout.write(str(meta[best_target]['resource_id']) + '\n')
  330. exit(0)
  331. ya_name = {'win32': 'ya-bin.exe', 'win32-clang-cl': 'ya-bin.exe'}.get(best_key, 'ya-bin') # XXX
  332. ya_dir = _get_dir(value['urls'], value['md5'], ya_name)
  333. # Popen `args` must have `str` type
  334. ya_path = str(os.path.join(ya_dir, ya_name))
  335. env = os.environ.copy()
  336. if 'YA_SOURCE_ROOT' not in env:
  337. src_root = _mine_arc_root()
  338. if src_root is not None:
  339. env['YA_SOURCE_ROOT'] = src_root
  340. # For more info see YT-14105
  341. for env_name in [
  342. 'LD_PRELOAD',
  343. 'Y_PYTHON_SOURCE_ROOT',
  344. ]:
  345. if env_name in os.environ:
  346. sys.stderr.write("Warn: {}='{}' is specified and may affect the correct operation of the ya\n".format(env_name, env[env_name]))
  347. env['YA_PYVER_REQUIRE'] = str(use_python)
  348. if use_python_set_force:
  349. env['YA_PYVER_SET_FORCED'] = 'yes'
  350. if os.name == 'nt':
  351. import subprocess
  352. p = subprocess.Popen([ya_path] + result_args, env=env)
  353. p.wait()
  354. sys.exit(p.returncode)
  355. else:
  356. os.execve(ya_path, [ya_path] + result_args, env)
  357. if __name__ == '__main__':
  358. try:
  359. main()
  360. except Exception as e:
  361. sys.stderr.write('ERROR: ' + str(e) + '\n')
  362. from traceback import format_exc
  363. sys.stderr.write(format_exc() + "\n")
  364. sys.exit(1)