Introduce --copy-kernel cmdline option to copy kernel files to output directory.
[tools/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
19 import ConfigParser
20
21 import msger
22 import kickstart
23 from .utils import misc, runner, proxy, errors
24
25 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
26
27 class ConfigMgr(object):
28     DEFAULTS = {'common': {
29                     "distro_name": "Default Distribution",
30                 },
31                 'create': {
32                     "tmpdir": '/var/tmp/mic',
33                     "cachedir": '/var/tmp/mic/cache',
34                     "outdir": './mic-output',
35                     "bootstrapdir": '/var/tmp/mic/bootstrap',
36
37                     "arch": None, # None means auto-detect
38                     "pkgmgr": "yum",
39                     "name": "output",
40                     "ksfile": None,
41                     "ks": None,
42                     "repomd": None,
43                     "local_pkgs_path": None,
44                     "release": None,
45                     "logfile": None,
46                     "record_pkgs": [],
47                     "rpmver": None,
48                     "compress_disk_image": None,
49                     "name_prefix": None,
50                     "proxy": None,
51                     "no_proxy": None,
52                     "copy_kernel": False,
53
54                     "runtime": None,
55                 },
56                 'chroot': {
57                     "saveto": None,
58                 },
59                 'convert': {
60                     "shell": False,
61                 },
62                 'bootstraps': {},
63                }
64
65     # make the manager class as singleton
66     _instance = None
67     def __new__(cls, *args, **kwargs):
68         if not cls._instance:
69             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
70
71         return cls._instance
72
73     def __init__(self, ksconf=None, siteconf=None):
74         # reset config options
75         self.reset()
76
77         # initial options from siteconf
78         if siteconf:
79             self._siteconf = siteconf
80         else:
81             # use default site config
82             self._siteconf = DEFAULT_GSITECONF
83
84         if ksconf:
85             self._ksconf = ksconf
86
87     def reset(self):
88         self.__ksconf = None
89         self.__siteconf = None
90
91         # initialize the values with defaults
92         for sec, vals in self.DEFAULTS.iteritems():
93             setattr(self, sec, vals)
94
95     def __set_siteconf(self, siteconf):
96         try:
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)
104
105     def __set_ksconf(self, ksconf):
106         if not os.path.isfile(ksconf):
107             msger.error('Cannot find ks file: %s' % ksconf)
108
109         self.__ksconf = ksconf
110         self._parse_kickstart(ksconf)
111     def __get_ksconf(self):
112         return self.__ksconf
113     _ksconf = property(__get_ksconf, __set_ksconf)
114
115     def _parse_siteconf(self, siteconf):
116         if not siteconf:
117             return
118
119         if not os.path.exists(siteconf):
120             raise errors.ConfigError("Failed to find config file: %s" \
121                                      % siteconf)
122
123         parser = ConfigParser.SafeConfigParser()
124         parser.read(siteconf)
125
126         for section in parser.sections():
127             if section in self.DEFAULTS:
128                 getattr(self, section).update(dict(parser.items(section)))
129
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)
134
135         proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
136
137         for section in parser.sections():
138             if section.startswith('bootstrap'):
139                 name = section
140                 repostr = {}
141                 for option in parser.options(section):
142                     if option == 'name':
143                         name = parser.get(section, 'name')
144                         continue
145
146                     val = parser.get(section, option)
147                     if '_' in option:
148                         (reponame, repoopt) = option.split('_')
149                         if repostr.has_key(reponame):
150                             repostr[reponame] += "%s:%s," % (repoopt, val)
151                         else:
152                             repostr[reponame] = "%s:%s," % (repoopt, val)
153                         continue
154
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)
158                         else:
159                             repostr[option]  = "name:%s,baseurl:%s," % (option, val)
160                         continue
161
162                 self.bootstraps[name] = repostr
163
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.
167         """
168
169         for path in ["/usr/sbin/getenforce",
170                      "/usr/bin/getenforce",
171                      "/sbin/getenforce",
172                      "/bin/getenforce",
173                      "/usr/local/sbin/getenforce",
174                      "/usr/locla/bin/getenforce"
175                      ]:
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")
182
183                 use_btrfs = False
184                 for part in ks.handler.partition.partitions:
185                     if part.fstype == "btrfs":
186                         use_btrfs = True
187                         break
188
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.")
193                 break
194
195     def _parse_kickstart(self, ksconf=None):
196         if not ksconf:
197             return
198
199         ks = kickstart.read_kickstart(ksconf)
200
201         self.create['ks'] = ks
202         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
203
204         if self.create['name_prefix']:
205             self.create['name'] = "%s-%s" % (self.create['name_prefix'],
206                                              self.create['name'])
207
208         self._selinux_check (self.create['arch'], ks)
209
210         msger.info("Retrieving repo metadata:")
211         ksrepos = misc.get_repostrs_from_ks(ks)
212         if not ksrepos:
213             raise errors.KsError('no valid repos found in ks file')
214
215         self.create['repomd'] = misc.get_metadata_from_repos(
216                                                     ksrepos,
217                                                     self.create['cachedir'])
218         msger.raw(" DONE")
219
220         self.create['rpmver'] = misc.get_rpmver_in_repo(self.create['repomd'])
221
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. "
226                                   "Valid arches: %s" \
227                                   % (self.create['arch'], ', '.join(archlist)))
228         else:
229             if len(target_archlist) == 1:
230                 self.create['arch'] = str(target_archlist[0])
231                 msger.info("\nUse detected arch %s." % target_archlist[0])
232             else:
233                 raise errors.ConfigError("Please specify a valid arch, "
234                                          "the choice can be: %s" \
235                                          % ', '.join(archlist))
236
237         kickstart.resolve_groups(self.create, self.create['repomd'])
238
239 configmgr = ConfigMgr()