Use cpio gzip in mic.
[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, re
19 import ConfigParser
20
21 from mic import msger
22 from mic import kickstart
23 from mic.utils import misc, runner, proxy, errors
24
25
26 DEFAULT_GSITECONF = '/etc/mic/mic.conf'
27
28
29 def get_siteconf():
30     if hasattr(sys, 'real_prefix'):
31         return os.path.join(sys.prefix, "etc/mic/mic.conf")
32     else:
33         return DEFAULT_GSITECONF
34
35 def inbootstrap():
36     if os.path.exists(os.path.join("/", ".chroot.lock")):
37         return True
38     return (os.stat("/").st_ino != 2)
39
40 class ConfigMgr(object):
41     prefer_backends = ["zypp", "yum"]
42
43     DEFAULTS = {'common': {
44                     "distro_name": "Default Distribution",
45                     "plugin_dir": "/usr/lib/mic/plugins", # TODO use prefix also?
46                 },
47                 'create': {
48                     "tmpdir": '/var/tmp/mic',
49                     "cachedir": '/var/tmp/mic/cache',
50                     "outdir": './mic-output',
51                     "destdir": None,
52                     "arch": None, # None means auto-detect
53                     "pkgmgr": "auto",
54                     "name": "output",
55                     "ksfile": None,
56                     "ks": None,
57                     "repomd": None,
58                     "local_pkgs_path": None,
59                     "release": None,
60                     "logfile": None,
61                     "releaselog": False,
62                     "record_pkgs": [],
63                     "pack_to": None,
64                     "name_prefix": None,
65                     "name_suffix": None,
66                     "proxy": None,
67                     "no_proxy": None,
68                     "ssl_verify": "yes",
69                     "copy_kernel": False,
70                     "install_pkgs": None,
71                     "check_pkgs": [],
72                     "repourl": {},
73                     "localrepos": [],  # save localrepos
74                     "runtime": "bootstrap",
75                     "extrarepos": {},
76                     "ignore_ksrepo": False,
77                     "strict_mode": False,
78                     "cpio":False,
79                 },
80                 'chroot': {
81                     "saveto": None,
82                 },
83                 'convert': {
84                     "shell": False,
85                 },
86                 'bootstrap': {
87                     "rootdir": '/var/tmp/mic-bootstrap',
88                     "packages": [],
89                     "distro_name": "",
90                 },
91                }
92
93     # make the manager class as singleton
94     _instance = None
95     def __new__(cls, *args, **kwargs):
96         if not cls._instance:
97             cls._instance = super(ConfigMgr, cls).__new__(cls, *args, **kwargs)
98
99         return cls._instance
100
101     def __init__(self, ksconf=None, siteconf=None):
102         # reset config options
103         self.reset()
104
105         if not siteconf:
106             siteconf = get_siteconf()
107
108         # initial options from siteconf
109         self._siteconf = siteconf
110
111         if ksconf:
112             self._ksconf = ksconf
113
114     def reset(self):
115         self.__ksconf = None
116         self.__siteconf = None
117
118         # initialize the values with defaults
119         for sec, vals in self.DEFAULTS.iteritems():
120             setattr(self, sec, vals)
121
122     def __set_siteconf(self, siteconf):
123         try:
124             self.__siteconf = siteconf
125             self._parse_siteconf(siteconf)
126         except ConfigParser.Error, error:
127             raise errors.ConfigError("%s" % error)
128     def __get_siteconf(self):
129         return self.__siteconf
130     _siteconf = property(__get_siteconf, __set_siteconf)
131
132     def __set_ksconf(self, ksconf):
133         if not os.path.isfile(ksconf):
134             raise errors.KsError('Cannot find ks file: %s' % ksconf)
135
136         self.__ksconf = ksconf
137         self._parse_kickstart(ksconf)
138     def __get_ksconf(self):
139         return self.__ksconf
140     _ksconf = property(__get_ksconf, __set_ksconf)
141
142     def _parse_siteconf(self, siteconf):
143
144         if os.getenv("MIC_PLUGIN_DIR"):
145             self.common["plugin_dir"] = os.environ["MIC_PLUGIN_DIR"]
146
147         if siteconf and not os.path.exists(siteconf):
148             msger.warning("cannot find config file: %s" % siteconf)
149             siteconf = None
150
151         if not siteconf:
152             self.common["distro_name"] = "Tizen"
153             # append common section items to other sections
154             for section in self.DEFAULTS.keys():
155                 if section != "common":
156                     getattr(self, section).update(self.common)
157
158             return
159
160         parser = ConfigParser.SafeConfigParser()
161         parser.read(siteconf)
162
163         for section in parser.sections():
164             if section in self.DEFAULTS:
165                 getattr(self, section).update(dict(parser.items(section)))
166
167         # append common section items to other sections
168         for section in self.DEFAULTS.keys():
169             if section != "common":
170                 getattr(self, section).update(self.common)
171
172         # check and normalize the scheme of proxy url
173         if self.create['proxy']:
174             m = re.match('^(\w+)://.*', self.create['proxy'])
175             if m:
176                 scheme = m.group(1)
177                 if scheme not in ('http', 'https', 'ftp', 'socks'):
178                     raise errors.ConfigError("%s: proxy scheme is incorrect" % siteconf)
179             else:
180                 msger.warning("%s: proxy url w/o scheme, use http as default"
181                               % siteconf)
182                 self.create['proxy'] = "http://" + self.create['proxy']
183
184         proxy.set_proxies(self.create['proxy'], self.create['no_proxy'])
185
186         # bootstrap option handling
187         self.set_runtime(self.create['runtime'])
188         if isinstance(self.bootstrap['packages'], basestring):
189             packages = self.bootstrap['packages'].replace('\n', ' ')
190             if packages.find(',') != -1:
191                 packages = packages.split(',')
192             else:
193                 packages = packages.split()
194             self.bootstrap['packages'] = packages
195
196     def _parse_kickstart(self, ksconf=None):
197         if not ksconf:
198             return
199
200         ksconf = misc.normalize_ksfile(ksconf,
201                                        self.create['release'],
202                                        self.create['arch'])
203
204         ks = kickstart.read_kickstart(ksconf)
205
206         self.create['ks'] = ks
207         self.create['name'] = os.path.splitext(os.path.basename(ksconf))[0]
208
209         self.create['name'] = misc.build_name(ksconf,
210                                               self.create['release'],
211                                               self.create['name_prefix'],
212                                               self.create['name_suffix'])
213
214         self.create['destdir'] = self.create['outdir']
215         if self.create['release'] is not None:
216             self.create['destdir'] = "%s/%s/images/%s/" % (self.create['outdir'],
217                                                            self.create['release'],
218                                                            self.create['name'])
219             self.create['name'] = self.create['release'] + '_' + self.create['name']
220
221             if not self.create['logfile']:
222                 self.create['logfile'] = os.path.join(self.create['destdir'],
223                                                       self.create['name'] + ".log")
224                 self.create['releaselog'] = True
225                 self.set_logfile()
226
227         msger.info("Retrieving repo metadata:")
228         ksrepos = kickstart.get_repos(ks,
229                                       self.create['extrarepos'],
230                                       self.create['ignore_ksrepo'])
231         if not ksrepos:
232             raise errors.KsError('no valid repos found in ks file')
233
234         for repo in ksrepos:
235             if hasattr(repo, 'baseurl') and repo.baseurl.startswith("file:"):
236                 repourl = repo.baseurl.replace('file:', '')
237                 repourl = "/%s" % repourl.lstrip('/')
238                 self.create['localrepos'].append(repourl)
239
240         self.create['repomd'] = misc.get_metadata_from_repos(
241                                                     ksrepos,
242                                                     self.create['cachedir'])
243         msger.raw(" DONE")
244
245         target_archlist, archlist = misc.get_arch(self.create['repomd'])
246         if self.create['arch']:
247             if self.create['arch'] not in archlist:
248                 raise errors.ConfigError("Invalid arch %s for repository. "
249                                   "Valid arches: %s" \
250                                   % (self.create['arch'], ', '.join(archlist)))
251         else:
252             if len(target_archlist) == 1:
253                 self.create['arch'] = str(target_archlist[0])
254                 msger.info("Use detected arch %s." % target_archlist[0])
255             else:
256                 raise errors.ConfigError("Please specify a valid arch, "
257                                          "the choice can be: %s" \
258                                          % ', '.join(archlist))
259
260         kickstart.resolve_groups(self.create, self.create['repomd'])
261
262         # check selinux, it will block arm and btrfs image creation
263         misc.selinux_check(self.create['arch'],
264                            [p.fstype for p in ks.handler.partition.partitions])
265
266     def set_logfile(self, logfile = None):
267         if not logfile:
268             logfile = self.create['logfile']
269
270         logfile_dir = os.path.dirname(self.create['logfile'])
271         if not os.path.exists(logfile_dir):
272             os.makedirs(logfile_dir)
273         msger.set_interactive(False)
274         if inbootstrap():
275             mode = 'a'
276         else:
277             mode = 'w'
278         msger.set_logfile(self.create['logfile'], mode)
279
280     def set_runtime(self, runtime):
281         if runtime != "bootstrap":
282             raise errors.CreatorError("Invalid runtime mode: %s, only 'bootstrap' mode is allowed." % runtime)
283
284         if misc.get_distro()[0] in ("tizen", "Tizen"):
285             runtime = "native"
286         self.create['runtime'] = runtime
287
288 configmgr = ConfigMgr()