3 # Copyright (c) 2011 Intel, Inc.
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
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
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.
22 from mic import kickstart
23 from mic.utils import misc, runner, proxy, errors
26 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
30 if hasattr(sys, 'real_prefix'):
31 return os.path.join(sys.prefix, "etc/mic/mic.conf")
33 return DEFAULT_GSITECONF
36 if os.path.exists(os.path.join("/", ".chroot.lock")):
38 return (os.stat("/").st_ino != 2)
40 class ConfigMgr(object):
41 prefer_backends = ["zypp", "yum"]
43 DEFAULTS = {'common': {
44 "distro_name": "Default Distribution",
45 "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
48 "tmpdir": '/var/tmp/mic',
49 "cachedir": '/var/tmp/mic/cache',
50 "outdir": './mic-output',
52 "arch": None, # None means auto-detect
58 "local_pkgs_path": None,
73 "localrepos": [], # save localrepos
75 "runtime": "bootstrap",
77 "ignore_ksrepo": False,
81 "use_mic_in_bootstrap": False,
90 "rootdir": '/var/tmp/mic-bootstrap',
96 # make the manager class as singleton
98 def __new__(cls, *args, **kwargs):
100 cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
104 def __init__(self, ksconf=None, siteconf=None):
105 # reset config options
109 siteconf = get_siteconf()
111 # initial options from siteconf
112 self._siteconf = siteconf
115 self._ksconf = ksconf
119 self.__siteconf = None
121 # initialize the values with defaults
122 for sec, vals in self.DEFAULTS.iteritems():
123 setattr(self, sec, vals)
125 def __set_siteconf(self, siteconf):
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)
135 def __set_ksconf(self, ksconf):
136 if not os.path.isfile(ksconf):
137 raise errors.KsError('Cannot find ks file: %s' % ksconf)
139 self.__ksconf = ksconf
140 self._parse_kickstart(ksconf)
141 def __get_ksconf(self):
143 _ksconf = property(__get_ksconf, __set_ksconf)
145 def _parse_siteconf(self, siteconf):
147 if os.getenv("MIC_PLUGIN_DIR"):
148 self.common["plugin_dir"] = os.environ["MIC_PLUGIN_DIR"]
150 if siteconf and not os.path.exists(siteconf):
151 msger.warning("cannot find config file: %s" % 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)
163 parser = ConfigParser.SafeConfigParser()
164 parser.read(siteconf)
166 for section in parser.sections():
167 if section in self.DEFAULTS:
168 getattr(self, section).update(dict(parser.items(section)))
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)
175 # check and normalize the scheme of proxy url
176 if self.create['proxy']:
177 m = re.match('^(\w+)://.*', self.create['proxy'])
180 if scheme not in ('http', 'https', 'ftp', 'socks'):
181 raise errors.ConfigError("%s: proxy scheme is incorrect" % siteconf)
183 msger.warning("%s: proxy url w/o scheme, use http as default"
185 self.create['proxy'] = "http://" + self.create['proxy']
187 proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
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(',')
196 packages = packages.split()
197 self.bootstrap['packages'] = packages
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
204 self.create['use_mic_in_bootstrap'] = False
206 def _parse_kickstart(self, ksconf=None):
210 ksconf = misc.normalize_ksfile(ksconf,
211 self.create['release'],
214 ks = kickstart.read_kickstart(ksconf)
216 self.create['ks'] = ks
217 self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
219 self.create['name'] = misc.build_name(ksconf,
220 self.create['release'],
221 self.create['name_prefix'],
222 self.create['name_suffix'])
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'],
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'])
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
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'])
250 msger.info("Retrieving repo metadata:")
251 ksrepos = kickstart.get_repos(ks,
252 self.create['extrarepos'],
253 self.create['ignore_ksrepo'])
255 raise errors.KsError('no valid repos found in ks file')
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)
263 self.create['repomd'] = misc.get_metadata_from_repos(
265 self.create['cachedir'])
266 kstpkrepos = kickstart.get_tpkrepos(ks)
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)
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. "
281 % (self.create['arch'], ', '.join(archlist)))
283 if len(target_archlist) == 1:
284 self.create['arch'] = str(target_archlist[0])
285 msger.info("Use detected arch %s." % target_archlist[0])
287 raise errors.ConfigError("Please specify a valid arch, "
288 "the choice can be: %s" \
289 % ', '.join(archlist))
291 kickstart.resolve_groups(self.create, self.create['repomd'])
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])
297 def set_logfile(self, logfile = None):
299 logfile = self.create['logfile']
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)
309 msger.set_logfile(self.create['logfile'], mode)
311 def set_runtime(self, runtime):
312 if runtime != "bootstrap":
313 raise errors.CreatorError("Invalid runtime mode: %s, only 'bootstrap' mode is allowed." % runtime)
315 if misc.get_distro()[0] in ("tizen", "Tizen"):
317 self.create['runtime'] = runtime
319 configmgr = ConfigMgr()