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
35 class ConfigMgr(object):
36 prefer_backends = ["zypp", "yum"]
38 DEFAULTS = {'common': {
39 "distro_name": "Default Distribution",
40 "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
43 "tmpdir": '/var/tmp/mic',
44 "cachedir": '/var/tmp/mic/cache',
45 "outdir": './mic-output',
47 "plugin_dir": "/usr/lib/mic/plugins",
48 "arch": None, # None means auto-detect
54 "local_pkgs_path": None,
67 "localrepos": [], # save localrepos
68 "runtime": "bootstrap",
77 "rootdir": '/var/tmp/mic-bootstrap',
83 # make the manager class as singleton
85 def __new__(cls, *args, **kwargs):
87 cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
91 def __init__(self, ksconf=None, siteconf=None):
92 # reset config options
96 siteconf = get_siteconf()
98 # initial options from siteconf
99 self._siteconf = siteconf
102 self._ksconf = ksconf
106 self.__siteconf = None
108 # initialize the values with defaults
109 for sec, vals in self.DEFAULTS.iteritems():
110 setattr(self, sec, vals)
112 def __set_siteconf(self, siteconf):
114 self.__siteconf = siteconf
115 self._parse_siteconf(siteconf)
116 except ConfigParser.Error, error:
117 raise errors.ConfigError("%s" % error)
118 def __get_siteconf(self):
119 return self.__siteconf
120 _siteconf = property(__get_siteconf, __set_siteconf)
122 def __set_ksconf(self, ksconf):
123 if not os.path.isfile(ksconf):
124 msger.error('Cannot find ks file: %s' % ksconf)
126 self.__ksconf = ksconf
127 self._parse_kickstart(ksconf)
128 def __get_ksconf(self):
130 _ksconf = property(__get_ksconf, __set_ksconf)
132 def _parse_siteconf(self, siteconf):
136 if not os.path.exists(siteconf):
137 msger.warning("cannot read config file: %s" % siteconf)
140 parser = ConfigParser.SafeConfigParser()
141 parser.read(siteconf)
143 for section in parser.sections():
144 if section in self.DEFAULTS:
145 getattr(self, section).update(dict(parser.items(section)))
147 # append common section items to other sections
148 for section in self.DEFAULTS.keys():
149 if section != "common":
150 getattr(self, section).update(self.common)
152 # check and normalize the scheme of proxy url
153 if self.create['proxy']:
154 m = re.match('^(\w+)://.*', self.create['proxy'])
157 if scheme not in ('http', 'https', 'ftp', 'socks'):
158 msger.error("%s: proxy scheme is incorrect" % siteconf)
160 msger.warning("%s: proxy url w/o scheme, use http as default"
162 self.create['proxy'] = "http://" + self.create['proxy']
164 proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
166 # bootstrap option handling
167 self.set_runtime(self.create['runtime'])
168 if isinstance(self.bootstrap['packages'], basestring):
169 packages = self.bootstrap['packages'].replace('\n', ' ')
170 if packages.find(',') != -1:
171 packages = packages.split(',')
173 packages = packages.split()
174 self.bootstrap['packages'] = packages
176 def _parse_kickstart(self, ksconf=None):
180 ksconf = misc.normalize_ksfile(ksconf,
181 self.create['release'],
184 ks = kickstart.read_kickstart(ksconf)
186 self.create['ks'] = ks
187 self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
189 self.create['name'] = misc.build_name(ksconf,
190 self.create['release'],
191 self.create['name_prefix'],
192 self.create['name_suffix'])
194 msger.info("Retrieving repo metadata:")
195 ksrepos = misc.get_repostrs_from_ks(ks)
197 raise errors.KsError('no valid repos found in ks file')
200 if 'baseurl' in repo and repo['baseurl'].startswith("file:"):
201 repourl = repo['baseurl'].replace('file:', '')
202 repourl = "/%s" % repourl.lstrip('/')
203 self.create['localrepos'].append(repourl)
205 self.create['repomd'] = misc.get_metadata_from_repos(
207 self.create['cachedir'])
210 target_archlist, archlist = misc.get_arch(self.create['repomd'])
211 if self.create['arch']:
212 if self.create['arch'] not in archlist:
213 raise errors.ConfigError("Invalid arch %s for repository. "
215 % (self.create['arch'], ', '.join(archlist)))
217 if len(target_archlist) == 1:
218 self.create['arch'] = str(target_archlist[0])
219 msger.info("\nUse detected arch %s." % target_archlist[0])
221 raise errors.ConfigError("Please specify a valid arch, "
222 "the choice can be: %s" \
223 % ', '.join(archlist))
225 kickstart.resolve_groups(self.create, self.create['repomd'])
227 # check selinux, it will block arm and btrfs image creation
228 misc.selinux_check(self.create['arch'],
229 [p.fstype for p in ks.handler.partition.partitions])
231 def set_runtime(self, runtime):
232 if runtime not in ("bootstrap", "native"):
233 msger.error("Invalid runtime mode: %s" % runtime)
235 if misc.get_distro()[0] in ("tizen", "Tizen"):
237 self.create['runtime'] = runtime
239 configmgr = ConfigMgr()