auto selecting backend with 'pkgmgr=auto'
[tools/mic.git] / mic / conf.py
index 112164c..5177480 100644 (file)
@@ -15,7 +15,7 @@
 # with this program; if not, write to the Free Software Foundation, Inc., 59
 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
-import os
+import os, sys, re
 import ConfigParser
 
 import msger
@@ -24,18 +24,27 @@ from .utils import misc, runner, proxy, errors
 
 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
 
+def get_siteconf():
+    mic_path = os.path.dirname(__file__)
+
+    m = re.match(r"(?P<prefix>.*)\/lib(64)?\/.*", mic_path)
+    if m and m.group('prefix') != "/usr":
+        return os.path.join(m.group('prefix'), "etc/mic/mic.conf")
+
+    return DEFAULT_GSITECONF
+
 class ConfigMgr(object):
     DEFAULTS = {'common': {
                     "distro_name": "Default Distribution",
+                    "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
                 },
                 'create': {
                     "tmpdir": '/var/tmp/mic',
                     "cachedir": '/var/tmp/mic/cache',
                     "outdir": './mic-output',
-                    "bootstrapdir": '/var/tmp/mic/bootstrap',
 
                     "arch": None, # None means auto-detect
-                    "pkgmgr": "yum",
+                    "pkgmgr": "auto",
                     "name": "output",
                     "ksfile": None,
                     "ks": None,
@@ -44,13 +53,11 @@ class ConfigMgr(object):
                     "release": None,
                     "logfile": None,
                     "record_pkgs": [],
-                    "rpmver": None,
-                    "compress_disk_image": None,
+                    "pack_to": None,
                     "name_prefix": None,
                     "proxy": None,
                     "no_proxy": None,
-
-                    "runtime": None,
+                    "copy_kernel": False,
                 },
                 'chroot': {
                     "saveto": None,
@@ -58,7 +65,11 @@ class ConfigMgr(object):
                 'convert': {
                     "shell": False,
                 },
-                'bootstraps': {},
+                'bootstrap': {
+                    "enable": False,
+                    "distro_name": None,
+                    "rootdir": '/var/tmp/mic-bootstrap',
+                },
                }
 
     # make the manager class as singleton
@@ -73,12 +84,15 @@ class ConfigMgr(object):
         # reset config options
         self.reset()
 
+        if not siteconf:
+            siteconf = get_siteconf()
+
         # initial options from siteconf
-        if siteconf:
-            self._siteconf = siteconf
-        else:
-            # use default site config
-            self._siteconf = DEFAULT_GSITECONF
+        self._siteconf = siteconf
+
+        # set bootstrap from bootstrap.conf
+        bsconf = os.path.join(os.path.dirname(siteconf), 'bootstrap.conf')
+        self._parse_bootstrap(bsconf)
 
         if ksconf:
             self._ksconf = ksconf
@@ -116,8 +130,8 @@ class ConfigMgr(object):
             return
 
         if not os.path.exists(siteconf):
-            raise errors.ConfigError("Failed to find config file: %s" \
-                                     % siteconf)
+            msger.warning("cannot read config file: %s" % siteconf)
+            return
 
         parser = ConfigParser.SafeConfigParser()
         parser.read(siteconf)
@@ -131,65 +145,19 @@ class ConfigMgr(object):
             if section != "common" and not section.startswith('bootstrap'):
                 getattr(self, section).update(self.common)
 
-        proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
+        # check and normalize the scheme of proxy url
+        if self.create['proxy']:
+            m = re.match('^(\w+)://.*', self.create['proxy'])
+            if m:
+                scheme = m.group(1)
+                if scheme not in ('http', 'https', 'ftp', 'socks'):
+                    msger.error("%s: proxy scheme is incorrect" % siteconf)
+            else:
+                msger.warning("%s: proxy url w/o scheme, use http as default"
+                              % siteconf)
+                self.create['proxy'] = "http://" + self.create['proxy']
 
-        for section in parser.sections():
-            if section.startswith('bootstrap'):
-                name = section
-                repostr = {}
-                for option in parser.options(section):
-                    if option == 'name':
-                        name = parser.get(section, 'name')
-                        continue
-
-                    val = parser.get(section, option)
-                    if '_' in option:
-                        (reponame, repoopt) = option.split('_')
-                        if repostr.has_key(reponame):
-                            repostr[reponame] += "%s:%s," % (repoopt, val)
-                        else:
-                            repostr[reponame] = "%s:%s," % (repoopt, val)
-                        continue
-
-                    if val.split(':')[0] in ('file', 'http', 'https', 'ftp'):
-                        if repostr.has_key(option):
-                            repostr[option] += "name:%s,baseurl:%s," % (option, val)
-                        else:
-                            repostr[option]  = "name:%s,baseurl:%s," % (option, val)
-                        continue
-
-                self.bootstraps[name] = repostr
-
-    def _selinux_check(self, arch, ks):
-        """If a user needs to use btrfs or creates ARM image,
-        selinux must be disabled at start.
-        """
-
-        for path in ["/usr/sbin/getenforce",
-                     "/usr/bin/getenforce",
-                     "/sbin/getenforce",
-                     "/bin/getenforce",
-                     "/usr/local/sbin/getenforce",
-                     "/usr/locla/bin/getenforce"
-                     ]:
-            if os.path.exists(path):
-                selinux_status = runner.outs([path])
-                if arch and arch.startswith("arm") \
-                        and selinux_status == "Enforcing":
-                    raise errors.ConfigError("Can't create arm image if "
-                          "selinux is enabled, please disable it and try again")
-
-                use_btrfs = False
-                for part in ks.handler.partition.partitions:
-                    if part.fstype == "btrfs":
-                        use_btrfs = True
-                        break
-
-                if use_btrfs and selinux_status == "Enforcing":
-                    raise errors.ConfigError("Can't create image using btrfs "
-                                           "filesystem if selinux is enabled, "
-                                           "please disable it and try again.")
-                break
+        proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
 
     def _parse_kickstart(self, ksconf=None):
         if not ksconf:
@@ -204,8 +172,6 @@ class ConfigMgr(object):
             self.create['name'] = "%s-%s" % (self.create['name_prefix'],
                                              self.create['name'])
 
-        self._selinux_check (self.create['arch'], ks)
-
         msger.info("Retrieving repo metadata:")
         ksrepos = misc.get_repostrs_from_ks(ks)
         if not ksrepos:
@@ -216,8 +182,6 @@ class ConfigMgr(object):
                                                     self.create['cachedir'])
         msger.raw(" DONE")
 
-        self.create['rpmver'] = misc.get_rpmver_in_repo(self.create['repomd'])
-
         target_archlist, archlist = misc.get_arch(self.create['repomd'])
         if self.create['arch']:
             if self.create['arch'] not in archlist:
@@ -235,4 +199,35 @@ class ConfigMgr(object):
 
         kickstart.resolve_groups(self.create, self.create['repomd'])
 
+        # check selinux, it will block arm and btrfs image creation
+        misc.selinux_check(self.create['arch'],
+                           [p.fstype for p in ks.handler.partition.partitions])
+
+
+    def _parse_bootstrap(self, bsconf):
+        if not bsconf or not os.path.exists(bsconf):
+            self.bootstrap['enable'] = False
+            return
+
+        parser = ConfigParser.SafeConfigParser()
+        parser.read(bsconf)
+
+        for section in parser.sections():
+            if section == "main":
+                self.bootstrap.update(dict(parser.items(section)))
+            elif parser.has_option(section, 'packages'):
+                pkglist = parser.get(section, 'packages')
+                pkglist = pkglist.replace('\n', ' ')
+                self.bootstrap[section.lower()] = pkglist.split()
+                self.bootstrap['enable'] = True
+
+        # update bootstrap options
+        if self.bootstrap['enable'] not in (True, False):
+            try:
+                self.bootstrap['enable'] = parser.getboolean('main', 'enable')
+            except:
+                self.bootstrap['enable'] = False
+        if not self.bootstrap['distro_name']:
+            self.bootstrap['distro_name'] = self.common['distro_name']
+
 configmgr = ConfigMgr()