s:/etc/make.profile:/etc/portage/make.profile:g - Use new location
[catalyst.git] / catalyst
1 #!/usr/bin/python -OO
2
3 # Maintained in full by:
4 # Andrew Gaffney <agaffney@gentoo.org>
5 # Chris Gianelloni <wolf31o2@wolf31o2.org>
6 # $Id$
7
8 import os, sys, imp, string, getopt
9 import pdb
10 import os.path
11
12 __selfpath__ = os.path.abspath(os.path.dirname(__file__))
13
14 sys.path.append(__selfpath__ + "/modules")
15
16 import catalyst.config
17 import catalyst.util
18
19 __maintainer__="Chris Gianelloni <wolf31o2@wolf31o2.org>"
20 __version__="2.0.7.1"
21
22 conf_values={}
23
24 def usage():
25         print "Usage catalyst [options] [-C variable=value...] [ -s identifier]"
26         print " -a --clear-autoresume   clear autoresume flags"
27         print " -c --config     use specified configuration file"
28         print " -C --cli        catalyst commandline (MUST BE LAST OPTION)"
29         print " -d --debug      enable debugging"
30         print " -f --file       read specfile"
31         print " -F --fetchonly  fetch files only"
32         print " -h --help       print this help message"
33         print " -p --purge      clear tmp dirs,package cache and autoresume flags"
34         print " -P --purgeonly  clear tmp dirs,package cache and autoresume flags and exit"
35         print " -T --purgetmponly  clear tmp dirs 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 version():
52         print "Catalyst, version "+__version__
53         print "Copyright 2003-2008 Gentoo Foundation"
54         print "Copyright 2008-2011 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 "tarball" in string.split(conf_values["options"]):
154 #               print "Tarball creation enabled."
155 #               conf_values["TARBALL"]="1"
156
157         if myconf.has_key("digests"):
158                 conf_values["digests"]=myconf["digests"]
159         if myconf.has_key("contents"):
160                 conf_values["contents"]=myconf["contents"]
161
162         if myconf.has_key("envscript"):
163                 print "Envscript support enabled."
164                 conf_values["ENVSCRIPT"]=myconf["envscript"]
165
166 def import_modules():
167         # import catalyst's own modules (i.e. catalyst_support and the arch modules)
168         targetmap={}
169
170         try:
171                 for x in required_build_targets:
172                         try:
173                                 fh=open(conf_values["sharedir"]+"/modules/"+x+".py")
174                                 module=imp.load_module(x,fh,"modules/"+x+".py",(".py","r",imp.PY_SOURCE))
175                                 fh.close()
176
177                         except IOError:
178                                 raise CatalystError,"Can't find "+x+".py plugin in "+\
179                                         conf_values["sharedir"]+"/modules/"
180
181                 for x in valid_build_targets:
182                         try:
183                                 fh=open(conf_values["sharedir"]+"/modules/"+x+".py")
184                                 module=imp.load_module(x,fh,"modules/"+x+".py",(".py","r",imp.PY_SOURCE))
185                                 module.register(targetmap)
186                                 fh.close()
187
188                         except IOError:
189                                 raise CatalystError,"Can't find "+x+".py plugin in "+\
190                                         conf_values["sharedir"]+"/modules/"
191
192         except ImportError:
193                 print "!!! catalyst: Python modules not found in "+\
194                         conf_values["sharedir"]+"/modules; exiting."
195                 sys.exit(1)
196
197         return targetmap
198
199 def build_target(addlargs, targetmap):
200         try:
201                 if not targetmap.has_key(addlargs["target"]):
202                         raise CatalystError,"Target \""+addlargs["target"]+"\" not available."
203                 
204                 mytarget=targetmap[addlargs["target"]](conf_values, addlargs)
205         
206                 mytarget.run()
207
208         except:
209                 catalyst.util.print_traceback()
210                 print "!!! catalyst: Error encountered during run of target " + addlargs["target"]
211                 sys.exit(1)
212
213 if __name__ == "__main__":
214         targetmap={}
215         
216         version()
217         if os.getuid() != 0:
218                 # catalyst cannot be run as a normal user due to chroots, mounts, etc
219                 print "!!! catalyst: This script requires root privileges to operate"
220                 sys.exit(2)
221
222         # we need some options in order to work correctly
223         if len(sys.argv) < 2:
224                 usage()
225                 sys.exit(2)
226
227         # parse out the command line arguments
228         try:
229                 opts,args = getopt.getopt(sys.argv[1:], "apPThvdc:C:f:FVs:", ["purge", "purgeonly", "purgetmponly", "help", "version", "debug",\
230                         "clear-autoresume", "config=", "cli=", "file=", "fetch", "verbose","snapshot="])
231         
232         except getopt.GetoptError:
233                 usage()
234                 sys.exit(2)
235         
236         # defaults for commandline opts
237         debug=False
238         verbose=False
239         fetch=False
240         myconfig=""
241         myspecfile=""
242         mycmdline=[]
243         myopts=[]
244
245         # check preconditions
246         if len(opts) == 0:
247                 print "!!! catalyst: please specify one of either -f or -C\n"
248                 usage()
249                 sys.exit(2)
250
251         run = False
252         for o, a in opts:
253                 if o in ("-h", "--help"):
254                         usage()
255                         sys.exit(1)
256                 
257                 if o in ("-V", "--version"):
258                         print "Catalyst version "+__version__
259                         sys.exit(1)
260
261                 if o in ("-d", "--debug"):
262                         conf_values["DEBUG"]="1"
263                         conf_values["VERBOSE"]="1"
264
265                 if o in ("-c", "--config"):
266                         myconfig=a
267
268                 if o in ("-C", "--cli"):
269                         run = True
270                         x=sys.argv.index(o)+1
271                         while x < len(sys.argv):
272                                 mycmdline.append(sys.argv[x])
273                                 x=x+1
274                         
275                 if o in ("-f", "--file"):
276                         run = True
277                         myspecfile=a
278
279                 if o in ("-F", "--fetchonly"):
280                         conf_values["FETCH"]="1"
281                         
282                 if o in ("-v", "--verbose"):
283                         conf_values["VERBOSE"]="1"
284
285                 if o in ("-s", "--snapshot"):
286                         if len(sys.argv) < 3:
287                                 print "!!! catalyst: missing snapshot identifier\n"
288                                 usage()
289                                 sys.exit(2)
290                         else:
291                                 run = True
292                                 mycmdline.append("target=snapshot")
293                                 mycmdline.append("version_stamp="+a)
294                 
295                 if o in ("-p", "--purge"):
296                         conf_values["PURGE"] = "1"
297
298                 if o in ("-P", "--purgeonly"):
299                         conf_values["PURGEONLY"] = "1"
300
301                 if o in ("-T", "--purgetmponly"):
302                         conf_values["PURGETMPONLY"] = "1"
303
304                 if o in ("-a", "--clear-autoresume"):
305                         conf_values["CLEAR_AUTORESUME"] = "1"
306
307         if not run:
308                 print "!!! catalyst: please specify one of either -f or -C\n"
309                 usage()
310                 sys.exit(2)
311
312         # import configuration file and import our main module using those settings
313         parse_config(myconfig)
314         sys.path.append(conf_values["sharedir"]+"/modules")
315         from catalyst_support import *
316         
317         # Start checking that digests are valid now that the hash_map was imported
318         # from catalyst_support
319         if conf_values.has_key("digests"):
320                 for i in conf_values["digests"].split():
321                         if not hash_map.has_key(i):
322                                 print
323                                 print i+" is not a valid digest entry"
324                                 print "Valid digest entries:"
325                                 print hash_map.keys()
326                                 print
327                                 print "Catalyst aborting...."
328                                 sys.exit(2)
329                         if find_binary(hash_map[i][1]) == None:
330                                 print
331                                 print "digest="+i
332                                 print "\tThe "+hash_map[i][1]+\
333                                         " binary was not found. It needs to be in your system path"
334                                 print
335                                 print "Catalyst aborting...."
336                                 sys.exit(2)
337         if conf_values.has_key("hash_function"):
338                 if not hash_map.has_key(conf_values["hash_function"]):
339                         print
340                         print conf_values["hash_function"]+\
341                                 " is not a valid hash_function entry"
342                         print "Valid hash_function entries:"
343                         print hash_map.keys()
344                         print
345                         print "Catalyst aborting...."
346                         sys.exit(2)
347                 if find_binary(hash_map[conf_values["hash_function"]][1]) == None:
348                         print
349                         print "hash_function="+conf_values["hash_function"]
350                         print "\tThe "+hash_map[conf_values["hash_function"]][1]+\
351                                 " binary was not found. It needs to be in your system path"
352                         print
353                         print "Catalyst aborting...."
354                         sys.exit(2)
355
356         # import the rest of the catalyst modules
357         targetmap=import_modules()
358
359         addlargs={}
360         
361         if myspecfile:
362                 spec = catalyst.config.SpecParser(myspecfile)
363                 addlargs.update(spec.get_values())
364         
365         if mycmdline:
366                 try:
367                         cmdline = catalyst.config.ConfigParser()
368                         cmdline.parse_lines(mycmdline)
369                         addlargs.update(cmdline.get_values())
370                 except CatalystError:
371                         print "!!! catalyst: Could not parse commandline, exiting."
372                         sys.exit(1)
373
374         if not addlargs.has_key("target"):
375                 raise CatalystError, "Required value \"target\" not specified."
376
377         # everything is setup, so the build is a go
378         try:
379                 build_target(addlargs, targetmap)
380                         
381         except CatalystError:
382                 print
383                 print "Catalyst aborting...."
384                 sys.exit(2)
385         except KeyboardInterrupt:
386                 print "\nCatalyst build aborted due to user interrupt ( Ctrl-C )"
387                 print
388                 print "Catalyst aborting...."
389                 sys.exit(2)
390         except LockInUse:
391                 print "Catalyst aborting...."
392                 sys.exit(2)
393         except:
394                 print "Catalyst aborting...."
395                 raise
396                 sys.exit(2)
397
398         #except CatalystError:
399         #       print
400         #       print "Catalyst aborting...."
401         #       sys.exit(2)
402         #except KeyError:
403         #       print "\nproblem with command line or spec file ( Key Error )"
404         #       print "Key: "+str(sys.exc_value)+" was not found"
405         #       print "Catalyst aborting...."
406         #       sys.exit(2)
407         #except UnboundLocalError:
408         #       print
409         #       print "UnboundLocalError: "+str(sys.exc_value)+" was not found"
410         #       raise
411         #       print
412         #       print "Catalyst aborting...."
413         #       sys.exit(2)