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