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