Merge "Another method of install tpk." into devel
[tools/mic.git] / mic / conf.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2011 Intel, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18 import os, sys, re
19 import ConfigParser
20
21 from mic import msger
22 from mic import kickstart
23 from mic.utils import misc, runner, proxy, errors
24
25
26 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
27
28
29 def get_siteconf():
30     if hasattr(sys, 'real_prefix'):
31         return os.path.join(sys.prefix, "etc/mic/mic.conf")
32     else:
33         return DEFAULT_GSITECONF
34
35 def inbootstrap():
36     if os.path.exists(os.path.join("/", ".chroot.lock")):
37         return True
38     return (os.stat("/").st_ino != 2)
39
40 class ConfigMgr(object):
41     prefer_backends = ["zypp", "yum"]
42
43     DEFAULTS = {'common': {
44                     "distro_name": "Default Distribution",
45                     "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
46                 },
47                 'create': {
48                     "tmpdir": '/var/tmp/mic',
49                     "cachedir": '/var/tmp/mic/cache',
50                     "outdir": './mic-output',
51                     "destdir": None,
52                     "arch": None, # None means auto-detect
53                     "pkgmgr": "auto",
54                     "name": "output",
55                     "ksfile": None,
56                     "ks": None,
57                     "repomd": None,
58                     "local_pkgs_path": None,
59                     "release": None,
60                     "logfile": None,
61                     "releaselog": False,
62                     "record_pkgs": [],
63                     "pack_to": None,
64                     "name_prefix": None,
65                     "name_suffix": None,
66                     "proxy": None,
67                     "no_proxy": None,
68                     "ssl_verify": "yes",
69                     "copy_kernel": False,
70                     "install_pkgs": None,
71                     "check_pkgs": [],
72                     "repourl": {},
73                     "localrepos": [],  # save localrepos
74                     "localtpkrepos":[],
75                     "runtime": "bootstrap",
76                     "extrarepos": {},
77                     "ignore_ksrepo": False,
78                     "strict_mode": False,
79                     "run_script": None,
80                     "tpk_install": None,
81                     "use_mic_in_bootstrap": False,
82                 },
83                 'chroot': {
84                     "saveto": None,
85                 },
86                 'convert': {
87                     "shell": False,
88                 },
89                 'bootstrap': {
90                     "rootdir": '/var/tmp/mic-bootstrap',
91                     "packages": [],
92                     "distro_name": "",
93                 },
94                }
95
96     # make the manager class as singleton
97     _instance = None
98     def __new__(cls, *args, **kwargs):
99         if not cls._instance:
100             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
101
102         return cls._instance
103
104     def __init__(self, ksconf=None, siteconf=None):
105         # reset config options
106         self.reset()
107
108         if not siteconf:
109             siteconf = get_siteconf()
110
111         # initial options from siteconf
112         self._siteconf = siteconf
113
114         if ksconf:
115             self._ksconf = ksconf
116
117     def reset(self):
118         self.__ksconf = None
119         self.__siteconf = None
120
121         # initialize the values with defaults
122         for sec, vals in self.DEFAULTS.iteritems():
123             setattr(self, sec, vals)
124
125     def __set_siteconf(self, siteconf):
126         try:
127             self.__siteconf = siteconf
128             self._parse_siteconf(siteconf)
129         except ConfigParser.Error, error:
130             raise errors.ConfigError("%s" % error)
131     def __get_siteconf(self):
132         return self.__siteconf
133     _siteconf = property(__get_siteconf, __set_siteconf)
134
135     def __set_ksconf(self, ksconf):
136         if not os.path.isfile(ksconf):
137             raise errors.KsError('Cannot find ks file: %s' % ksconf)
138
139         self.__ksconf = ksconf
140         self._parse_kickstart(ksconf)
141     def __get_ksconf(self):
142         return self.__ksconf
143     _ksconf = property(__get_ksconf, __set_ksconf)
144
145     def _parse_siteconf(self, siteconf):
146
147         if os.getenv("MIC_PLUGIN_DIR"):
148             self.common["plugin_dir"] = os.environ["MIC_PLUGIN_DIR"]
149
150         if siteconf and not os.path.exists(siteconf):
151             msger.warning("cannot find config file: %s" % siteconf)
152             siteconf = None
153
154         if not siteconf:
155             self.common["distro_name"] = "Tizen"
156             # append common section items to other sections
157             for section in self.DEFAULTS.keys():
158                 if section != "common":
159                     getattr(self, section).update(self.common)
160
161             return
162
163         parser = ConfigParser.SafeConfigParser()
164         parser.read(siteconf)
165
166         for section in parser.sections():
167             if section in self.DEFAULTS:
168                 getattr(self, section).update(dict(parser.items(section)))
169
170         # append common section items to other sections
171         for section in self.DEFAULTS.keys():
172             if section != "common":
173                 getattr(self, section).update(self.common)
174
175         # check and normalize the scheme of proxy url
176         if self.create['proxy']:
177             m = re.match('^(\w+)://.*', self.create['proxy'])
178             if m:
179                 scheme = m.group(1)
180                 if scheme not in ('http', 'https', 'ftp', 'socks'):
181                     raise errors.ConfigError("%s: proxy scheme is incorrect" % siteconf)
182             else:
183                 msger.warning("%s: proxy url w/o scheme, use http as default"
184                               % siteconf)
185                 self.create['proxy'] = "http://" + self.create['proxy']
186
187         proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
188
189         # bootstrap option handling
190         self.set_runtime(self.create['runtime'])
191         if isinstance(self.bootstrap['packages'], basestring):
192             packages = self.bootstrap['packages'].replace('\n', ' ')
193             if packages.find(',') != -1:
194                 packages = packages.split(',')
195             else:
196                 packages = packages.split()
197             self.bootstrap['packages'] = packages
198
199         if type(self.create['use_mic_in_bootstrap']) != 'bool':
200             use_mic_in_bootstrap = str(self.create['use_mic_in_bootstrap'])
201             if use_mic_in_bootstrap.lower() in ('on', 'yes', 'true', '1'):
202                 self.create['use_mic_in_bootstrap'] = True
203             else:
204                 self.create['use_mic_in_bootstrap'] = False
205
206     def _parse_kickstart(self, ksconf=None):
207         if not ksconf:
208             return
209
210         ksconf = misc.normalize_ksfile(ksconf,
211                                        self.create['release'],
212                                        self.create['arch'])
213
214         ks = kickstart.read_kickstart(ksconf)
215
216         self.create['ks'] = ks
217         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
218
219         self.create['name'] = misc.build_name(ksconf,
220                                               self.create['release'],
221                                               self.create['name_prefix'],
222                                               self.create['name_suffix'])
223
224         self.create['destdir'] = self.create['outdir']
225         if self.create['release'] is not None:
226             self.create['destdir'] = "%s/%s/images/%s/" % (self.create['outdir'],
227                                                            self.create['release'],
228                                                            self.create['name'])
229             self.create['name'] = self.create['release'] + '_' + self.create['name']
230             if self.create['pack_to'] is not None:
231                 if '@NAME@' in self.create['pack_to']:
232                     self.create['pack_to'] = self.create['pack_to'].replace('@NAME@', self.create['name'])
233                 self.create['name'] = misc.strip_archive_suffix(self.create['pack_to'])
234                 if self.create['name'] is None:
235                     raise errors.CreatorError("Not supported archive file format: %s" % self.create['pack_to'])
236
237             if not self.create['logfile']:
238                 self.create['logfile'] = os.path.join(self.create['destdir'],
239                                                       self.create['name'] + ".log")
240                 self.create['releaselog'] = True
241                 self.set_logfile()
242
243         elif self.create['pack_to'] is not None:
244             if '@NAME@' in self.create['pack_to']:
245                 self.create['pack_to'] = self.create['pack_to'].replace('@NAME@', self.create['name'])
246             self.create['name'] = misc.strip_archive_suffix(self.create['pack_to'])
247             if self.create['name'] is None:
248                 raise errors.CreatorError("Not supported archive file format: %s" % self.create['pack_to'])
249
250         msger.info("Retrieving repo metadata:")
251         ksrepos = kickstart.get_repos(ks,
252                                       self.create['extrarepos'],
253                                       self.create['ignore_ksrepo'])
254         if not ksrepos:
255             raise errors.KsError('no valid repos found in ks file')
256
257         for repo in ksrepos:
258             if hasattr(repo, 'baseurl') and repo.baseurl.startswith("file:"):
259                 repourl = repo.baseurl.replace('file:', '')
260                 repourl = "/%s" % repourl.lstrip('/')
261                 self.create['localrepos'].append(repourl)
262
263         self.create['repomd'] = misc.get_metadata_from_repos(
264                                                     ksrepos,
265                                                     self.create['cachedir'])
266         kstpkrepos = kickstart.get_tpkrepos(ks)
267         if kstpkrepos:
268             for tpk_repo in kstpkrepos:
269                 if hasattr(tpk_repo,'baseurl') and tpk_repo.baseurl.startswith("file:"):
270                     tpk_repourl = tpk_repo.baseurl.replace('file:','')
271                     tpk_repourl = "/%s" % tpk_repourl.lstrip('/')
272                     self.create['localtpkrepos'].append(tpk_repourl)
273
274         msger.raw(" DONE")
275
276         target_archlist, archlist = misc.get_arch(self.create['repomd'])
277         if self.create['arch']:
278             if self.create['arch'] not in archlist:
279                 raise errors.ConfigError("Invalid arch %s for repository. "
280                                   "Valid arches: %s" \
281                                   % (self.create['arch'], ', '.join(archlist)))
282         else:
283             if len(target_archlist) == 1:
284                 self.create['arch'] = str(target_archlist[0])
285                 msger.info("Use detected arch %s." % target_archlist[0])
286             else:
287                 raise errors.ConfigError("Please specify a valid arch, "
288                                          "the choice can be: %s" \
289                                          % ', '.join(archlist))
290
291         kickstart.resolve_groups(self.create, self.create['repomd'])
292
293         # check selinux, it will block arm and btrfs image creation
294         misc.selinux_check(self.create['arch'],
295                            [p.fstype for p in ks.handler.partition.partitions])
296
297     def set_logfile(self, logfile = None):
298         if not logfile:
299             logfile = self.create['logfile']
300
301         logfile_dir = os.path.dirname(self.create['logfile'])
302         if not os.path.exists(logfile_dir):
303             os.makedirs(logfile_dir)
304         msger.set_interactive(False)
305         if inbootstrap():
306             mode = 'a'
307         else:
308             mode = 'w'
309         msger.set_logfile(self.create['logfile'], mode)
310
311     def set_runtime(self, runtime):
312         if runtime != "bootstrap":
313             raise errors.CreatorError("Invalid runtime mode: %s, only 'bootstrap' mode is allowed." % runtime)
314
315         if misc.get_distro()[0] in ("tizen", "Tizen"):
316             runtime = "native"
317         self.create['runtime'] = runtime
318
319 configmgr = ConfigMgr()