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.
23 from .utils import misc, runner, proxy, errors
25 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
28 mic_path = os.path.dirname(__file__)
30 m = re.match(r"(?P<prefix>.*)\/lib(64)?\/.*", mic_path)
31 if m and m.group('prefix') != "/usr":
32 return os.path.join(m.group('prefix'), "etc/mic/mic.conf")
34 return DEFAULT_GSITECONF
36 class ConfigMgr(object):
37 DEFAULTS = {'common': {
38 "distro_name": "Default Distribution",
39 "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
42 "tmpdir": '/var/tmp/mic',
43 "cachedir": '/var/tmp/mic/cache',
44 "outdir": './mic-output',
46 "arch": None, # None means auto-detect
52 "local_pkgs_path": None,
71 "rootdir": '/var/tmp/mic-bootstrap',
75 # make the manager class as singleton
77 def __new__(cls, *args, **kwargs):
79 cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
83 def __init__(self, ksconf=None, siteconf=None):
84 # reset config options
88 siteconf = get_siteconf()
90 # initial options from siteconf
91 self._siteconf = siteconf
93 # set bootstrap from bootstrap.conf
94 bsconf = os.path.join(os.path.dirname(siteconf), 'bootstrap.conf')
95 self._parse_bootstrap(bsconf)
102 self.__siteconf = None
104 # initialize the values with defaults
105 for sec, vals in self.DEFAULTS.iteritems():
106 setattr(self, sec, vals)
108 def __set_siteconf(self, siteconf):
110 self.__siteconf = siteconf
111 self._parse_siteconf(siteconf)
112 except ConfigParser.Error, error:
113 raise errors.ConfigError("%s" % error)
114 def __get_siteconf(self):
115 return self.__siteconf
116 _siteconf = property(__get_siteconf, __set_siteconf)
118 def __set_ksconf(self, ksconf):
119 if not os.path.isfile(ksconf):
120 msger.error('Cannot find ks file: %s' % ksconf)
122 self.__ksconf = ksconf
123 self._parse_kickstart(ksconf)
124 def __get_ksconf(self):
126 _ksconf = property(__get_ksconf, __set_ksconf)
128 def _parse_siteconf(self, siteconf):
132 if not os.path.exists(siteconf):
133 msger.warning("cannot read config file: %s" % siteconf)
136 parser = ConfigParser.SafeConfigParser()
137 parser.read(siteconf)
139 for section in parser.sections():
140 if section in self.DEFAULTS:
141 getattr(self, section).update(dict(parser.items(section)))
143 # append common section items to other sections
144 for section in self.DEFAULTS.keys():
145 if section != "common" and not section.startswith('bootstrap'):
146 getattr(self, section).update(self.common)
148 # check and normalize the scheme of proxy url
149 if self.create['proxy']:
150 m = re.match('^(\w+)://.*', self.create['proxy'])
153 if scheme not in ('http', 'https', 'ftp', 'socks'):
154 msger.error("%s: proxy scheme is incorrect" % siteconf)
156 msger.warning("%s: proxy url w/o scheme, use http as default"
158 self.create['proxy'] = "http://" + self.create['proxy']
160 proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
162 def _parse_kickstart(self, ksconf=None):
166 ks = kickstart.read_kickstart(ksconf)
168 self.create['ks'] = ks
169 self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
171 if self.create['name_prefix']:
172 self.create['name'] = "%s-%s" % (self.create['name_prefix'],
175 msger.info("Retrieving repo metadata:")
176 ksrepos = misc.get_repostrs_from_ks(ks)
178 raise errors.KsError('no valid repos found in ks file')
180 self.create['repomd'] = misc.get_metadata_from_repos(
182 self.create['cachedir'])
185 target_archlist, archlist = misc.get_arch(self.create['repomd'])
186 if self.create['arch']:
187 if self.create['arch'] not in archlist:
188 raise errors.ConfigError("Invalid arch %s for repository. "
190 % (self.create['arch'], ', '.join(archlist)))
192 if len(target_archlist) == 1:
193 self.create['arch'] = str(target_archlist[0])
194 msger.info("\nUse detected arch %s." % target_archlist[0])
196 raise errors.ConfigError("Please specify a valid arch, "
197 "the choice can be: %s" \
198 % ', '.join(archlist))
200 kickstart.resolve_groups(self.create, self.create['repomd'])
202 # check selinux, it will block arm and btrfs image creation
203 misc.selinux_check(self.create['arch'],
204 [p.fstype for p in ks.handler.partition.partitions])
207 def _parse_bootstrap(self, bsconf):
208 if not bsconf or not os.path.exists(bsconf):
209 self.bootstrap['enable'] = False
212 parser = ConfigParser.SafeConfigParser()
215 for section in parser.sections():
216 if section == "main":
217 self.bootstrap.update(dict(parser.items(section)))
218 elif parser.has_option(section, 'packages'):
219 pkglist = parser.get(section, 'packages')
220 pkglist = pkglist.replace('\n', ' ')
221 self.bootstrap[section.lower()] = pkglist.split()
222 self.bootstrap['enable'] = True
224 # update bootstrap options
225 if self.bootstrap['enable'] not in (True, False):
227 self.bootstrap['enable'] = parser.getboolean('main', 'enable')
229 self.bootstrap['enable'] = False
230 if not self.bootstrap['distro_name']:
231 self.bootstrap['distro_name'] = self.common['distro_name']
233 configmgr = ConfigMgr()