[TIC-CORE] support caching for analysis data
[archive/20170607/tools/tic-core.git] / tic / command.py
1 #!/usr/bin/python
2 # Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
3 #
4 # Contact: 
5 # @author Chulwoo Shin <cw1.shin@samsung.com>
6
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 # Contributors:
20 # - S-Core Co., Ltd
21
22 import os
23 import logging
24 import hashlib
25
26 from tic.dependency import get_installed_packages
27 from tic.parser.recipe_parser import get_default_recipe, convert_recipe_to_yaml
28 from tic.parser.repo_parser import RepodataParser
29 from tic.parser.view_parser import make_view_data
30 from tic.utils.error import TICError
31 from tic.utils.file import copyfile
32 from tic.repo import get_repodata_from_repos
33 from tic.pykickstarter import KSoption, kswriter
34 from tic.utils import process
35 from tic.utils import misc
36 from tic.utils import file
37
38 DEFAULT_CACHEDIR='/var/tmp/tic-core'
39 DEFAULT_ANALYSIS_CACHEDIR='/var/tmp/tic-core/analysis'
40 DEFAULT_KICKSTARTDIR='/var/tmp/tic-core/kickstart'
41
42 def analyze(repo_list, recipe_list=None):
43     logger = logging.getLogger(__name__)
44     if not repo_list and not recipe_list:
45         raise TICError('No repositories defined')
46     repos = []
47     recipe = None
48     #TODO Repository check
49     # using default recipe (Temporary Code)
50     if recipe_list and recipe_list[0] == 'default':
51         recipe = get_default_recipe()
52         for repo_url in recipe.get('Repositories'):
53             repos.append({'name': repo_url.get('Name'),
54                           'url': repo_url.get('Url')})
55     else:
56         number=1
57         for repo_url in repo_list:
58             repos.append({'name': 'repository_%d' % number,
59                           'url': repo_url})
60             number = number + 1
61     start_time = misc.get_timestamp()
62     #Download repodata from repositories (Remote/Local)
63     repoinfo = get_repodata_from_repos(repos, DEFAULT_CACHEDIR)
64     logger.info('time to get repodata from repo: %d ms', misc.get_timestamp() - start_time)
65     
66     checksum_list=[]
67     for repo in repoinfo:
68         checksum_list.append(repo['checksum'])
69     all_checksum = hashlib.sha256('_'.join(checksum_list)).hexdigest()
70     analysis_file=os.path.join(DEFAULT_ANALYSIS_CACHEDIR, all_checksum, 'analysis.json')
71     pkg_group=None
72     if os.path.exists(analysis_file):
73         pkg_group=file.read_json(analysis_file)
74
75     if not pkg_group or not pkg_group.get('pkg_dict'):
76         start_time = misc.get_timestamp()
77         # Parse the xml files for the analysis of package (.rpm)
78         repo_parser = RepodataParser('armv7l', repoinfo)
79         pkg_group = repo_parser.parse()
80         logger.info('packages: %d, provides: %d, files: %d', len(pkg_group['pkg_dict']), len(pkg_group['provides']), len(pkg_group['files']))
81         logger.info('time to parse repodata: %d ms', misc.get_timestamp() - start_time)
82         # dump to cached file
83         file.write_json_flock(analysis_file, pkg_group)
84     else:
85         logger.info('use a cache parsing data - %s', analysis_file)
86
87     start_time = misc.get_timestamp()
88     # Make a data for TIC (Tizen image creation)
89     view_data = make_view_data(pkg_group)
90     # analyze install-dependency
91     inst_packages = get_installed_packages(recipe, repoinfo, pkg_group)
92     logger.info('installed package: %d', len(inst_packages))
93     logger.info('time to analyze dependency: %d ms', misc.get_timestamp() - start_time)
94
95     result = {'view': view_data,
96               'data': {'packages': pkg_group.get('pkg_dict'),
97                        'provides': pkg_group.get('provides'),
98                        'files': pkg_group.get('files'),
99                        'groups': pkg_group.get('groups'),
100                        'conflicts': pkg_group.get('conflicts')},
101               'repos': repos,
102               'defaultpackages': inst_packages}
103     return result
104
105 def exports(export_type, recipe, packages, outdir, filename=None):
106     logger = logging.getLogger(__name__)
107     #TODO validation should be checked before request
108     if not export_type:
109         export_type='ks'
110         logger.info('set default export format(.ks)')
111
112     if not recipe:
113         raise TICError('No recipe defined')
114     if not packages or type(packages) is not list:
115         raise TICError('No packages defined')
116
117     #TODO recipe parsing
118     # Temporary code for 1st prototype release
119     if recipe.get('name') == 'default':
120         recipe = get_default_recipe()
121         config = recipe.get('Configurations')[0]
122         for key in ['Default', config['Platform']]:
123             recipe[key]['Groups']=[]
124             recipe[key]['ExtraPackages']=[]
125         config['Groups']=[]
126         config['ExtraPackages'] = packages
127     else:
128         raise TICError('No recipes defined')
129     
130     # create the yaml
131     yaml_info = convert_recipe_to_yaml(recipe, DEFAULT_KICKSTARTDIR)
132     
133     # create kickstart(.ks) using kickstarter tool
134     options = KSoption(yaml_info.configs, yaml_info.repos, yaml_info.cachedir)
135     kswriter(options)
136     
137     # check whether the ks exists
138     baseline=recipe['Default'].get('Baseline')
139     ksname= ''.join([config.get('FileName'), '.ks'])
140     kspath=os.path.join(yaml_info.cachedir, baseline, ksname)
141     if not os.path.exists(kspath):
142         raise TICError('No ks file was created from kickstarter')
143     
144     # copy the ks to output directory
145     output=copyfile(kspath, outdir, filename)
146     logger.info('copy the ks file from %s to dst:%s', kspath, output)
147     result = {'kspath':output, 'arch':config.get('Architecture')}
148     return result
149
150 def createimage(recipes, ksfile, outdir):
151     logger = logging.getLogger(__name__)
152     
153     if recipes:
154         logger.info('the recipes option is not yet supported')
155         return
156     
157     if not os.path.exists(ksfile) or os.path.isdir(ksfile):
158         raise TICError('kickstart file does not exist')
159     
160     mic_command=['mic', 'cr', 'auto', ksfile]
161     if outdir:
162         mic_command.append('--outdir=%s' % outdir)
163     
164     process.run(mic_command, 2)