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