Add get_rpmver_in_repo() for rpmversion
[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                     "arch": None, # None means auto-detect
36                     "pkgmgr": "yum",
37                     "name": "output",
38                     "ksfile": None,
39                     "ks": None,
40                     "repomd": None,
41                     "local_pkgs_path": None,
42                     "release": None,
43                     "logfile": None,
44                     "record_pkgs": [],
45                     "rpmver": None,
46                     "compress_disk_image": None,
47                     "name_prefix": None,
48                     "proxy": None,
49                     "no_proxy": None,
50                 },
51                 'chroot': {},
52                 'convert': {},
53                }
54
55     # make the manager class as singleton
56     _instance = None
57     def __new__(cls, *args, **kwargs):
58         if not cls._instance:
59             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
60
61         return cls._instance
62
63     def __init__(self, ksconf=None, siteconf=None):
64         # reset config options
65         self.reset()
66
67         # initial options from siteconf
68         if siteconf:
69             self._siteconf = siteconf
70         else:
71             # use default site config
72             self._siteconf = DEFAULT_GSITECONF
73
74         if ksconf:
75             self._ksconf = ksconf
76
77     def reset(self):
78         self.__ksconf = None
79         self.__siteconf = None
80
81         # initialize the values with defaults
82         for sec, vals in self.DEFAULTS.iteritems():
83             setattr(self, sec, vals)
84
85     def __set_siteconf(self, siteconf):
86         try:
87             self.__siteconf = siteconf
88             self._parse_siteconf(siteconf)
89         except ConfigParser.Error, error:
90             raise errors.ConfigError("%s" % error)
91     def __get_siteconf(self):
92         return self.__siteconf
93     _siteconf = property(__get_siteconf, __set_siteconf)
94
95     def __set_ksconf(self, ksconf):
96         if not os.path.isfile(ksconf):
97             msger.error('Cannot find ks file: %s' % ksconf)
98
99         self.__ksconf = ksconf
100         self._parse_kickstart(ksconf)
101     def __get_ksconf(self):
102         return self.__ksconf
103     _ksconf = property(__get_ksconf, __set_ksconf)
104
105     def _parse_siteconf(self, siteconf):
106         if not siteconf:
107             return
108
109         if not os.path.exists(siteconf):
110             raise errors.ConfigError("Failed to find config file: %s" \
111                                      % siteconf)
112
113         parser = ConfigParser.SafeConfigParser()
114         parser.read(siteconf)
115
116         for section in parser.sections():
117             if section in self.DEFAULTS:
118                 getattr(self, section).update(dict(parser.items(section)))
119
120         # append common section items to other sections
121         for section in self.DEFAULTS.keys():
122             if section != "common":
123                 getattr(self, section).update(self.common)
124
125         proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
126
127     def _selinux_check(self, arch, ks):
128         """If a user needs to use btrfs or creates ARM image,
129         selinux must be disabled at start.
130         """
131
132         for path in ["/usr/sbin/getenforce",
133                      "/usr/bin/getenforce",
134                      "/sbin/getenforce",
135                      "/bin/getenforce",
136                      "/usr/local/sbin/getenforce",
137                      "/usr/locla/bin/getenforce"
138                      ]:
139             if os.path.exists(path):
140                 selinux_status = runner.outs([path])
141                 if arch and arch.startswith("arm") \
142                         and selinux_status == "Enforcing":
143                     raise errors.ConfigError("Can't create arm image if "
144                           "selinux is enabled, please disable it and try again")
145
146                 use_btrfs = False
147                 for part in ks.handler.partition.partitions:
148                     if part.fstype == "btrfs":
149                         use_btrfs = True
150                         break
151
152                 if use_btrfs and selinux_status == "Enforcing":
153                     raise errors.ConfigError("Can't create image using btrfs "
154                                            "filesystem if selinux is enabled, "
155                                            "please disable it and try again.")
156                 break
157
158     def _parse_kickstart(self, ksconf=None):
159         if not ksconf:
160             return
161
162         ks = kickstart.read_kickstart(ksconf)
163
164         self.create['ks'] = ks
165         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
166
167         if self.create['name_prefix']:
168             self.create['name'] = "%s-%s" % (self.create['name_prefix'],
169                                              self.create['name'])
170
171         self._selinux_check (self.create['arch'], ks)
172
173         msger.info("Retrieving repo metadata:")
174         ksrepos = misc.get_repostrs_from_ks(ks)
175         self.create['repomd'] = misc.get_metadata_from_repos(
176                                                     ksrepos,
177                                                     self.create['cachedir'])
178         msger.raw(" DONE")
179
180         self.create['rpmver'] = misc.get_rpmver_in_repo(self.create['repomd'])
181
182         target_archlist, archlist = misc.get_arch(self.create['repomd'])
183         if self.create['arch']:
184             if self.create['arch'] not in archlist:
185                 raise errors.ConfigError("Invalid arch %s for repository. "
186                                   "Valid arches: %s" \
187                                   % (self.create['arch'], ', '.join(archlist)))
188         else:
189             if len(target_archlist) == 1:
190                 self.create['arch'] = str(target_archlist[0])
191                 msger.info("\nUse detected arch %s." % target_archlist[0])
192             else:
193                 raise errors.ConfigError("Please specify a valid arch, "
194                                          "your choise can be: %s" \
195                                          % ', '.join(archlist))
196
197         kickstart.resolve_groups(self.create, self.create['repomd'])
198
199 configmgr = ConfigMgr()