Another method of install tpk.
[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                 },
82                 'chroot': {
83                     "saveto": None,
84                 },
85                 'convert': {
86                     "shell": False,
87                 },
88                 'bootstrap': {
89                     "rootdir": '/var/tmp/mic-bootstrap',
90                     "packages": [],
91                     "distro_name": "",
92                 },
93                }
94
95     # make the manager class as singleton
96     _instance = None
97     def __new__(cls, *args, **kwargs):
98         if not cls._instance:
99             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
100
101         return cls._instance
102
103     def __init__(self, ksconf=None, siteconf=None):
104         # reset config options
105         self.reset()
106
107         if not siteconf:
108             siteconf = get_siteconf()
109
110         # initial options from siteconf
111         self._siteconf = siteconf
112
113         if ksconf:
114             self._ksconf = ksconf
115
116     def reset(self):
117         self.__ksconf = None
118         self.__siteconf = None
119
120         # initialize the values with defaults
121         for sec, vals in self.DEFAULTS.iteritems():
122             setattr(self, sec, vals)
123
124     def __set_siteconf(self, siteconf):
125         try:
126             self.__siteconf = siteconf
127             self._parse_siteconf(siteconf)
128         except ConfigParser.Error, error:
129             raise errors.ConfigError("%s" % error)
130     def __get_siteconf(self):
131         return self.__siteconf
132     _siteconf = property(__get_siteconf, __set_siteconf)
133
134     def __set_ksconf(self, ksconf):
135         if not os.path.isfile(ksconf):
136             raise errors.KsError('Cannot find ks file: %s' % ksconf)
137
138         self.__ksconf = ksconf
139         self._parse_kickstart(ksconf)
140     def __get_ksconf(self):
141         return self.__ksconf
142     _ksconf = property(__get_ksconf, __set_ksconf)
143
144     def _parse_siteconf(self, siteconf):
145
146         if os.getenv("MIC_PLUGIN_DIR"):
147             self.common["plugin_dir"] = os.environ["MIC_PLUGIN_DIR"]
148
149         if siteconf and not os.path.exists(siteconf):
150             msger.warning("cannot find config file: %s" % siteconf)
151             siteconf = None
152
153         if not siteconf:
154             self.common["distro_name"] = "Tizen"
155             # append common section items to other sections
156             for section in self.DEFAULTS.keys():
157                 if section != "common":
158                     getattr(self, section).update(self.common)
159
160             return
161
162         parser = ConfigParser.SafeConfigParser()
163         parser.read(siteconf)
164
165         for section in parser.sections():
166             if section in self.DEFAULTS:
167                 getattr(self, section).update(dict(parser.items(section)))
168
169         # append common section items to other sections
170         for section in self.DEFAULTS.keys():
171             if section != "common":
172                 getattr(self, section).update(self.common)
173
174         # check and normalize the scheme of proxy url
175         if self.create['proxy']:
176             m = re.match('^(\w+)://.*', self.create['proxy'])
177             if m:
178                 scheme = m.group(1)
179                 if scheme not in ('http', 'https', 'ftp', 'socks'):
180                     raise errors.ConfigError("%s: proxy scheme is incorrect" % siteconf)
181             else:
182                 msger.warning("%s: proxy url w/o scheme, use http as default"
183                               % siteconf)
184                 self.create['proxy'] = "http://" + self.create['proxy']
185
186         proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
187
188         # bootstrap option handling
189         self.set_runtime(self.create['runtime'])
190         if isinstance(self.bootstrap['packages'], basestring):
191             packages = self.bootstrap['packages'].replace('\n', ' ')
192             if packages.find(',') != -1:
193                 packages = packages.split(',')
194             else:
195                 packages = packages.split()
196             self.bootstrap['packages'] = packages
197
198     def _parse_kickstart(self, ksconf=None):
199         if not ksconf:
200             return
201
202         ksconf = misc.normalize_ksfile(ksconf,
203                                        self.create['release'],
204                                        self.create['arch'])
205
206         ks = kickstart.read_kickstart(ksconf)
207
208         self.create['ks'] = ks
209         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
210
211         self.create['name'] = misc.build_name(ksconf,
212                                               self.create['release'],
213                                               self.create['name_prefix'],
214                                               self.create['name_suffix'])
215
216         self.create['destdir'] = self.create['outdir']
217         if self.create['release'] is not None:
218             self.create['destdir'] = "%s/%s/images/%s/" % (self.create['outdir'],
219                                                            self.create['release'],
220                                                            self.create['name'])
221             self.create['name'] = self.create['release'] + '_' + self.create['name']
222
223             if not self.create['logfile']:
224                 self.create['logfile'] = os.path.join(self.create['destdir'],
225                                                       self.create['name'] + ".log")
226                 self.create['releaselog'] = True
227                 self.set_logfile()
228
229         msger.info("Retrieving repo metadata:")
230         ksrepos = kickstart.get_repos(ks,
231                                       self.create['extrarepos'],
232                                       self.create['ignore_ksrepo'])
233         if not ksrepos:
234             raise errors.KsError('no valid repos found in ks file')
235
236         for repo in ksrepos:
237             if hasattr(repo, 'baseurl') and repo.baseurl.startswith("file:"):
238                 repourl = repo.baseurl.replace('file:', '')
239                 repourl = "/%s" % repourl.lstrip('/')
240                 self.create['localrepos'].append(repourl)
241
242         self.create['repomd'] = misc.get_metadata_from_repos(
243                                                     ksrepos,
244                                                     self.create['cachedir'])
245         kstpkrepos = kickstart.get_tpkrepos(ks)
246         if kstpkrepos:
247             for tpk_repo in kstpkrepos:
248                 if hasattr(tpk_repo,'baseurl') and tpk_repo.baseurl.startswith("file:"):
249                     tpk_repourl = tpk_repo.baseurl.replace('file:','')
250                     tpk_repourl = "/%s" % tpk_repourl.lstrip('/')
251                     self.create['localtpkrepos'].append(tpk_repourl)
252
253         msger.raw(" DONE")
254
255         target_archlist, archlist = misc.get_arch(self.create['repomd'])
256         if self.create['arch']:
257             if self.create['arch'] not in archlist:
258                 raise errors.ConfigError("Invalid arch %s for repository. "
259                                   "Valid arches: %s" \
260                                   % (self.create['arch'], ', '.join(archlist)))
261         else:
262             if len(target_archlist) == 1:
263                 self.create['arch'] = str(target_archlist[0])
264                 msger.info("Use detected arch %s." % target_archlist[0])
265             else:
266                 raise errors.ConfigError("Please specify a valid arch, "
267                                          "the choice can be: %s" \
268                                          % ', '.join(archlist))
269
270         kickstart.resolve_groups(self.create, self.create['repomd'])
271
272         # check selinux, it will block arm and btrfs image creation
273         misc.selinux_check(self.create['arch'],
274                            [p.fstype for p in ks.handler.partition.partitions])
275
276     def set_logfile(self, logfile = None):
277         if not logfile:
278             logfile = self.create['logfile']
279
280         logfile_dir = os.path.dirname(self.create['logfile'])
281         if not os.path.exists(logfile_dir):
282             os.makedirs(logfile_dir)
283         msger.set_interactive(False)
284         if inbootstrap():
285             mode = 'a'
286         else:
287             mode = 'w'
288         msger.set_logfile(self.create['logfile'], mode)
289
290     def set_runtime(self, runtime):
291         if runtime != "bootstrap":
292             raise errors.CreatorError("Invalid runtime mode: %s, only 'bootstrap' mode is allowed." % runtime)
293
294         if misc.get_distro()[0] in ("tizen", "Tizen"):
295             runtime = "native"
296         self.create['runtime'] = runtime
297
298 configmgr = ConfigMgr()