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