4146bcae205bd4253695d2df6e8a17353774b694
[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:
231                 print "!!! catalyst: Python modules not found in "+\
232                         module_dir + "; exiting."
233                 sys.exit(1)
234
235         return targetmap
236
237 def build_target(addlargs, targetmap):
238         try:
239                 if addlargs["target"] not in targetmap:
240                         raise CatalystError,"Target \""+addlargs["target"]+"\" not available."
241
242                 mytarget=targetmap[addlargs["target"]](conf_values, addlargs)
243
244                 mytarget.run()
245
246         except:
247                 catalyst.util.print_traceback()
248                 print "!!! catalyst: Error encountered during run of target " + addlargs["target"]
249                 sys.exit(1)
250
251 def main():
252         targetmap={}
253
254         version()
255         if os.getuid() != 0:
256                 # catalyst cannot be run as a normal user due to chroots, mounts, etc
257                 print "!!! catalyst: This script requires root privileges to operate"
258                 sys.exit(2)
259
260         # we need some options in order to work correctly
261         if len(sys.argv) < 2:
262                 usage()
263                 sys.exit(2)
264
265         # parse out the command line arguments
266         try:
267                 opts,args = getopt.getopt(sys.argv[1:], "apPThvdc:C:f:FVs:", ["purge", "purgeonly", "purgetmponly", "help", "version", "debug",\
268                         "clear-autoresume", "config=", "cli=", "file=", "fetch", "verbose","snapshot="])
269
270         except getopt.GetoptError:
271                 usage()
272                 sys.exit(2)
273
274         # defaults for commandline opts
275         debug=False
276         verbose=False
277         fetch=False
278         myconfig=""
279         myspecfile=""
280         mycmdline=[]
281         myopts=[]
282
283         # check preconditions
284         if len(opts) == 0:
285                 print "!!! catalyst: please specify one of either -f or -C\n"
286                 usage()
287                 sys.exit(2)
288
289         run = False
290         for o, a in opts:
291                 if o in ("-h", "--help"):
292                         usage()
293                         sys.exit(1)
294
295                 if o in ("-V", "--version"):
296                         print "Catalyst version "+__version__
297                         sys.exit(1)
298
299                 if o in ("-d", "--debug"):
300                         conf_values["DEBUG"]="1"
301                         conf_values["VERBOSE"]="1"
302
303                 if o in ("-c", "--config"):
304                         myconfig=a
305
306                 if o in ("-C", "--cli"):
307                         run = True
308                         x=sys.argv.index(o)+1
309                         while x < len(sys.argv):
310                                 mycmdline.append(sys.argv[x])
311                                 x=x+1
312
313                 if o in ("-f", "--file"):
314                         run = True
315                         myspecfile=a
316
317                 if o in ("-F", "--fetchonly"):
318                         conf_values["FETCH"]="1"
319
320                 if o in ("-v", "--verbose"):
321                         conf_values["VERBOSE"]="1"
322
323                 if o in ("-s", "--snapshot"):
324                         if len(sys.argv) < 3:
325                                 print "!!! catalyst: missing snapshot identifier\n"
326                                 usage()
327                                 sys.exit(2)
328                         else:
329                                 run = True
330                                 mycmdline.append("target=snapshot")
331                                 mycmdline.append("version_stamp="+a)
332
333                 if o in ("-p", "--purge"):
334                         conf_values["PURGE"] = "1"
335
336                 if o in ("-P", "--purgeonly"):
337                         conf_values["PURGEONLY"] = "1"
338
339                 if o in ("-T", "--purgetmponly"):
340                         conf_values["PURGETMPONLY"] = "1"
341
342                 if o in ("-a", "--clear-autoresume"):
343                         conf_values["CLEAR_AUTORESUME"] = "1"
344
345         if not run:
346                 print "!!! catalyst: please specify one of either -f or -C\n"
347                 usage()
348                 sys.exit(2)
349
350         # import configuration file and import our main module using those settings
351         parse_config(myconfig)
352
353         # initialize our contents generator
354         contents_map = ContentsMap(CONTENTS_DEFINITIONS)
355         conf_values["contents_map"] = contents_map
356
357         # initialze our hash and contents generators
358         hash_map = HashMap(HASH_DEFINITIONS)
359         conf_values["hash_map"] = hash_map
360
361         # Start checking that digests are valid now that hash_map is initialized
362         if "digests" in conf_values:
363                 for i in conf_values["digests"].split():
364                         if i not in HASH_DEFINITIONS:
365                                 print
366                                 print i+" is not a valid digest entry"
367                                 print "Valid digest entries:"
368                                 print HASH_DEFINITIONS.keys()
369                                 print
370                                 print "Catalyst aborting...."
371                                 sys.exit(2)
372                         if find_binary(hash_map.hash_map[i].cmd) == None:
373                                 print
374                                 print "digest=" + i
375                                 print "\tThe " + hash_map.hash_map[i].cmd + \
376                                         " binary was not found. It needs to be in your system path"
377                                 print
378                                 print "Catalyst aborting...."
379                                 sys.exit(2)
380         if "hash_function" in conf_values:
381                 if conf_values["hash_function"] not in HASH_DEFINITIONS:
382                         print
383                         print conf_values["hash_function"]+\
384                                 " is not a valid hash_function entry"
385                         print "Valid hash_function entries:"
386                         print HASH_DEFINITIONS.keys()
387                         print
388                         print "Catalyst aborting...."
389                         sys.exit(2)
390                 if find_binary(hash_map.hash_map[conf_values["hash_function"]].cmd) == None:
391                         print
392                         print "hash_function="+conf_values["hash_function"]
393                         print "\tThe "+hash_map.hash_map[conf_values["hash_function"]].cmd + \
394                                 " binary was not found. It needs to be in your system path"
395                         print
396                         print "Catalyst aborting...."
397                         sys.exit(2)
398
399         # import the rest of the catalyst modules
400         targetmap=import_modules()
401
402         addlargs={}
403
404         if myspecfile:
405                 spec = catalyst.config.SpecParser(myspecfile)
406                 addlargs.update(spec.get_values())
407
408         if mycmdline:
409                 try:
410                         cmdline = catalyst.config.ConfigParser()
411                         cmdline.parse_lines(mycmdline)
412                         addlargs.update(cmdline.get_values())
413                 except CatalystError:
414                         print "!!! catalyst: Could not parse commandline, exiting."
415                         sys.exit(1)
416
417         if "target" not in addlargs:
418                 raise CatalystError, "Required value \"target\" not specified."
419
420         # everything is setup, so the build is a go
421         try:
422                 build_target(addlargs, targetmap)
423
424         except CatalystError:
425                 print
426                 print "Catalyst aborting...."
427                 sys.exit(2)
428         except KeyboardInterrupt:
429                 print "\nCatalyst build aborted due to user interrupt ( Ctrl-C )"
430                 print
431                 print "Catalyst aborting...."
432                 sys.exit(2)
433         except LockInUse:
434                 print "Catalyst aborting...."
435                 sys.exit(2)
436         except:
437                 print "Catalyst aborting...."
438                 raise
439                 sys.exit(2)