[TIC-CORE] fix the issue that cannot analyze the install-dependency
[archive/20170607/tools/tic-core.git] / tic / command.py
1 #!/usr/bin/python
2 # Copyright (c) 2016 Samsung Electronics Co., Ltd
3 #
4 # Licensed under the Flora License, Version 1.1 (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://floralicense.org/license/
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 #
16 # Contributors:
17 # - S-Core Co., Ltd
18
19 import os
20 import logging
21 import hashlib
22
23 from tic.dependency import get_installed_packages
24 from tic.parser.recipe_parser import default_recipe, RecipeParser
25 from tic.parser.repo_parser import RepodataParser
26 from tic.parser.view_parser import make_view_data
27 from tic.utils.error import TICError
28 from tic.utils.file import copyfile
29 from tic.repo import get_repodata_from_repos
30 from tic.pykickstarter import KSoption, kswriter
31 from tic.utils import process
32 from tic.utils import misc
33 from tic.utils import file
34 from tic.config import configmgr
35
36 DEFAULT_CACHEDIR=configmgr.setting['tempdir']
37 DEFAULT_ANALYSISDIR=os.path.join(DEFAULT_CACHEDIR, 'analysis')
38 DEFAULT_KICKSTARTDIR=os.path.join(DEFAULT_CACHEDIR, 'kickstart')
39 DEFAULT_RECIPE_NAME='recipe.yaml';
40
41 def analyze(recipe_list):
42     logger = logging.getLogger(__name__)
43     if not recipe_list:
44         logger.info('Use default recipe because there is no import data')
45         recipe_list = default_recipe.getDefaultParameter()
46
47     recipe_parser = RecipeParser(recipe_list)
48     recipe_parser.parse()
49     recipe_info = recipe_parser.getMergedRecipe()
50     
51     start_time = misc.get_timestamp()
52     #Download repodata from repositories (Remote/Local)
53     repoinfo = get_repodata_from_repos(recipe_info.get('Repositories'), DEFAULT_CACHEDIR)
54     logger.info('time to get repodata from repo: %d ms', misc.get_timestamp() - start_time)
55     
56     checksum_list=[]
57     for repo in repoinfo:
58         checksum_list.append(repo['checksum'])
59     all_checksum = hashlib.sha256('_'.join(checksum_list)).hexdigest()
60     analysis_file=os.path.join(DEFAULT_ANALYSISDIR, all_checksum, 'analysis.json')
61     pkg_group=None
62     if os.path.exists(analysis_file):
63         pkg_group=file.read_json(analysis_file)
64
65     if not pkg_group or not pkg_group.get('pkg_dict'):
66         start_time = misc.get_timestamp()
67         # Parse the xml files for the analysis of package (.rpm)
68         repo_parser = RepodataParser('armv7l', repoinfo)
69         pkg_group = repo_parser.parse()
70         logger.info('packages: %d, provides: %d, files: %d', len(pkg_group['pkg_dict']), len(pkg_group['provides']), len(pkg_group['files']))
71         logger.info('time to parse repodata: %d ms', misc.get_timestamp() - start_time)
72         # dump to cached file
73         file.write_json_flock(analysis_file, pkg_group)
74     else:
75         logger.info('use a cache parsing data - %s', analysis_file)
76
77     start_time = misc.get_timestamp()
78     # Make a data for TIC (Tizen image creation)
79     view_data = make_view_data(pkg_group)
80     logger.info('time to create view-tree: %d ms', misc.get_timestamp() - start_time)
81     # analyze install-dependency
82     start_time = misc.get_timestamp()
83     inst_packages = get_installed_packages(recipe_info, repoinfo, pkg_group)
84     logger.info('installed package: %d', len(inst_packages))
85     logger.info('time to analyze dependency: %d ms', misc.get_timestamp() - start_time)
86
87     result = {'view': view_data,
88               'data': {'packages': pkg_group.get('pkg_dict'),
89                        'provides': pkg_group.get('provides'),
90                        'files': pkg_group.get('files'),
91                        'groups': pkg_group.get('groups'),
92                        'conflicts': pkg_group.get('conflicts')},
93               'recipes': recipe_parser.getRepositories(),
94               'installpackages': inst_packages}
95     return result
96
97 def imports(recipe_list):
98     logger = logging.getLogger(__name__)
99     if not recipe_list:
100         logger.info('Use default recipe because there is no import data')
101         recipe_list = default_recipe.getDefaultParameter()
102     
103     recipe_parser = RecipeParser(recipe_list)
104     recipe_parser.parse()
105     result = {'recipes': recipe_parser.getRepositories()}
106     #result = {'imports': recipe_parser.getMergedRepositories()}
107     return result
108
109 def exports(export_type, recipes, packages, outdir, filename=None):
110     logger = logging.getLogger(__name__)
111     #TODO validation should be checked before request
112     if not export_type:
113         export_type='ks'
114         logger.info('set default export format(.ks)')
115     if not filename and export_type == 'recipe':
116         filename = DEFAULT_RECIPE_NAME
117
118     if not recipes:
119         raise TICError(configmgr.message['recipes_not_define'])
120     if not packages or type(packages) is not list:
121         raise TICError(configmgr.message['no_package_to_install'])
122
123     recipe_parser = RecipeParser(recipes)
124     recipe_parser.parse()
125     result = None
126     if export_type == 'recipe':
127         recipe_path = recipe_parser.export2Recipe(packages, outdir, filename)
128         logger.info('export the recipe to %s' % recipe_path)
129         result = {'path': recipe_path}
130     elif export_type == 'ks':
131         # 1. create yaml files
132         yaml_info = recipe_parser.export2Yaml(packages, DEFAULT_KICKSTARTDIR)
133         # 2. create kickstart(.ks) using kickstarter tool
134         options = KSoption(yaml_info.configs, yaml_info.repos, yaml_info.cachedir)
135         kswriter(options)
136         # check whether the ks exists
137         recipe_info = recipe_parser.getMergedRecipe()
138         baseline=recipe_info['Recipe'].get('Baseline')
139         ksname= ''.join([recipe_info['Recipe'].get('FileName'), '.ks'])
140         kspath=os.path.join(yaml_info.cachedir, baseline, ksname)
141         logger.info('the kickstarter created the ks file (%s)' % kspath)
142         if not os.path.exists(kspath):
143             raise TICError('No ks file was created from kickstarter')
144         # copy the ks to output directory
145         output=copyfile(kspath, outdir, filename)
146         logger.info('export the ks to %s' % output)
147         result = {'path':output, 'arch':recipe_info['Recipe'].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)