ae3b31c4af4451b37b07d0c9fe4196efd7aeaf1e
[platform/core/ml/nnfw.git] / compiler / onecc-docker / onecc-docker
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2022 Samsung Electronics Co., Ltd. All Rights Reserved
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import sys
18 import subprocess
19 import json
20 import requests
21 import os
22 import argparse
23
24
25 def _run(cmd, is_shell=False):
26     result = subprocess.Popen(
27         cmd, shell=is_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
28
29     stdout, stderr = result.communicate()
30     stdout = stdout.decode('utf-8')
31     stderr = stderr.decode('utf-8')
32
33     if result.returncode:
34         print(stderr, end='')
35         exit(result.returncode)
36     else:
37         return stdout
38
39
40 def _image_exists(name):
41     cmd = ['docker', 'images', '-q', name]
42     lines = _run(cmd).splitlines()
43     return lines
44
45
46 def main():
47     script_path = os.path.dirname(os.path.realpath(__file__))
48     dockerfile_path = os.path.join(script_path, 'docker')
49
50     onecc_docker_usage = 'onecc-docker [-h] [-t TOKEN] [COMMAND <args>]'
51     onecc_docker_desc = 'Run onecc via docker'
52     parser = argparse.ArgumentParser(
53         usage=onecc_docker_usage, description=onecc_docker_desc)
54     parser.add_argument(
55         "-t",
56         "--token",
57         help=
58         "Token for authentication to GitHub. This is a workaround for Rate limit exceeded error"
59     )
60
61     args, onecc_arguments = parser.parse_known_args()
62     authorization_token = args.token
63
64     LATEST_URL = "https://api.github.com/repos/Samsung/ONE/releases/latest"
65     headers = {}
66     if authorization_token:
67         headers = {"Authorization": "Bearer {}".format(authorization_token)}
68     try:
69         response = requests.get(LATEST_URL, headers=headers)
70         response.raise_for_status()
71     except requests.exceptions.RequestException as e:
72         raise SystemExit('onecc-docker: error: {}'.format(e))
73
74     versions_str = response.content
75     versions_json = json.loads(versions_str)
76     recent_version = versions_json["tag_name"]
77
78     image_name = f"onecc:{recent_version}"
79     build_arg = f"VERSION={recent_version}"
80
81     if not _image_exists(image_name):
82         build_cmd = [
83             "docker", "build", "-t", image_name, "--build-arg", build_arg, dockerfile_path
84         ]
85         print('build Docker image ...')
86         _run(build_cmd)
87         print('Dockerfile successfully built.')
88
89     contianer_name = f"onecc_{recent_version.replace('.','_')}"
90     user_cmd = ' '.join(onecc_arguments)
91
92     run_cmd = [
93         "docker", "run", "--rm", "-u", "$(id -u):$(id -g)", "--name", contianer_name,
94         "-v", "${HOME}:${HOME}", "-e", "HOME=${HOME}", "-w", "${PWD}", image_name,
95         user_cmd
96     ]
97
98     cmd = ' '.join(run_cmd)
99     output = _run(cmd, is_shell=True)
100     print(output, end='')
101
102
103 if __name__ == "__main__":
104     try:
105         main()
106     except Exception as e:
107         prog_name = os.path.basename(__file__)
108         print(f"{prog_name}: {type(e).__name__}: " + str(e), file=sys.stderr)
109         sys.exit(255)