Merge remote branch 'origin/master'
[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, sys
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                 },
44                 'chroot': {},
45                 'convert': {},
46                }
47
48     # make the manager class as singleton
49     _instance = None
50     def __new__(cls, *args, **kwargs):
51         if not cls._instance:
52             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
53
54         return cls._instance
55
56     def __init__(self, ksconf=None, siteconf=None):
57         # reset config options
58         self.reset()
59
60         if not siteconf:
61             # initial options from siteconf
62             self._siteconf = DEFAULT_GSITECONF
63
64     def reset(self):
65         self.__ksconf = None
66         self.__siteconf = None
67
68         # initialize the values with defaults
69         for sec, vals in self.DEFAULTS.iteritems():
70             setattr(self, sec, vals)
71
72     def __set_siteconf(self, siteconf):
73         try:
74             self.__siteconf = siteconf
75             self._parse_siteconf(siteconf)
76         except ConfigParser.Error, error:
77             raise errors.ConfigError("%s" % error)
78     def __get_siteconf(self):
79         return self.__siteconf
80     _siteconf = property(__get_siteconf, __set_siteconf)
81
82     def __set_ksconf(self, ksconf):
83         if not os.path.isfile(ksconf):
84             msger.error('Cannot find ks file: %s' % ksconf)
85
86         self.__ksconf = ksconf
87         self._parse_kickstart(ksconf)
88     def __get_ksconf(self):
89         return self.__ksconf
90     _ksconf = property(__get_ksconf, __set_ksconf)
91
92     def _parse_siteconf(self, siteconf):
93         if not siteconf:
94             return
95
96         if not os.path.exists(siteconf):
97             raise errors.ConfigError("Failed to find config file: %s" % siteconf)
98
99         parser = ConfigParser.SafeConfigParser()
100         parser.read(siteconf)
101
102         for section in parser.sections():
103             if section in self.DEFAULTS.keys():
104                 getattr(self, section).update(dict(parser.items(section)))
105
106     def _selinux_check(self, arch, ks):
107         """ If a user needs to use btrfs or creates ARM image, selinux must be disabled at start """
108
109         for path in ["/usr/sbin/getenforce",
110                      "/usr/bin/getenforce",
111                      "/sbin/getenforce",
112                      "/bin/getenforce",
113                      "/usr/local/sbin/getenforce",
114                      "/usr/locla/bin/getenforce"
115                      ]:
116             if os.path.exists(path):
117                 selinux_status = runner.outs([path])
118                 if  arch and arch.startswith("arm") and selinux_status == "Enforcing":
119                     raise errors.ConfigError("Can't create arm image if selinux is enabled, please disbale it and try again")
120
121                 use_btrfs = False
122                 parts = ks.handler.partition.partitions
123                 for part in ks.handler.partition.partitions:
124                     if part.fstype == "btrfs":
125                         use_btrfs = True
126                         break
127
128                 if use_btrfs and selinux_status == "Enforcing":
129                     raise errors.ConfigError("Can't create image useing btrfs filesystem if selinux is enabled, please disbale it and try again")
130
131                 break
132
133     def _parse_kickstart(self, ksconf=None):
134         if not ksconf:
135             return
136
137         ks = kickstart.read_kickstart(ksconf)
138
139         self.create['ks'] = ks
140         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
141
142         self._selinux_check (self.create['arch'], ks)
143
144         msger.info("Retrieving repo metadata:")
145         ksrepos = misc.get_repostrs_from_ks(ks)
146         self.create['repomd'] = misc.get_metadata_from_repos(ksrepos, self.create['cachedir'])
147         msger.raw(" DONE")
148
149         target_archlist = misc.get_arch(self.create['repomd'])
150         if self.create['arch']:
151             if self.create['arch'] not in target_archlist:
152                 raise errors.ConfigError("Invalid arch %s for repository. Valid arches: %s"\
153                                          % (self.create['arch'], ', '.join(target_archlist)))
154         else:
155             if len(target_archlist) == 1:
156                 self.create['arch'] = str(target_archlist[0])
157                 msger.info("\nUse detected arch %s." % target_archlist[0])
158             else:
159                 raise errors.ConfigError("Please specify a valid arch, "
160                                          "your choise can be: " % ', '.join(target_archlist))
161
162         kickstart.resolve_groups(self.create, self.create['repomd'])
163
164 configmgr = ConfigMgr()