40a156b307aa58f09f9b7c05e80c1f77939f6390
[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 from tic.config import configmgr
38
39 DEFAULT_CACHEDIR=configmgr.setting['tempdir']
40 DEFAULT_ANALYSISDIR=os.path.join(DEFAULT_CACHEDIR, 'analysis')
41 DEFAULT_KICKSTARTDIR=os.path.join(DEFAULT_CACHEDIR, 'kickstart')
42
43 def analyze(repo_list, recipe_list=None):
44     logger = logging.getLogger(__name__)
45     if not repo_list and not recipe_list:
46         raise TICError('No repositories defined')
47     repos = []
48     recipe = None
49     #TODO Repository check
50     # using default recipe (Temporary Code)
51     if recipe_list and recipe_list[0] == 'default':
52         recipe = get_default_recipe()
53         for repo_url in recipe.get('Repositories'):
54             repos.append({'name': repo_url.get('Name'),
55                           'url': repo_url.get('Url')})
56     else:
57         number=1
58         for repo_url in repo_list:
59             repos.append({'name': 'repository_%d' % number,
60                           'url': repo_url})
61             number = number + 1
62     start_time = misc.get_timestamp()
63     #Download repodata from repositories (Remote/Local)
64     repoinfo = get_repodata_from_repos(repos, DEFAULT_CACHEDIR)
65     logger.info('time to get repodata from repo: %d ms', misc.get_timestamp() - start_time)
66     
67     checksum_list=[]
68     for repo in repoinfo:
69         checksum_list.append(repo['checksum'])
70     all_checksum = hashlib.sha256('_'.join(checksum_list)).hexdigest()
71     analysis_file=os.path.join(DEFAULT_ANALYSISDIR, all_checksum, 'analysis.json')
72     pkg_group=None
73     if os.path.exists(analysis_file):
74         pkg_group=file.read_json(analysis_file)
75
76     if not pkg_group or not pkg_group.get('pkg_dict'):
77         start_time = misc.get_timestamp()
78         # Parse the xml files for the analysis of package (.rpm)
79         repo_parser = RepodataParser('armv7l', repoinfo)
80         pkg_group = repo_parser.parse()
81         logger.info('packages: %d, provides: %d, files: %d', len(pkg_group['pkg_dict']), len(pkg_group['provides']), len(pkg_group['files']))
82         logger.info('time to parse repodata: %d ms', misc.get_timestamp() - start_time)
83         # dump to cached file
84         file.write_json_flock(analysis_file, pkg_group)
85     else:
86         logger.info('use a cache parsing data - %s', analysis_file)
87
88     start_time = misc.get_timestamp()
89     # Make a data for TIC (Tizen image creation)
90     view_data = make_view_data(pkg_group)
91     # analyze install-dependency
92     inst_packages = get_installed_packages(recipe, repoinfo, pkg_group)
93     logger.info('installed package: %d', len(inst_packages))
94     logger.info('time to analyze dependency: %d ms', misc.get_timestamp() - start_time)
95
96     result = {'view': view_data,
97               'data': {'packages': pkg_group.get('pkg_dict'),
98                        'provides': pkg_group.get('provides'),
99                        'files': pkg_group.get('files'),
100                        'groups': pkg_group.get('groups'),
101                        'conflicts': pkg_group.get('conflicts')},
102               'repos': repos,
103               'defaultpackages': inst_packages}
104     return result
105
106 def exports(export_type, recipe, packages, outdir, filename=None):
107     logger = logging.getLogger(__name__)
108     #TODO validation should be checked before request
109     if not export_type:
110         export_type='ks'
111         logger.info('set default export format(.ks)')
112
113     if not recipe:
114         raise TICError('No recipe defined')
115     if not packages or type(packages) is not list:
116         raise TICError('No packages defined')
117
118     #TODO recipe parsing
119     # Temporary code for 1st prototype release
120     if recipe.get('name') == 'default':
121         recipe = get_default_recipe()
122         config = recipe.get('Configurations')[0]
123         for key in ['Default', config['Platform']]:
124             recipe[key]['Groups']=[]
125             recipe[key]['ExtraPackages']=[]
126         config['Groups']=[]
127         config['ExtraPackages'] = packages
128     else:
129         raise TICError('No recipes defined')
130     
131     # create the yaml
132     yaml_info = convert_recipe_to_yaml(recipe, DEFAULT_KICKSTARTDIR)
133     
134     # create kickstart(.ks) using kickstarter tool
135     options = KSoption(yaml_info.configs, yaml_info.repos, yaml_info.cachedir)
136     kswriter(options)
137     
138     # check whether the ks exists
139     baseline=recipe['Default'].get('Baseline')
140     ksname= ''.join([config.get('FileName'), '.ks'])
141     kspath=os.path.join(yaml_info.cachedir, baseline, ksname)
142     if not os.path.exists(kspath):
143         raise TICError('No ks file was created from kickstarter')
144     
145     # copy the ks to output directory
146     output=copyfile(kspath, outdir, filename)
147     logger.info('copy the ks file from %s to dst:%s', kspath, output)
148     result = {'kspath':output, 'arch':config.get('Architecture')}
149     return result
150
151 def createimage(recipes, ksfile, outdir):
152     logger = logging.getLogger(__name__)
153     
154     if recipes:
155         logger.info('the recipes option is not yet supported')
156         return
157     
158     if not os.path.exists(ksfile) or os.path.isdir(ksfile):
159         raise TICError('kickstart file does not exist')
160     
161     mic_command=['mic', 'cr', 'auto', ksfile]
162     if outdir:
163         mic_command.append('--outdir=%s' % outdir)
164     
165     process.run(mic_command, 2)