|
| 1 | +import sys |
| 2 | +import time |
| 3 | +import platform |
| 4 | +from urllib import request |
| 5 | + |
| 6 | + |
| 7 | +PING_TIMEOUT = 3 |
| 8 | + |
| 9 | + |
| 10 | +def _get_download_urls(version): |
| 11 | + s3_url_template = 'https://github.com/LeetCode-OpenSource/py-sourcemap/releases/download/{tag}/py_sourcemap.{py_ver}-{platform}.{ext}' |
| 12 | + aliyun_url_template = 'https://static.leetcode-cn.com/packages/py_sourcemap/{package_ver}/py_sourcemap.{py_ver}-{platform}.{ext}' |
| 13 | + |
| 14 | + version_tag = 'v{}'.format(version) |
| 15 | + (major, minor, _) = platform.python_version_tuple() |
| 16 | + if major != '3' or not(minor in ['5', '6', '7']): |
| 17 | + raise Exception('Only python 3.5, 3.6, 3.7 are supported') |
| 18 | + system = platform.system() |
| 19 | + if system == 'Linux': |
| 20 | + py_version = 'cpython-{}{}m'.format(major, minor) |
| 21 | + usr_platform = 'x86_64-linux-gnu' |
| 22 | + ext = 'so' |
| 23 | + elif system == 'Darwin': |
| 24 | + py_version = 'cpython-{}{}m'.format(major, minor) |
| 25 | + usr_platform = 'x86_64-apple-darwin' |
| 26 | + ext = 'so' |
| 27 | + elif system == 'Windows': |
| 28 | + py_version = 'cp{}{}'.format(major, minor) |
| 29 | + # from https://docs.python.org/3/library/platform.html |
| 30 | + is_64bits = sys.maxsize > 2**32 |
| 31 | + usr_platform = 'win_amd64' if is_64bits else 'win32' |
| 32 | + ext = 'pyd' |
| 33 | + else: |
| 34 | + raise Exception('Your system is unrecognized: {}'.format(system)) |
| 35 | + |
| 36 | + return { |
| 37 | + 's3': s3_url_template.format(tag=version_tag, |
| 38 | + py_ver=py_version, |
| 39 | + platform=usr_platform, |
| 40 | + ext=ext), |
| 41 | + 'aliyun': aliyun_url_template.format(package_ver=version, |
| 42 | + py_ver=py_version, |
| 43 | + platform=usr_platform, |
| 44 | + ext=ext) |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +def _get_latency(url): |
| 49 | + req = request.Request(url, method="HEAD") |
| 50 | + try: |
| 51 | + start = time.perf_counter() |
| 52 | + request.urlopen(req, timeout=PING_TIMEOUT) |
| 53 | + end = time.perf_counter() |
| 54 | + return end - start |
| 55 | + except Exception: |
| 56 | + return 999 |
| 57 | + |
| 58 | + |
| 59 | +def get_remote_binary(version): |
| 60 | + urls = _get_download_urls(version) |
| 61 | + print('Try ping servers...') |
| 62 | + s3_time = _get_latency(urls['s3']) |
| 63 | + aliyun_time = _get_latency(urls['aliyun']) |
| 64 | + print('s3: {:.3f}s, aliyun: {:.3f}s'.format(s3_time, aliyun_time)) |
| 65 | + url = urls['s3'] if s3_time <= aliyun_time else urls['aliyun'] |
| 66 | + print('Start downloading {}...'.format(url)) |
| 67 | + binary_fp = request.urlopen(url) |
| 68 | + print('Downloaded {}'.format(url)) |
| 69 | + return binary_fp |
0 commit comments