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