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'
27 class ConfigMgr(object):
28 DEFAULTS = {'common': {
29 "distro_name": "Default Distribution",
32 "tmpdir": '/var/tmp/mic',
33 "cachedir": '/var/tmp/mic/cache',
34 "outdir": './mic-output',
35 "bootstrapdir": '/var/tmp/mic/bootstrap',
37 "arch": None, # None means auto-detect
43 "local_pkgs_path": None,
48 "compress_disk_image": None,
65 # make the manager class as singleton
67 def __new__(cls, *args, **kwargs):
69 cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
73 def __init__(self, ksconf=None, siteconf=None):
74 # reset config options
77 # initial options from siteconf
79 self._siteconf = siteconf
81 # use default site config
82 self._siteconf = DEFAULT_GSITECONF
89 self.__siteconf = None
91 # initialize the values with defaults
92 for sec, vals in self.DEFAULTS.iteritems():
93 setattr(self, sec, vals)
95 def __set_siteconf(self, siteconf):
97 self.__siteconf = siteconf
98 self._parse_siteconf(siteconf)
99 except ConfigParser.Error, error:
100 raise errors.ConfigError("%s" % error)
101 def __get_siteconf(self):
102 return self.__siteconf
103 _siteconf = property(__get_siteconf, __set_siteconf)
105 def __set_ksconf(self, ksconf):
106 if not os.path.isfile(ksconf):
107 msger.error('Cannot find ks file: %s' % ksconf)
109 self.__ksconf = ksconf
110 self._parse_kickstart(ksconf)
111 def __get_ksconf(self):
113 _ksconf = property(__get_ksconf, __set_ksconf)
115 def _parse_siteconf(self, siteconf):
119 if not os.path.exists(siteconf):
120 raise errors.ConfigError("Failed to find config file: %s" \
123 parser = ConfigParser.SafeConfigParser()
124 parser.read(siteconf)
126 for section in parser.sections():
127 if section in self.DEFAULTS:
128 getattr(self, section).update(dict(parser.items(section)))
130 # append common section items to other sections
131 for section in self.DEFAULTS.keys():
132 if section != "common" and not section.startswith('bootstrap'):
133 getattr(self, section).update(self.common)
135 proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
137 for section in parser.sections():
138 if section.startswith('bootstrap'):
141 for option in parser.options(section):
143 name = parser.get(section, 'name')
146 val = parser.get(section, option)
148 (reponame, repoopt) = option.split('_')
149 if repostr.has_key(reponame):
150 repostr[reponame] += "%s:%s," % (repoopt, val)
152 repostr[reponame] = "%s:%s," % (repoopt, val)
155 if val.split(':')[0] in ('file', 'http', 'https', 'ftp'):
156 if repostr.has_key(option):
157 repostr[option] += "name:%s,baseurl:%s," % (option, val)
159 repostr[option] = "name:%s,baseurl:%s," % (option, val)
162 self.bootstraps[name] = repostr
164 def _selinux_check(self, arch, ks):
165 """If a user needs to use btrfs or creates ARM image,
166 selinux must be disabled at start.
169 for path in ["/usr/sbin/getenforce",
170 "/usr/bin/getenforce",
173 "/usr/local/sbin/getenforce",
174 "/usr/locla/bin/getenforce"
176 if os.path.exists(path):
177 selinux_status = runner.outs([path])
178 if arch and arch.startswith("arm") \
179 and selinux_status == "Enforcing":
180 raise errors.ConfigError("Can't create arm image if "
181 "selinux is enabled, please disable it and try again")
184 for part in ks.handler.partition.partitions:
185 if part.fstype == "btrfs":
189 if use_btrfs and selinux_status == "Enforcing":
190 raise errors.ConfigError("Can't create image using btrfs "
191 "filesystem if selinux is enabled, "
192 "please disable it and try again.")
195 def _parse_kickstart(self, ksconf=None):
199 ks = kickstart.read_kickstart(ksconf)
201 self.create['ks'] = ks
202 self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
204 if self.create['name_prefix']:
205 self.create['name'] = "%s-%s" % (self.create['name_prefix'],
208 self._selinux_check (self.create['arch'], ks)
210 msger.info("Retrieving repo metadata:")
211 ksrepos = misc.get_repostrs_from_ks(ks)
213 raise errors.KsError('no valid repos found in ks file')
215 self.create['repomd'] = misc.get_metadata_from_repos(
217 self.create['cachedir'])
220 self.create['rpmver'] = misc.get_rpmver_in_repo(self.create['repomd'])
222 target_archlist, archlist = misc.get_arch(self.create['repomd'])
223 if self.create['arch']:
224 if self.create['arch'] not in archlist:
225 raise errors.ConfigError("Invalid arch %s for repository. "
227 % (self.create['arch'], ', '.join(archlist)))
229 if len(target_archlist) == 1:
230 self.create['arch'] = str(target_archlist[0])
231 msger.info("\nUse detected arch %s." % target_archlist[0])
233 raise errors.ConfigError("Please specify a valid arch, "
234 "the choice can be: %s" \
235 % ', '.join(archlist))
237 kickstart.resolve_groups(self.create, self.create['repomd'])
239 configmgr = ConfigMgr()