main.py: print the output of an ImportError to help in debugging.
[catalyst.git] / catalyst / main.py
1
2 # Maintained in full by:
3 # Catalyst Team <catalyst@gentoo.org>
4 # Release Engineering Team <releng@gentoo.org>
5 # Andrew Gaffney <agaffney@gentoo.org>
6 # Chris Gianelloni <wolf31o2@wolf31o2.org>
7 # $Id$
8
9 import os
10 import sys
11 import imp
12 import string
13 import getopt
14 import pdb
15 import os.path
16
17 __selfpath__ = os.path.abspath(os.path.dirname(__file__))
18
19 sys.path.append(__selfpath__ + "/modules")
20
21 from . import __version__
22 import catalyst.config
23 import catalyst.util
24 from catalyst.support import (required_build_targets,
25         valid_build_targets, CatalystError, find_binary, LockInUse)
26
27 from hash_utils import HashMap, HASH_DEFINITIONS
28 from contents import ContentsMap, CONTENTS_DEFINITIONS
29
30
31
32 conf_values={}
33
34 def usage():
35         print """Usage catalyst [options] [-C variable=value...] [ -s identifier]
36  -a --clear-autoresume  clear autoresume flags
37  -c --config            use specified configuration file
38  -C --cli               catalyst commandline (MUST BE LAST OPTION)
39  -d --debug             enable debugging
40  -f --file              read specfile
41  -F --fetchonly         fetch files only
42  -h --help              print this help message
43  -p --purge             clear tmp dirs,package cache, autoresume flags
44  -P --purgeonly         clear tmp dirs,package cache, autoresume flags and exit
45  -T --purgetmponly      clear tmp dirs and autoresume flags and exit
46  -s --snapshot          generate a release snapshot
47  -V --version           display version information
48  -v --verbose           verbose output
49
50 Usage examples:
51
52 Using the commandline option (-C, --cli) to build a Portage snapshot:
53 catalyst -C target=snapshot version_stamp=my_date
54
55 Using the snapshot option (-s, --snapshot) to build a release snapshot:
56 catalyst -s 20071121"
57
58 Using the specfile option (-f, --file) to build a stage target:
59 catalyst -f stage1-specfile.spec
60 """
61
62
63 def version():
64         print "Catalyst, version "+__version__
65         print "Copyright 2003-2008 Gentoo Foundation"
66         print "Copyright 2008-2012 various authors"
67         print "Distributed under the GNU General Public License version 2.1\n"
68
69 def parse_config(myconfig):
70         # search a couple of different areas for the main config file
71         myconf={}
72         config_file=""
73
74         confdefaults = {
75                 "distdir": "/usr/portage/distfiles",
76                 "hash_function": "crc32",
77                 "icecream": "/var/cache/icecream",
78                 "local_overlay": "/usr/local/portage",
79                 "options": "",
80                 "packagedir": "/usr/portage/packages",
81                 "portdir": "/usr/portage",
82                 "repo_name": "portage",
83                 "sharedir": "/usr/share/catalyst",
84                 "snapshot_name": "portage-",
85                 "snapshot_cache": "/var/tmp/catalyst/snapshot_cache",
86                 "storedir": "/var/tmp/catalyst",
87                 }
88
89         # first, try the one passed (presumably from the cmdline)
90         if myconfig:
91                 if os.path.exists(myconfig):
92                         print "Using command line specified Catalyst configuration file, "+myconfig
93                         config_file=myconfig
94
95                 else:
96                         print "!!! catalyst: Could not use specified configuration file "+\
97                                 myconfig
98                         sys.exit(1)
99
100         # next, try the default location
101         elif os.path.exists("/etc/catalyst/catalyst.conf"):
102                 print "Using default Catalyst configuration file, /etc/catalyst/catalyst.conf"
103                 config_file="/etc/catalyst/catalyst.conf"
104
105         # can't find a config file (we are screwed), so bail out
106         else:
107                 print "!!! catalyst: Could not find a suitable configuration file"
108                 sys.exit(1)
109
110         # now, try and parse the config file "config_file"
111         try:
112 #               execfile(config_file, myconf, myconf)
113                 myconfig = catalyst.config.ConfigParser(config_file)
114                 myconf.update(myconfig.get_values())
115
116         except:
117                 print "!!! catalyst: Unable to parse configuration file, "+myconfig
118                 sys.exit(1)
119
120         # now, load up the values into conf_values so that we can use them
121         for x in confdefaults.keys():
122                 if x in myconf:
123                         print "Setting",x,"to config file value \""+myconf[x]+"\""
124                         conf_values[x]=myconf[x]
125                 else:
126                         print "Setting",x,"to default value \""+confdefaults[x]+"\""
127                         conf_values[x]=confdefaults[x]
128
129         # add our python base directory to use for loading target arch's
130         conf_values["PythonDir"] = __selfpath__
131
132         # parse out the rest of the options from the config file
133         if "autoresume" in string.split(conf_values["options"]):
134                 print "Autoresuming support enabled."
135                 conf_values["AUTORESUME"]="1"
136
137         if "bindist" in string.split(conf_values["options"]):
138                 print "Binary redistribution enabled"
139                 conf_values["BINDIST"]="1"
140         else:
141                 print "Bindist is not enabled in catalyst.conf"
142                 print "Binary redistribution of generated stages/isos may be prohibited by law."
143                 print "Please see the use description for bindist on any package you are including."
144
145         if "ccache" in string.split(conf_values["options"]):
146                 print "Compiler cache support enabled."
147                 conf_values["CCACHE"]="1"
148
149         if "clear-autoresume" in string.split(conf_values["options"]):
150                 print "Cleaning autoresume flags support enabled."
151                 conf_values["CLEAR_AUTORESUME"]="1"
152
153         if "distcc" in string.split(conf_values["options"]):
154                 print "Distcc support enabled."
155                 conf_values["DISTCC"]="1"
156
157         if "icecream" in string.split(conf_values["options"]):
158                 print "Icecream compiler cluster support enabled."
159                 conf_values["ICECREAM"]="1"
160
161         if "kerncache" in string.split(conf_values["options"]):
162                 print "Kernel cache support enabled."
163                 conf_values["KERNCACHE"]="1"
164
165         if "pkgcache" in string.split(conf_values["options"]):
166                 print "Package cache support enabled."
167                 conf_values["PKGCACHE"]="1"
168
169         if "preserve_libs" in string.split(conf_values["options"]):
170                 print "Preserving libs during unmerge."
171                 conf_values["PRESERVE_LIBS"]="1"
172
173         if "purge" in string.split(conf_values["options"]):
174                 print "Purge support enabled."
175                 conf_values["PURGE"]="1"
176
177         if "seedcache" in string.split(conf_values["options"]):
178                 print "Seed cache support enabled."
179                 conf_values["SEEDCACHE"]="1"
180
181         if "snapcache" in string.split(conf_values["options"]):
182                 print "Snapshot cache support enabled."
183                 conf_values["SNAPCACHE"]="1"
184
185         if "digests" in myconf:
186                 conf_values["digests"]=myconf["digests"]
187         if "contents" in myconf:
188                 # replace '-' with '_' (for compatibility with existing configs)
189                 conf_values["contents"] = myconf["contents"].replace("-", '_')
190
191         if "envscript" in myconf:
192                 print "Envscript support enabled."
193                 conf_values["ENVSCRIPT"]=myconf["envscript"]
194
195         if "var_tmpfs_portage" in myconf:
196                 conf_values["var_tmpfs_portage"]=myconf["var_tmpfs_portage"];
197
198         if "port_logdir" in myconf:
199                 conf_values["port_logdir"]=myconf["port_logdir"];
200
201 def import_modules():
202         # import catalyst's own modules
203         # (i.e. stage and the arch modules)
204         targetmap={}
205
206         try:
207                 module_dir = __selfpath__ + "/targets/"
208                 for x in required_build_targets:
209                         try:
210                                 fh=open(module_dir + x + ".py")
211                                 module=imp.load_module(x, fh,"targets/" + x + ".py",
212                                         (".py", "r", imp.PY_SOURCE))
213                                 fh.close()
214
215                         except IOError:
216                                 raise CatalystError, "Can't find " + x + ".py plugin in " + \
217                                         module_dir
218                 for x in valid_build_targets:
219                         try:
220                                 fh=open(module_dir + x + ".py")
221                                 module=imp.load_module(x, fh, "targets/" + x + ".py",
222                                         (".py", "r", imp.PY_SOURCE))
223                                 module.register(targetmap)
224                                 fh.close()
225
226                         except IOError:
227                                 raise CatalystError,"Can't find " + x + ".py plugin in " + \
228                                         module_dir
229
230         except ImportError as e:
231                 print "!!! catalyst: Python modules not found in "+\
232                         module_dir + "; exiting."
233                 print e
234                 sys.exit(1)
235
236         return targetmap
237
238 def build_target(addlargs, targetmap):
239         try:
240                 if addlargs["target"] not in targetmap:
241                         raise CatalystError,"Target \""+addlargs["target"]+"\" not available."
242
243                 mytarget=targetmap[addlargs["target"]](conf_values, addlargs)
244
245                 mytarget.run()
246
247         except:
248                 catalyst.util.print_traceback()
249                 print "!!! catalyst: Error encountered during run of target " + addlargs["target"]
250                 sys.exit(1)
251
252 def main():
253         targetmap={}
254
255         version()
256         if os.getuid() != 0:
257                 # catalyst cannot be run as a normal user due to chroots, mounts, etc
258                 print "!!! catalyst: This script requires root privileges to operate"
259                 sys.exit(2)
260
261         # we need some options in order to work correctly
262         if len(sys.argv) < 2:
263                 usage()
264                 sys.exit(2)
265
266         # parse out the command line arguments
267         try:
268                 opts,args = getopt.getopt(sys.argv[1:], "apPThvdc:C:f:FVs:", ["purge", "purgeonly", "purgetmponly", "help", "version", "debug",\
269                         "clear-autoresume", "config=", "cli=", "file=", "fetch", "verbose","snapshot="])
270
271         except getopt.GetoptError:
272                 usage()
273                 sys.exit(2)
274
275         # defaults for commandline opts
276         debug=False
277         verbose=False
278         fetch=False
279         myconfig=""
280         myspecfile=""
281         mycmdline=[]
282         myopts=[]
283
284         # check preconditions
285         if len(opts) == 0:
286                 print "!!! catalyst: please specify one of either -f or -C\n"
287                 usage()
288                 sys.exit(2)
289
290         run = False
291         for o, a in opts:
292                 if o in ("-h", "--help"):
293                         usage()
294                         sys.exit(1)
295
296                 if o in ("-V", "--version"):
297                         print "Catalyst version "+__version__
298                         sys.exit(1)
299
300                 if o in ("-d", "--debug"):
301                         conf_values["DEBUG"]="1"
302                         conf_values["VERBOSE"]="1"
303
304                 if o in ("-c", "--config"):
305                         myconfig=a
306
307                 if o in ("-C", "--cli"):
308                         run = True
309                         x=sys.argv.index(o)+1
310                         while x < len(sys.argv):
311                                 mycmdline.append(sys.argv[x])
312                                 x=x+1
313
314                 if o in ("-f", "--file"):
315                         run = True
316                         myspecfile=a
317
318                 if o in ("-F", "--fetchonly"):
319                         conf_values["FETCH"]="1"
320
321                 if o in ("-v", "--verbose"):
322                         conf_values["VERBOSE"]="1"
323
324                 if o in ("-s", "--snapshot"):
325                         if len(sys.argv) < 3:
326                                 print "!!! catalyst: missing snapshot identifier\n"
327                                 usage()
328                                 sys.exit(2)
329                         else:
330                                 run = True
331                                 mycmdline.append("target=snapshot")
332                                 mycmdline.append("version_stamp="+a)
333
334                 if o in ("-p", "--purge"):
335                         conf_values["PURGE"] = "1"
336
337                 if o in ("-P", "--purgeonly"):
338                         conf_values["PURGEONLY"] = "1"
339
340                 if o in ("-T", "--purgetmponly"):
341                         conf_values["PURGETMPONLY"] = "1"
342
343                 if o in ("-a", "--clear-autoresume"):
344                         conf_values["CLEAR_AUTORESUME"] = "1"
345
346         if not run:
347                 print "!!! catalyst: please specify one of either -f or -C\n"
348                 usage()
349                 sys.exit(2)
350
351         # import configuration file and import our main module using those settings
352         parse_config(myconfig)
353
354         # initialize our contents generator
355         contents_map = ContentsMap(CONTENTS_DEFINITIONS)
356         conf_values["contents_map"] = contents_map
357
358         # initialze our hash and contents generators
359         hash_map = HashMap(HASH_DEFINITIONS)
360         conf_values["hash_map"] = hash_map
361
362         # Start checking that digests are valid now that hash_map is initialized
363         if "digests" in conf_values:
364                 for i in conf_values["digests"].split():
365                         if i not in HASH_DEFINITIONS:
366                                 print
367                                 print i+" is not a valid digest entry"
368                                 print "Valid digest entries:"
369                                 print HASH_DEFINITIONS.keys()
370                                 print
371                                 print "Catalyst aborting...."
372                                 sys.exit(2)
373                         if find_binary(hash_map.hash_map[i].cmd) == None:
374                                 print
375                                 print "digest=" + i
376                                 print "\tThe " + hash_map.hash_map[i].cmd + \
377                                         " binary was not found. It needs to be in your system path"
378                                 print
379                                 print "Catalyst aborting...."
380                                 sys.exit(2)
381         if "hash_function" in conf_values:
382                 if conf_values["hash_function"] not in HASH_DEFINITIONS:
383                         print
384                         print conf_values["hash_function"]+\
385                                 " is not a valid hash_function entry"
386                         print "Valid hash_function entries:"
387                         print HASH_DEFINITIONS.keys()
388                         print
389                         print "Catalyst aborting...."
390                         sys.exit(2)
391                 if find_binary(hash_map.hash_map[conf_values["hash_function"]].cmd) == None:
392                         print
393                         print "hash_function="+conf_values["hash_function"]
394                         print "\tThe "+hash_map.hash_map[conf_values["hash_function"]].cmd + \
395                                 " binary was not found. It needs to be in your system path"
396                         print
397                         print "Catalyst aborting...."
398                         sys.exit(2)
399
400         # import the rest of the catalyst modules
401         targetmap=import_modules()
402
403         addlargs={}
404
405         if myspecfile:
406                 spec = catalyst.config.SpecParser(myspecfile)
407                 addlargs.update(spec.get_values())
408
409         if mycmdline:
410                 try:
411                         cmdline = catalyst.config.ConfigParser()
412                         cmdline.parse_lines(mycmdline)
413                         addlargs.update(cmdline.get_values())
414                 except CatalystError:
415                         print "!!! catalyst: Could not parse commandline, exiting."
416                         sys.exit(1)
417
418         if "target" not in addlargs:
419                 raise CatalystError, "Required value \"target\" not specified."
420
421         # everything is setup, so the build is a go
422         try:
423                 build_target(addlargs, targetmap)
424
425         except CatalystError:
426                 print
427                 print "Catalyst aborting...."
428                 sys.exit(2)
429         except KeyboardInterrupt:
430                 print "\nCatalyst build aborted due to user interrupt ( Ctrl-C )"
431                 print
432                 print "Catalyst aborting...."
433                 sys.exit(2)
434         except LockInUse:
435                 print "Catalyst aborting...."
436                 sys.exit(2)
437         except:
438                 print "Catalyst aborting...."
439                 raise
440                 sys.exit(2)