fix sdks list bug: move rgx into db-dump
[src/xds/xds-server.git] / scripts / sdks / agl / db-dump
1 #!/usr/bin/python3
2 #
3 # /**************************************************************************
4 # * Copyright 2017-2018 IoT.bzh
5 # *
6 # * author: Romain Forlot <romain.forlot@iot.bzh>
7 # *
8 # * Licensed under the Apache License, Version 2.0 (the "License");
9 # * you may not use this file except in compliance with the License.
10 # * You may obtain a copy of the License at
11 # *
12 # *     http://www.apache.org/licenses/LICENSE-2.0
13 # *
14 # * Unless required by applicable law or agreed to in writing, software
15 # * distributed under the License is distributed on an "AS IS" BASIS,
16 # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 # * See the License for the specific language governing permissions and
18 # * limitations under the License.
19 # **************************************************************************/
20
21 import os
22 import json
23 import logging
24 import inspect
25 import fnmatch
26 import argparse
27 import subprocess
28 import re
29
30 PARSER = argparse.ArgumentParser(
31     description='Lists available and installed SDKs')
32 PARSER.add_argument('-debug', dest='debug', action='store_true',
33                     help='Output debug log messages')
34
35 ARGS = PARSER.parse_args()
36
37 if ARGS.debug:
38     logging.basicConfig(level=logging.DEBUG,
39                         format='%(asctime)s:%(levelname)s: %(message)s')
40 else:
41     logging.basicConfig(level=logging.INFO,
42                         format='%(asctime)s:%(levelname)s: %(message)s')
43
44 SCRIPT_PATH = os.path.dirname(os.path.abspath(
45     inspect.getfile(inspect.currentframe())))
46
47 ENV = subprocess.check_output(
48     [os.path.join(SCRIPT_PATH, './_env-init.sh'), '-print']).splitlines()
49
50 SDK_ROOT_DIR = None
51 for elt in ENV:
52     #only match what defines a variable
53     z = re.match(r"^(\w+)=([^']*)$", elt.decode())
54     if z:
55         k = z.group(1)
56         v = z.group(2)
57         if k == 'SDK_ROOT_DIR':
58             SDK_ROOT_DIR = v.rstrip('/')
59         elif k == 'SDK_ENV_SETUP_FILENAME':
60             SDK_ENV_SETUP_FILENAME = v
61
62 if SDK_ROOT_DIR is None:
63     logging.error('No SDK_ROOT_DIR environment variable found.')
64     exit(1)
65 elif SDK_ENV_SETUP_FILENAME is None:
66     SDK_ENV_SETUP_FILENAME = 'environment-setup*'
67
68 # Get list of available SDKs
69 SDK_DB_FILEPATH = os.path.join(SDK_ROOT_DIR, "sdks_latest.json")
70
71 if not os.path.exists(SDK_DB_FILEPATH):
72     DB_UPDATE_FILEPATH = os.path.join(SCRIPT_PATH, 'db-update')
73     os.system(DB_UPDATE_FILEPATH + " " + SDK_DB_FILEPATH)
74
75 SDK_DB_JSON = json.load(open(SDK_DB_FILEPATH, 'r'))
76
77 for one_sdk in SDK_DB_JSON:
78     one_sdk['status'] = 'Not Installed'
79     one_sdk['uuid'] = ''
80
81 INSTALLED_SDK = []
82 for root, dirs, files in os.walk(SDK_ROOT_DIR):
83     depth = root[len(SDK_ROOT_DIR) + len(os.path.sep):].count(os.path.sep)
84     # Limit the walking depth of processed directories
85     if depth >= 4:
86         dirs[:] = []
87     # Only process SDK dir matching profile/version/arch or
88     # profile/version/arch/tag
89     elif depth != 2 and depth != 3:
90         continue
91     EF, VF = '', ''
92     for one_file in files:
93         if fnmatch.fnmatch(one_file, SDK_ENV_SETUP_FILENAME):
94             EF = os.path.join(root, one_file)
95         if fnmatch.fnmatch(one_file, 'version-*'):
96             VF = os.path.join(root, one_file)
97     if EF != '' and VF != '':
98         logging.debug('Adding installed SDK ' + root)
99         INSTALLED_SDK.append({'ENV_FILE': EF, 'VERSION_FILE': VF})
100     elif (EF == '' and VF != '') or (EF != '' and VF == ''):
101         logging.debug(
102             'WARNING SDK ignored : root=%s, EnvFile=%s, VersFile=%s', root, EF, VF)
103
104 for one_sdk in INSTALLED_SDK:
105     logging.debug("Processing %s", one_sdk['ENV_FILE'])
106     envFile = one_sdk['ENV_FILE'].split(SDK_ROOT_DIR+'/')[1]
107     PROFILE = envFile.split('/')[0]
108     VERSION = envFile.split('/')[1]
109     ARCH = envFile.split('/')[2]
110     DIR = os.path.dirname(one_sdk['ENV_FILE'])
111     if PROFILE == '' or VERSION == '' or ARCH == '' or DIR == '':
112         logging.debug('Path not compliant, skipping')
113         continue
114
115     UUID = os.path.basename(os.path.normpath(DIR))
116
117     SDK_DATE = ''
118     for line in open(one_sdk['VERSION_FILE']).readlines():
119         if line.startswith('Timestamp'):
120             D = line.split(':')[1]
121             if D:
122                 D = D.strip()
123                 SDK_DATE = '{}-{}-{} {}:{}'.format(
124                     D[0:4], D[4:6], D[6:8], D[8:10], D[10:12])
125                 logging.debug('Found date: %s', SDK_DATE)
126
127     found = False
128     for sdk in SDK_DB_JSON:
129         if sdk['profile'] == PROFILE and sdk['version'] == VERSION and sdk['arch'] == ARCH:
130             if sdk['status'] == 'Installed':
131                 continue
132             found = True
133             sdk['status'] = 'Installed'
134             sdk['date'] = SDK_DATE
135             sdk['setupFile'] = one_sdk['ENV_FILE']
136             sdk['path'] = DIR
137             sdk['uuid'] = UUID
138             break
139
140     if not found:
141         logging.debug('Not found in database, add: ' +
142                       PROFILE + '-' + ARCH + '-' + VERSION)
143         NEW_SDK = {
144             'name': PROFILE + '-' + ARCH + '-' + VERSION,
145             'uuid': UUID,
146             'description': 'AGL SDK ' + ARCH + ' (version ' + VERSION + ')',
147             'profile': PROFILE,
148             'version': VERSION,
149             'arch': ARCH,
150             'path': DIR,
151             'url': "",
152             'status': "Installed",
153             'date': SDK_DATE,
154             'size': "",
155             'md5sum': "",
156             'setupFile': one_sdk['ENV_FILE']
157         }
158         SDK_DB_JSON.append(NEW_SDK)
159
160 print(json.dumps(SDK_DB_JSON))