1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (c) 2022 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os
17import sys
18import argparse
19import subprocess
20import ssl
21import shutil
22import importlib
23import time
24import pathlib
25import re
26from multiprocessing import cpu_count
27from concurrent.futures import ThreadPoolExecutor, as_completed
28from functools import partial
29from urllib.request import urlopen
30import urllib.error
31from scripts.util.file_utils import read_json_file
32
33
34def _run_cmd(cmd: str):
35    res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
36                           stderr=subprocess.PIPE)
37    sout, serr = res.communicate()
38    return sout.rstrip().decode('utf-8'), serr, res.returncode
39
40
41def _check_sha256(check_url: str, local_file: str) -> bool:
42    check_sha256_cmd = 'curl -s -k ' + check_url + '.sha256'
43    local_sha256_cmd = 'sha256sum ' + local_file + "|cut -d ' ' -f1"
44    check_sha256, err, returncode = _run_cmd(check_sha256_cmd)
45    local_sha256, err, returncode = _run_cmd(local_sha256_cmd)
46    if check_sha256 != local_sha256:
47        print('remote file {}.sha256 is not found, begin check SHASUMS256.txt'.format(check_url))
48        check_sha256 = _obtain_sha256_by_sha_sums256(check_url)
49    return check_sha256 == local_sha256
50
51
52def _check_sha256_by_mark(args, check_url: str, code_dir: str, unzip_dir: str, unzip_filename: str) -> bool:
53    check_sha256_cmd = 'curl -s -k ' + check_url + '.sha256'
54    check_sha256, err, returncode = _run_cmd(check_sha256_cmd)
55    mark_file_dir = os.path.join(code_dir, unzip_dir)
56    mark_file_name = check_sha256 + '.' + unzip_filename + '.mark'
57    mark_file_path = os.path.join(mark_file_dir, mark_file_name)
58    args.mark_file_path = mark_file_path
59    return os.path.exists(mark_file_path)
60
61
62def _obtain_sha256_by_sha_sums256(check_url: str) -> str:
63    sha_sums256 = 'SHASUMS256.txt'
64    sha_sums256_path = os.path.join(os.path.dirname(check_url), sha_sums256)
65    file_name = os.path.basename(check_url)
66    cmd = 'curl -s -k ' + sha_sums256_path
67    data_sha_sums256, err, returncode = _run_cmd(cmd)
68    check_sha256 = None
69    for line in data_sha_sums256.split('\n'):
70        if file_name in line:
71            check_sha256 = line.split(' ')[0]
72    return check_sha256
73
74
75def _config_parse(config: dict, tool_repo: str, glibc_version: str) -> dict:
76    parse_dict = dict()
77    parse_dict['unzip_dir'] = config.get('unzip_dir')
78    file_path = config.get('file_path')
79    if 'python' in file_path and glibc_version is not None:
80        file_path = re.sub(r'GLIBC[0-9]\.[0-9]{2}', glibc_version, file_path)
81    parse_dict['huaweicloud_url'] = tool_repo + file_path
82    parse_dict['unzip_filename'] = config.get('unzip_filename')
83    md5_huaweicloud_url_cmd = 'echo ' + parse_dict.get('huaweicloud_url') + "|md5sum|cut -d ' ' -f1"
84    parse_dict['md5_huaweicloud_url'], err, returncode = _run_cmd(md5_huaweicloud_url_cmd)
85    parse_dict['bin_file'] = os.path.basename(parse_dict.get('huaweicloud_url'))
86    return parse_dict
87
88
89def _uncompress(args, src_file: str, code_dir: str, unzip_dir: str, unzip_filename: str, mark_file_path: str):
90    dest_dir = os.path.join(code_dir, unzip_dir)
91    if src_file[-3:] == 'zip':
92        cmd = 'unzip -o {} -d {};echo 0 > {}'.format(src_file, dest_dir, mark_file_path)
93    elif src_file[-6:] == 'tar.gz':
94        cmd = 'tar -xvzf {} -C {};echo 0 > {}'.format(src_file, dest_dir, mark_file_path)
95    else:
96        cmd = 'tar -xvf {} -C {};echo 0 > {}'.format(src_file, dest_dir, mark_file_path)
97    _run_cmd(cmd)
98
99
100def _copy_url(args, task_id: int, url: str, local_file: str, code_dir: str, unzip_dir: str,
101              unzip_filename: str, mark_file_path: str, progress):
102    retry_times = 0
103    max_retry_times = 3
104    while retry_times < max_retry_times:
105        # download files
106        download_buffer_size = 32768
107        progress.console.log('Requesting {}'.format(url))
108        try:
109            response = urlopen(url)
110        except urllib.error.HTTPError as e:
111            progress.console.log("Failed to open {}, HTTPError: {}".format(url, e.code), style='red')
112        progress.update(task_id, total=int(response.info()["Content-length"]))
113        with open(local_file, "wb") as dest_file:
114            progress.start_task(task_id)
115            for data in iter(partial(response.read, download_buffer_size), b""):
116                dest_file.write(data)
117                progress.update(task_id, advance=len(data))
118        progress.console.log("Downloaded {}".format(local_file))
119
120        if os.path.exists(local_file):
121            if _check_sha256(url, local_file):
122                # decompressing files
123                progress.console.log("Decompressing {}".format(local_file))
124                _uncompress(args, local_file, code_dir, unzip_dir, unzip_filename, mark_file_path)
125                progress.console.log("Decompressed {}".format(local_file))
126                break
127            else:
128                os.remove(local_file)
129        retry_times += 1
130    if retry_times == max_retry_times:
131        print('{}, download failed with three times retry, please check network status. Prebuilts download exit.'.format(local_file))
132        # todo, merge with copy_url_disable_rich
133        sys.exit(1)
134
135
136def _copy_url_disable_rich(args, url: str, local_file: str, code_dir: str, unzip_dir: str,
137                           unzip_filename: str, mark_file_path: str):
138    # download files
139    download_buffer_size = 32768
140    print('Requesting {}, please wait'.format(url))
141    try:
142        response = urlopen(url)
143    except urllib.error.HTTPError as e:
144        print("Failed to open {}, HTTPError: {}".format(url, e.code))
145    with open(local_file, "wb") as dest_file:
146        for data in iter(partial(response.read, download_buffer_size), b""):
147            dest_file.write(data)
148    print("Downloaded {}".format(local_file))
149
150    # decompressing files
151    print("Decompressing {}, please wait".format(local_file))
152    _uncompress(args, local_file, code_dir, unzip_dir, unzip_filename, mark_file_path)
153    print("Decompressed {}".format(local_file))
154
155
156def _is_system_component() -> bool:
157    root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
158    if pathlib.Path(os.path.join(root_dir, 'interface', 'sdk-js')).exists() or pathlib.Path(
159            os.path.join(root_dir, 'foundation', 'arkui')).exists() or pathlib.Path(
160            os.path.join(root_dir, 'arkcompiler')).exists():
161        return True
162    else:
163        return False
164
165
166def _hwcloud_download(args, config: dict, bin_dir: str, code_dir: str, glibc_version: str):
167    try:
168        cnt = cpu_count()
169    except Exception as e:
170        cnt = 1
171    with ThreadPoolExecutor(max_workers=cnt) as pool:
172        tasks = dict()
173        for config_info in config:
174            parse_dict = _config_parse(config_info, args.tool_repo, glibc_version)
175            unzip_dir = parse_dict.get('unzip_dir')
176            huaweicloud_url = parse_dict.get('huaweicloud_url')
177            unzip_filename = parse_dict.get('unzip_filename')
178            md5_huaweicloud_url = parse_dict.get('md5_huaweicloud_url')
179            bin_file = parse_dict.get('bin_file')
180            abs_unzip_dir = os.path.join(code_dir, unzip_dir)
181            if not os.path.exists(abs_unzip_dir):
182                os.makedirs(abs_unzip_dir, exist_ok=True)
183            if _check_sha256_by_mark(args, huaweicloud_url, code_dir, unzip_dir, unzip_filename):
184                if not args.disable_rich:
185                    args.progress.console.log('{}, Sha256 markword check OK.'.format(huaweicloud_url), style='green')
186                else:
187                    print('{}, Sha256 markword check OK.'.format(huaweicloud_url))
188            else:
189                _run_cmd(('rm -rf {}/{}/*.{}.mark').format(code_dir, unzip_dir, unzip_filename))
190                _run_cmd(('rm -rf {}/{}/{}').format(code_dir, unzip_dir, unzip_filename))
191                local_file = os.path.join(bin_dir, '{}.{}'.format(md5_huaweicloud_url, bin_file))
192                if os.path.exists(local_file):
193                    if _check_sha256(huaweicloud_url, local_file):
194                        if not args.disable_rich:
195                            args.progress.console.log('{}, Sha256 check download OK.'.format(local_file), style='green')
196                        else:
197                            print('{}, Sha256 check download OK. Start decompression, please wait'.format(local_file))
198                        task = pool.submit(_uncompress, args, local_file, code_dir,
199                                           unzip_dir, unzip_filename, args.mark_file_path)
200                        tasks[task] = os.path.basename(huaweicloud_url)
201                        continue
202                    else:
203                        os.remove(local_file)
204                filename = huaweicloud_url.split("/")[-1]
205                if not args.disable_rich:
206                    task_id = args.progress.add_task("download", filename=filename, start=False)
207                    task = pool.submit(_copy_url, args, task_id, huaweicloud_url, local_file, code_dir,
208                                    unzip_dir, unzip_filename, args.mark_file_path, args.progress)
209                    tasks[task] = os.path.basename(huaweicloud_url)
210                else:
211                    task = pool.submit(_copy_url_disable_rich, args, huaweicloud_url, local_file, code_dir,
212                                        unzip_dir, unzip_filename, args.mark_file_path)
213
214        for task in as_completed(tasks):
215            if not args.disable_rich:
216                args.progress.console.log('{}, download and decompress completed'.format(tasks.get(task)),
217                style='green')
218            else:
219                print('{}, download and decompress completed'.format(tasks.get(task)))
220
221
222def _npm_install(args):
223    node_path = 'prebuilts/build-tools/common/nodejs/current/bin'
224    os.environ['PATH'] = '{}/{}:{}'.format(args.code_dir, node_path, os.environ.get('PATH'))
225    npm = os.path.join(args.code_dir, node_path, 'npm')
226    if args.skip_ssl:
227        skip_ssl_cmd = '{} config set strict-ssl false;'.format(npm)
228        out, err, retcode = _run_cmd(skip_ssl_cmd)
229        if retcode != 0:
230            return False, err.decode()
231    npm_clean_cmd = '{} cache clean -f'.format(npm)
232    npm_package_lock_cmd = '{} config set package-lock true'.format(npm)
233    out, err, retcode = _run_cmd(npm_clean_cmd)
234    if retcode != 0:
235        return False, err.decode()
236    out, err, retcode = _run_cmd(npm_package_lock_cmd)
237    if retcode != 0:
238        return False, err.decode()
239    print('start npm install, please wait.')
240    for install_info in args.npm_install_config:
241        full_code_path = os.path.join(args.code_dir, install_info)
242        basename = os.path.basename(full_code_path)
243        node_modules_path = os.path.join(full_code_path, "node_modules")
244        npm_cache_dir = os.path.join('~/.npm/_cacache', basename)
245
246        if os.path.exists(node_modules_path):
247            print('remove node_modules %s' % node_modules_path)
248            _run_cmd(('rm -rf {}'.format(node_modules_path)))
249        if os.path.exists(full_code_path):
250            cmd = ['timeout', '-s', '9', '90s', npm, 'install', '--registry', args.npm_registry, '--cache', npm_cache_dir]
251            if args.host_platform == 'darwin':
252                cmd = [npm, 'install', '--registry', args.npm_registry, '--cache', npm_cache_dir]
253            if args.unsafe_perm:
254                cmd.append('--unsafe-perm')
255            proc = subprocess.Popen(cmd, cwd=full_code_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
256            # wait proc Popen with 0.1 second
257            time.sleep(0.1)
258            out, err = proc.communicate()
259            if proc.returncode:
260                print("in dir:{}, executing:{}".format(full_code_path, ' '.join(cmd)))
261                return False, err.decode()
262        else:
263            raise Exception("{} not exist, it shouldn't happen, pls check...".format(full_code_path))
264    return True, None
265
266
267def _node_modules_copy(config: dict, code_dir: str, enable_symlink: bool):
268    for config_info in config:
269        src_dir = os.path.join(code_dir, config_info.get('src'))
270        if not os.path.exists(src_dir):
271            print(f"{src_dir} not exist, skip node_modules copy.")
272            continue
273        dest_dir = os.path.join(code_dir, config_info.get('dest'))
274        use_symlink = config_info.get('use_symlink')
275        if os.path.exists(os.path.dirname(dest_dir)):
276            shutil.rmtree(os.path.dirname(dest_dir))
277        if use_symlink == 'True' and enable_symlink == True:
278            os.makedirs(os.path.dirname(dest_dir), exist_ok=True)
279            os.symlink(src_dir, dest_dir)
280        else:
281            shutil.copytree(src_dir, dest_dir, symlinks=True)
282
283
284def _file_handle(config: dict, code_dir: str, host_platform: str):
285    for config_info in config:
286        src_dir = code_dir + config_info.get('src')
287        dest_dir = code_dir + config_info.get('dest')
288        tmp_dir = config_info.get('tmp')
289        symlink_src = config_info.get('symlink_src')
290        symlink_dest = config_info.get('symlink_dest')
291        rename = config_info.get('rename')
292        if os.path.exists(src_dir):
293            if tmp_dir:
294                tmp_dir = code_dir + tmp_dir
295                shutil.move(src_dir, tmp_dir)
296                cmd = 'mv {}/*.mark {}'.format(dest_dir, tmp_dir)
297                _run_cmd(cmd)
298                if os.path.exists(dest_dir):
299                    shutil.rmtree(dest_dir)
300                shutil.move(tmp_dir, dest_dir)
301            elif rename:
302                if os.path.exists(dest_dir) and dest_dir != src_dir:
303                    shutil.rmtree(dest_dir)
304                shutil.move(src_dir, dest_dir)
305                if symlink_src and symlink_dest:
306                    if os.path.exists(dest_dir + symlink_dest):
307                        os.remove(dest_dir + symlink_dest)
308                    if host_platform == 'darwin' and os.path.basename(dest_dir) == "nodejs":
309                        symlink_src = symlink_src.replace('linux', 'darwin')
310                    os.symlink(os.path.basename(symlink_src), dest_dir + symlink_dest)
311            else:
312                _run_cmd('chmod 755 {} -R'.format(dest_dir))
313
314
315def _import_rich_module():
316    module = importlib.import_module('rich.progress')
317    progress = module.Progress(
318        module.TextColumn("[bold blue]{task.fields[filename]}", justify="right"),
319        module.BarColumn(bar_width=None),
320        "[progress.percentage]{task.percentage:>3.1f}%",
321        "•",
322        module.DownloadColumn(),
323        "•",
324        module.TransferSpeedColumn(),
325        "•",
326        module.TimeRemainingColumn(),
327    )
328    return progress
329
330
331def _install(config: dict, code_dir: str):
332    for config_info in config:
333        install_dir = '{}/{}'.format(code_dir, config_info.get('install_dir'))
334        script = config_info.get('script')
335        cmd = '{}/{}'.format(install_dir, script)
336        args = config_info.get('args')
337        for arg in args:
338            for key in arg.keys():
339                cmd = '{} --{}={}'.format(cmd, key, arg[key])
340        dest_dir = '{}/{}'.format(code_dir, config_info.get('destdir'))
341        cmd = '{} --destdir={}'.format(cmd, dest_dir)
342        _run_cmd(cmd)
343
344
345def main():
346    parser = argparse.ArgumentParser()
347    parser.add_argument('--skip-ssl', action='store_true', help='skip ssl authentication')
348    parser.add_argument('--unsafe-perm', action='store_true', help='add "--unsafe-perm" for npm install')
349    parser.add_argument('--disable-rich', action='store_true', help='disable the rich module')
350    parser.add_argument('--enable-symlink', action='store_true', help='enable symlink while copying node_modules')
351    parser.add_argument('--build-arkuix', action='store_true', help='build ArkUI-X SDK')
352    parser.add_argument('--tool-repo', default='https://repo.huaweicloud.com', help='prebuilt file download source')
353    parser.add_argument('--npm-registry', default='https://repo.huaweicloud.com/repository/npm/',
354                        help='npm download source')
355    parser.add_argument('--host-cpu', help='host cpu', required=True)
356    parser.add_argument('--host-platform', help='host platform', required=True)
357    parser.add_argument('--glibc-version', help='glibc version', required=False)
358    parser.add_argument('--config-file', help='prebuilts download config file')
359    args = parser.parse_args()
360    args.code_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
361    if args.skip_ssl:
362        ssl._create_default_https_context = ssl._create_unverified_context
363
364    host_platform = args.host_platform
365    host_cpu = args.host_cpu
366    glibc_version = args.glibc_version
367    tool_repo = args.tool_repo
368    if args.build_arkuix:
369        config_file = os.path.join(args.code_dir, 'build_plugins/prebuilts_download_config.json')
370    elif args.config_file:
371        config_file = args.config_file
372    else:
373        config_file = os.path.join(args.code_dir, 'build/prebuilts_download_config.json')
374    config_info = read_json_file(config_file)
375    if _is_system_component():
376        args.npm_install_config = config_info.get('npm_install_path')
377        node_modules_copy_config = config_info.get('node_modules_copy')
378    else:
379        args.npm_install_config = []
380        node_modules_copy_config = []
381    file_handle_config = config_info.get('file_handle_config')
382
383    args.bin_dir = os.path.join(args.code_dir, config_info.get('prebuilts_download_dir'))
384    if not os.path.exists(args.bin_dir):
385        os.makedirs(args.bin_dir, exist_ok=True)
386    copy_config = config_info.get(host_platform).get(host_cpu).get('copy_config')
387    node_config = config_info.get(host_platform).get('node_config')
388    copy_config.extend(node_config)
389    install_config = config_info.get(host_platform).get(host_cpu).get('install')
390    if host_platform == 'linux':
391        linux_copy_config = config_info.get(host_platform).get(host_cpu).get('linux_copy_config')
392        copy_config.extend(linux_copy_config)
393    elif host_platform == 'darwin':
394        darwin_copy_config = config_info.get(host_platform).get(host_cpu).get('darwin_copy_config')
395        copy_config.extend(darwin_copy_config)
396    if args.disable_rich:
397        _hwcloud_download(args, copy_config, args.bin_dir, args.code_dir, glibc_version)
398    else:
399        args.progress = _import_rich_module()
400        with args.progress:
401            _hwcloud_download(args, copy_config, args.bin_dir, args.code_dir, glibc_version)
402
403    _file_handle(file_handle_config, args.code_dir, args.host_platform)
404    retry_times = 0
405    max_retry_times = 2
406    while retry_times <= max_retry_times:
407        result, error = _npm_install(args)
408        if result:
409            break
410        print("npm install error, error info: %s" % error)
411        if retry_times == max_retry_times:
412            for error_info in error.split('\n'):
413                if error_info.endswith('debug.log'):
414                    log_path = error_info.split()[-1]
415                    cmd = ['cat', log_path]
416                    process_cat = subprocess.Popen(cmd)
417                    process_cat.communicate(timeout=60)
418                    raise Exception("npm install error with three times, prebuilts download exit")
419        retry_times += 1
420    _node_modules_copy(node_modules_copy_config, args.code_dir, args.enable_symlink)
421    if install_config:
422        _install(install_config, args.code_dir)
423
424    # delete uninstalled tools
425    uninstalled_tools = config_info.get('uninstalled_tools')
426    for tool_path in uninstalled_tools:
427        subprocess.run(['rm', '-rf', tool_path])
428
429if __name__ == '__main__':
430    sys.exit(main())
431