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