[cvs] / gkb / gkb.py  

cvs: gkb/gkb.py


1 : tmcnulty 1.1 #!/usr/bin/python
2 :     #
3 :     # GKB - GNU Kernel Builder
4 : tmcnulty 1.2 # Copyright (C) 2003-2004 Tobias McNulty, Mark Guertin
5 : tmcnulty 1.1 #
6 :     # This program is free software; you can redistribute it and/or modify
7 :     # it under the terms of the GNU General Public License as published by
8 :     # the Free Software Foundation; either version 2 of the License, or
9 :     # (at your option) any later version.
10 :     #
11 :     # This program is distributed in the hope that it will be useful,
12 :     # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 :     # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 :     # GNU General Public License for more details.
15 :     #
16 :     # You should have received a copy of the GNU General Public License
17 :     # along with this program; if not, write to the Free Software
18 :     # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 :     #
20 :     # Ported from PHP version Copyright (c) Tobias McNulty 2000-2003
21 :    
22 :     import sys, os, ConfigParser
23 :     import xml.parsers.expat
24 :     import md5
25 :     from ftplib import FTP
26 :     from commands import getoutput
27 :     from shutil import copy, move
28 :     from string import split
29 :     from urllib2 import urlopen
30 :     from ClientForm import ParseResponse
31 :    
32 :     debug=0
33 : tmcnulty 1.10 clean=0
34 :     dont_build=1
35 : tmcnulty 1.1 verbose=1
36 :    
37 :     # parse host-specific configuration information from gkb.cfg
38 :     config = ConfigParser.ConfigParser()
39 :     config.readfp(open('gkb-host.cfg'))
40 :     buildroot=config.get("options","buildroot")
41 :     host=config.get("options","host")
42 :     passwd=config.get("options","passwd")
43 :    
44 :     # this one is passed verbatim before the make command. might be useful for alternate toolchains, etc
45 :     # example: premake="HOST=powerpc-unknown-linux-gnu"
46 :     premake=config.get("options","premake")
47 :     # make options, passed verbatim after make command
48 :     makeopts=config.get("options","makeopts")
49 :    
50 :     # parse manager-related configuration from gkb-manager.cfg
51 :     config.readfp(open('gkb-manager.cfg'))
52 :     msite=config.get('options','msite')
53 :    
54 :     # these values will likely stay fairly static across different builds
55 :     patchdir="%s/patches" % buildroot # full path to patch file dir
56 :     configdir="%s/configs" % buildroot # path to where configs are to be stored
57 :     logdir="%s/logs" % buildroot # the logs will go here
58 :     bindir="%s/bin" % buildroot # the directory that binaries built will be sent for pkging
59 :     workdir="%s/work" % buildroot # work directory, where builds take place
60 :    
61 :     # setup the global dicts to hold build data, imported from xml
62 :     mastertrees={}
63 :     builds={}
64 :    
65 : tmcnulty 1.7 class Error(Exception):
66 :     """Base class for exceptions in this module."""
67 :     pass
68 :    
69 :     class BuildError(Error):
70 :     """Exception raised for build-level errors.
71 :    
72 :     Attributes:
73 :     message -- explanation of the error
74 :     """
75 :    
76 :     def __init__(self, message):
77 :     self.message = message
78 :    
79 :     class FatalError(Error):
80 :     """Exception for fatal errors that prevent program continuation.
81 :    
82 :     Attributes:
83 :     message -- explanation of why the specific transition is not allowed
84 :     """
85 :    
86 : tmcnulty 1.12 def __init__(self, message):
87 : tmcnulty 1.7 self.message = message
88 :    
89 : tmcnulty 1.1 def printverbose(myoutput):
90 :     """Supporting method to output info to stdout if verbosity level is set"""
91 :     if verbose==1:
92 :     print myoutput
93 :    
94 : tmcnulty 1.16 def linkpipes(input, output):
95 :     data = input.read(2048)
96 :     while data:
97 :     output.write(data)
98 : tmcnulty 1.18 data = input.read(2048)
99 :    
100 : tmcnulty 1.16 def runcmd(cmd, outfile=None, append=False, infile=None):
101 : tmcnulty 1.14 log("running " + cmd)
102 : tmcnulty 1.16
103 : tmcnulty 1.19 p4obj = Popen4(cmd)
104 :    
105 :     pin = p4obj.tochild
106 :     pouterr = p4obj.fromchild
107 : tmcnulty 1.16
108 :     if infile != None:
109 :     inobj = open(infile, "r")
110 :     linkpipes(inobj, pin)
111 :     inobj.close()
112 :    
113 :     if outfile != None:
114 :     if append:
115 :     mode = "a"
116 :     else:
117 :     mode = "w"
118 :    
119 :     outobj = open(outfile, mode)
120 : tmcnulty 1.18 linkpipes(pouterr,outobj)
121 : tmcnulty 1.16 outobj.close()
122 :    
123 : tmcnulty 1.19 err = p4obj.wait()
124 : tmcnulty 1.16
125 :     if err == None:
126 :     err = 0
127 : tmcnulty 1.17
128 : tmcnulty 1.15 log("result code: %i" % err)
129 : tmcnulty 1.14 return err
130 :    
131 : tmcnulty 1.1 def log(text,kinfo=0):
132 :     if kinfo:
133 :     printverbose(kinfo["name"] + " : " + text)
134 :     else:
135 :     printverbose("gkb : " + text)
136 :    
137 :     def verifydir(mydir,kinfo=0):
138 :     """Supporting method to verify a given exists, if not it will create it"""
139 :     log("verifying directory " + mydir,kinfo)
140 :     if not os.path.isdir(mydir):
141 :     log("%s doesn't exist, creating" % mydir,kinfo)
142 :     os.mkdir(mydir)
143 :     return mydir
144 :    
145 :     def chdir(mydir,kinfo):
146 :     verifydir(mydir,kinfo)
147 :     log("entering "+mydir,kinfo)
148 :     os.chdir(mydir)
149 :    
150 :     def verifyfile(myfile,kinfo):
151 :     """Supporting method to verify file exists, if not it will exit with error"""
152 :     if not os.path.isfile(myfile):
153 : tmcnulty 1.7 raise BuildError("cannot find file expected at %s, exiting" % myfile)
154 : tmcnulty 1.1 return myfile
155 :    
156 :     def md5sum(fileobj):
157 :     """calculates the md5sum for fileobj and returns it in hexadecimal"""
158 :     md = md5.new()
159 :     data = fileobj.read(8192)
160 :     while (data):
161 :     md.update(data)
162 :     data = fileobj.read(8192)
163 :    
164 :     digest = md.hexdigest()
165 :     return digest
166 :    
167 :     def krn_querymgr(command,kinfo):
168 :     """queries the build host manager with a variety of commands, such as checkout, checkin, etc."""
169 :     version=krn_localversion(kinfo)
170 :     log("querying distribution site manager with command '%s' (kernel version=%s)" % (command,version),kinfo)
171 :     result=getoutput("wget --quiet --output-document=- \"%s/manager.php?cmd=%s&host=%s&pass=%s&build=%s&version=%s\"" % (msite,command,host,passwd,kinfo["name"],version))
172 :     log("result: '"+result+"'",kinfo)
173 :     return result=="1"
174 :    
175 :     def krn_localversion(kinfo):
176 :     """Checks the version of the local source tree specified in kinfo"""
177 :     version=getoutput("""awk -F '=' '/^VERSION/{v=$2} /^PATCHLEVEL/{p=$2} /^SUBLEVEL/{s=$2} /^EXTRAVERSION/{e=$2} END { printf("%s.%s.%s%s\\n", v, p, s, e) }' """ + kinfo["workdir"] + """/Makefile | sed "s/ //g" """)
178 :     return version
179 :    
180 :     def gkb_build(root,kinfo):
181 :     """performs actual kernel builds given root, kinfo (tuple containing relevant data) , premake and makeopts"""
182 :    
183 :     # make sure needed directoriess (for this build) exist, if not create them
184 :    
185 :     verifydir("%s/%s" % (logdir, kinfo["name"]),kinfo)
186 :     verifydir("%s/%s" % (patchdir, kinfo["name"]),kinfo)
187 :    
188 :     # sync the source to make sure we are up to date ...
189 :     log("calling gkb_getsource",kinfo)
190 :     gkb_getsource(kinfo)
191 :    
192 : tmcnulty 1.10 # go into the work directory
193 : tmcnulty 1.12 chdir(workdir, kinfo)
194 : tmcnulty 1.10
195 :     # archive the clean source for later uploading
196 : tmcnulty 1.12 log("archiving source to " + kinfo["mastertree"] + ".tar.bz2", kinfo)
197 : tmcnulty 1.17 runcmd("tar cjf " + kinfo["mastertree"] + ".tar.bz2 " + kinfo["mastertree"])
198 : tmcnulty 1.10
199 :     # now we'll go into the tree's work dir
200 : tmcnulty 1.1 chdir(kinfo["workdir"],kinfo)
201 :    
202 :     # check for patches and apply if necessary
203 :     gkb_patch(kinfo)
204 :    
205 :     if kinfo["type"] == "kernel24":
206 :     krn_build24(kinfo)
207 :     elif kinfo["type"] == "kernel26":
208 :     krn_build24(kinfo) #run kernel24 for now, change later
209 :    
210 :     # Gerk comment:
211 :     # Do we need to change this with 24/26? we probably don't ... I'd rather see us define the list of make targets
212 :     # i.e. "dep","clean","vmlinux","modules","modules_install" or "clean","all","modules_install" for 2.6
213 :     # also of note, make all is not what we will always want with 2.6 kernels ... i.e. zImage.prep, zImage.chrp, etc
214 :     # also for backward compat they will continue to support calling things individual .. the makefile just does
215 :     # this for us with 'all'
216 :    
217 :    
218 :     def krn_build24(kinfo):
219 :     """build a kernel, version 2.4.x"""
220 :    
221 :     if krn_querymgr("checkout",kinfo):
222 : tmcnulty 1.7 try:
223 :     myversion=krn_localversion(kinfo)
224 :    
225 :     # fetch and cp the config file to work/.config
226 :     krn_config(kinfo)
227 :    
228 :     # **Note** : we set the preprocessing command to premake inline instead
229 :     # of globally as it is only needed in this target
230 :     if dont_build==0:
231 :     gkb_runmake("oldconfig",kinfo,premake+" /bin/cat %s/newlines | " % buildroot,makeopts)
232 :    
233 :     # give option to only repackage for testing purposes, comment out clean=1 at top of this file to use this feature
234 :     if (clean==1 and dont_build==0):
235 :     gkb_runmake("clean", kinfo, premake, makeopts)
236 :    
237 :     if dont_build==0:
238 :     gkb_runmake("dep", kinfo, premake, makeopts)
239 :     gkb_runmake(kinfo["binname"], kinfo, premake, makeopts)
240 :    
241 :     # We should check to see if binary built ok, if not bail out
242 :     mybindir=bindir+"/linux-"+kinfo["name"]+"-"+myversion
243 :     verifydir(mybindir,kinfo)
244 :     verifydir(mybindir+"/boot",kinfo)
245 :    
246 :     kbinloc=kinfo["workdir"]+"/"+kinfo["binpath"]+"/"+kinfo["binname"]
247 :     if verifyfile(kbinloc,kinfo):
248 :     # the binary exists, so let's cp it to bin...
249 :     copy(kbinloc,mybindir+"/boot/"+kinfo["binname"]+"-"+myversion)
250 :     else:
251 :     # the binary is not there, inform user and bail out with error
252 :     raise BuildError("%s is not present, assuming build failure and exiting. See log for details." % kbinloc)
253 :    
254 :     # now that we know he binary built, let's continue
255 :     if dont_build==0:
256 :     gkb_runmake("modules",kinfo, premake, makeopts)
257 :    
258 :     # **Note** : we prepend the INSTALL_MOD_PATH to the makeopts inline instead
259 :     # of globally as it is only needed in this target
260 :     gkb_runmake("modules_install", kinfo, premake, "INSTALL_MOD_PATH=%s %s" % (mybindir, makeopts))
261 :    
262 : tmcnulty 1.10 # compress and upload source archive
263 :     chdir(kinfo["workdir"]+"/..",kinfo)
264 :     archive_name = "src-%s.tar.bz2" % kinfo["mastertree"],
265 :    
266 :     # compress and upload kernel binary
267 : tmcnulty 1.7 chdir(bindir,kinfo)
268 :     archive_name = "linux-%s-%s.tar.bz2" % (kinfo["name"], myversion)
269 :    
270 :     log("compressing binary archive "+archive_name,kinfo)
271 :    
272 : tmcnulty 1.16 if runcmd("tar cjf "+archive_name+" "+os.path.basename(mybindir)):
273 : tmcnulty 1.7 raise BuildError("failed to `tar cjf %s`" % archive_name)
274 :    
275 : tmcnulty 1.16 runcmd("rm -rf %s" % mybindir)
276 : tmcnulty 1.7
277 : tmcnulty 1.10 krn_upload(archive_name,"kernel",myversion,kinfo)
278 :     krn_querymgr("checkin",kinfo)
279 :    
280 :     if (os.fork() == 0):
281 :     #in child
282 :     krn_upload(workdir + "/" + kinfo["mastertree"] + ".tar.bz2", "source", myversion, kinfo)
283 :    
284 : tmcnulty 1.7 except BuildError, e:
285 :     log(e.message, kinfo)
286 :     krn_querymgr("checkin",kinfo)
287 : tmcnulty 1.8 except:
288 :     krn_querymgr("checkin",kinfo)
289 :     raise
290 :    
291 : tmcnulty 1.1 def krn_build26(kinfo):
292 :     """build a kernel, version 2.6"""
293 :    
294 :     # source get routines
295 :     def gkb_getsource(kinfo):
296 :     """method to perform source sync on demand, currenty only supports rsync, but others can be added"""
297 :    
298 :     method=mastertrees[kinfo["mastertree"]]["method"]
299 :    
300 :     if method == "rsync":
301 :     get_rsync(kinfo)
302 :     elif method == "wget":
303 :     get_wget(kinfo)
304 :     elif method == "vanilla":
305 :     get_vanilla(kinfo)
306 :    
307 :     def get_rsync(kinfo):
308 :     """sync the source using rsync"""
309 :     args=mastertrees[kinfo["mastertree"]]["args"]
310 :    
311 :     if clean==1:
312 :     syncoptions="rsync -azv --delete"
313 :     else:
314 :     syncoptions="rsync -azv"
315 :    
316 :     syncline=args+" "+kinfo["workdir"]
317 :    
318 :     log("running rsync : %s %s" % (syncoptions, syncline),kinfo)
319 : tmcnulty 1.16 if runcmd("%s %s" % (syncoptions, syncline), "%s/%s/rsync.log" % (logdir, kinfo["name"])):
320 : tmcnulty 1.7 raise BuildError("sync failed, tried %s. See log for details." % syncline)
321 : tmcnulty 1.1
322 :     def get_wget(kinfo):
323 :     #needs work
324 :     """sync the source using wget and a tar.bz2"""
325 :     args=mastertrees[kinfo["mastertree"]]["args"]
326 :    
327 :     log("fetching source archive " % args,kinfo)
328 :     mysourcefile="%s/%s.tar.bz2" % (kinfo["workdir"],kinfo["name"])
329 :    
330 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
331 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
332 : tmcnulty 1.1
333 :     log("decompressing source file",kinfo)
334 : tmcnulty 1.16 if runcmd("tar xjf " % (myconfigfile,msite,kinfo["name"])):
335 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
336 : tmcnulty 1.1
337 :     def get_vanilla(kinfo):
338 :     args=mastertrees[kinfo["mastertree"]]["args"]
339 :    
340 :     log("fetching source archive %s" % args)
341 :     mysourcefile="%s/%s.tar.bz2" % (workdir,kinfo["name"])
342 :    
343 : tmcnulty 1.16 if runcmd("wget -c --output-document=%s %s" % (mysourcefile,args)):
344 : tmcnulty 1.7 raise BuildError("unable to download source file %s, aborting." % args)
345 : tmcnulty 1.1
346 :     log("decompressing source file %s" % mysourcefile,kinfo)
347 :    
348 :     #save the current working ectory
349 :     cwd=getoutput("pwd")
350 :    
351 :     chdir(workdir,kinfo)
352 :     pfd=os.popen("tar vxjf %s" % mysourcefile,"r")
353 :     trash=data=pfd.read(255)
354 :    
355 :     while trash:
356 :     trash=pfd.read(4096)
357 :    
358 :     if pfd.close():
359 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
360 : tmcnulty 1.1
361 :     fnames=split(data)
362 :     name=fnames[0]
363 :    
364 : tmcnulty 1.16 runcmd("rm -rf %s" % kinfo["workdir"])
365 : tmcnulty 1.1 move(work + "/" + dirname, kinfo["workdir"])
366 :    
367 :     #restore the previous working ectory
368 :     chdir(cwd,kinfo)
369 :    
370 :     def gkb_patch(kinfo):
371 :     """method that applies patch found in kinfo config files for running kernel build"""
372 :     if kinfo["patches"]:
373 :     patches=split(kinfo["patches"],";")
374 :    
375 :     for patch in patches:
376 :     log("downloading patch %s" % patch,kinfo)
377 :    
378 :     #set a name for this patch file
379 :     mypatchfile="%s/%s/%s.patch" % (patchdir,kinfo["name"],patch)
380 :    
381 :     # download pathfile or bail
382 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/patches/%s/%s" % (mypatchfile,msite,kinfo["name"],patch)):
383 : tmcnulty 1.7 raise BuildError("unable to download patchfile %s, aborting." % patch)
384 : tmcnulty 1.1
385 :     # we have a patch file, apply it or bail
386 :     log("perfoming patch with %s" % patch,kinfo)
387 : tmcnulty 1.16
388 :     # former patchcommand was:
389 :     #patchcommand="patch -p1 < %s > %s/%s/patch-%s.log 2>&1" % (mypatchfile,logdir,kinfo["name"],patch)
390 :     #log("using %s from %s" % (patchcommand,kinfo["workdir"]),kinfo)
391 :    
392 : tmcnulty 1.1 chdir(kinfo["workdir"],kinfo)
393 : tmcnulty 1.16 if runcmd("patch -p1", "%s/%s/patch-%s.log" % (logdir,kinfo["name"],patch), False, mypatchfile):
394 : tmcnulty 1.7 raise BuildError("patchfile %s failed, aborting. See patch log for details." % patch)
395 : tmcnulty 1.1 else:
396 :     log("no patchfiles, continuing",kinfo)
397 :    
398 :     def krn_config(kinfo):
399 :     """method to fetch and place config file for running kernel build"""
400 :    
401 :     if kinfo["config"]==1:
402 :     log("fetching config file",kinfo)
403 :     myconfigfile="%s/%s.config" % (configdir,kinfo["name"])
404 :    
405 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
406 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
407 : tmcnulty 1.1
408 :     log("copying config file to %s/.config" % kinfo["workdir"],kinfo)
409 :     copy(verifyfile(myconfigfile,kinfo),"%s/.config" % kinfo["workdir"])
410 :    
411 :     # Methods to support build()
412 :     def gkb_runmake(command, kinfo, premake, makeopts):
413 :     """Supporting method for build() ... a stub to run a make target and auto log it, given make target (command) and name (kernel name)"""
414 :     log("running make %s" % command,kinfo)
415 : tmcnulty 1.16 if runcmd("%s make %s %s" % (premake, makeopts, command), "%s/%s/make-%s.log" % (logdir, kinfo["name"], command)):
416 : tmcnulty 1.7 raise BuildError("unable to run make %s, aborting." % command)
417 : tmcnulty 1.1
418 :     def gkb_parsexml(name):
419 :     """parse the xml build file into mastertrees and builds"""
420 :     def start_element(name, attrs):
421 :     #print "In start_element: %s %s" % (name, attrs)
422 :     if name=="mastertree":
423 :     mastertrees[attrs["name"]]=attrs
424 :     elif name=="build":
425 :     builds[attrs["name"]]=attrs
426 :    
427 :     p = xml.parsers.expat.ParserCreate()
428 :     p.StartElementHandler = start_element
429 :     p.ParseFile(open(name))
430 : tmcnulty 1.3
431 : tmcnulty 1.10 def krn_upload(file, type, version, kinfo):
432 : tmcnulty 1.3 """upload the indicated file to the distribution site (kernel archives)"""
433 : tmcnulty 1.10
434 :     if type=="kernel":
435 :     log("uploading kernel version "+version+" to "+msite,kinfo)
436 :     elif type=="source":
437 :     log("uploading source "+kinfo["mastertree"]+" to "+msite,kinfo)
438 :     else:
439 :     raise BuildException, "invalid file upload type: " + type
440 :    
441 :     forms = ParseResponse(urlopen(msite+"/upload.html"))
442 : tmcnulty 1.3 form = forms[0]
443 :    
444 :     form["host"] = host
445 :     form["pass"] = passwd
446 : tmcnulty 1.10 form["type"] = type
447 :     form["tree"] = kinfo["mastertree"]
448 : tmcnulty 1.3 form["build"] = kinfo["name"]
449 :     form["version"] = version
450 :    
451 : tmcnulty 1.5 form.add_file(open(file), "application/x-bzip2", os.path.basename(file))
452 : tmcnulty 1.10
453 : tmcnulty 1.3 # form.click() returns a urllib2.Request object
454 :     # (see HTMLForm.click.__doc__ if you don't have urllib2)
455 : tmcnulty 1.10 response = urlopen(form.click("cmd"))
456 : tmcnulty 1.3
457 : tmcnulty 1.10 if debug:
458 :     print response.geturl()
459 :     print response.info() # headers
460 :     print response.read() # body
461 :    
462 :     log("response: " + response.read(),kinfo)
463 : tmcnulty 1.3
464 : tmcnulty 1.10 response.close()
465 :    
466 : tmcnulty 1.1 def main():
467 :     """ main program gets executed here """
468 :    
469 :     # get our working ectory
470 :     root=getoutput("pwd")
471 :    
472 :     today=getoutput("date +%D")
473 :     buildtime=getoutput("date +'%R:%S %Z'")
474 :    
475 :     print "GKB started %s %s" % (today,buildtime)
476 :    
477 :     # verify the existence important directories, and create if necessary
478 :     verifydir(logdir)
479 :     verifydir(configdir)
480 :     verifydir(patchdir)
481 :     verifydir(bindir)
482 :     verifydir("%s/work" % buildroot) # build dir, make sure it exists
483 :    
484 :     # download the build jobs from the master site
485 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=gkb.xml \"%s/manager.php?cmd=getjobs&host=%s&pass=%s\"" % (msite,host,passwd)):
486 : tmcnulty 1.12 raise FatalError, "Unable to download build config from master site %s, aborting." % msite
487 : tmcnulty 1.1
488 :     # sets up 'mastertrees' and 'builds' dicts
489 :     gkb_parsexml('gkb.xml')
490 :    
491 : tmcnulty 1.19 runcmd("sleep 10")
492 :    
493 : tmcnulty 1.1 for bdict in builds.values():
494 :     myworkdir="%s/%s" % (workdir,bdict["mastertree"])
495 :     bdict["workdir"]=myworkdir
496 :    
497 : tmcnulty 1.9 try:
498 :     # for now just call the build
499 :     gkb_build(root, bdict)
500 :     except BuildError, e:
501 :     log(e.message, bdict)
502 : tmcnulty 1.12 except KeyboardInterrupt, e:
503 :     log("Caught keyboard interrupt, exiting...")
504 :     break
505 : tmcnulty 1.13
506 : tmcnulty 1.1 endtime=getoutput("date +'%R:%S %Z'")
507 :    
508 :     print "GKB finished %s %s" % (today,endtime)
509 :    
510 :     # and finally, call the mainloop to execute
511 :     main()

Tobias McNulty

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help