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