[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 :    
99 :     def runcmd(cmd, outfile=None, append=False, infile=None):
100 : tmcnulty 1.14 log("running " + cmd)
101 : tmcnulty 1.16
102 :     (pin, pouterr) = os.popen4(cmd)
103 :    
104 :     if infile != None:
105 :     inobj = open(infile, "r")
106 :     linkpipes(inobj, pin)
107 :     inobj.close()
108 :    
109 :     if outfile != None:
110 :     if append:
111 :     mode = "a"
112 :     else:
113 :     mode = "w"
114 :    
115 :     outobj = open(outfile, mode)
116 :     linkpipes(file,pouterr)
117 :     outobj.close()
118 :    
119 :     err = file.close()
120 :    
121 :     if err == None:
122 :     err = 0
123 :    
124 : tmcnulty 1.15 log("result code: %i" % err)
125 : tmcnulty 1.16
126 : tmcnulty 1.14 return err
127 :    
128 : tmcnulty 1.1 def log(text,kinfo=0):
129 :     if kinfo:
130 :     printverbose(kinfo["name"] + " : " + text)
131 :     else:
132 :     printverbose("gkb : " + text)
133 :    
134 :     def verifydir(mydir,kinfo=0):
135 :     """Supporting method to verify a given exists, if not it will create it"""
136 :     log("verifying directory " + mydir,kinfo)
137 :     if not os.path.isdir(mydir):
138 :     log("%s doesn't exist, creating" % mydir,kinfo)
139 :     os.mkdir(mydir)
140 :     return mydir
141 :    
142 :     def chdir(mydir,kinfo):
143 :     verifydir(mydir,kinfo)
144 :     log("entering "+mydir,kinfo)
145 :     os.chdir(mydir)
146 :    
147 :     def verifyfile(myfile,kinfo):
148 :     """Supporting method to verify file exists, if not it will exit with error"""
149 :     if not os.path.isfile(myfile):
150 : tmcnulty 1.7 raise BuildError("cannot find file expected at %s, exiting" % myfile)
151 : tmcnulty 1.1 return myfile
152 :    
153 :     def md5sum(fileobj):
154 :     """calculates the md5sum for fileobj and returns it in hexadecimal"""
155 :     md = md5.new()
156 :     data = fileobj.read(8192)
157 :     while (data):
158 :     md.update(data)
159 :     data = fileobj.read(8192)
160 :    
161 :     digest = md.hexdigest()
162 :     return digest
163 :    
164 :     def krn_querymgr(command,kinfo):
165 :     """queries the build host manager with a variety of commands, such as checkout, checkin, etc."""
166 :     version=krn_localversion(kinfo)
167 :     log("querying distribution site manager with command '%s' (kernel version=%s)" % (command,version),kinfo)
168 :     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))
169 :     log("result: '"+result+"'",kinfo)
170 :     return result=="1"
171 :    
172 :     def krn_localversion(kinfo):
173 :     """Checks the version of the local source tree specified in kinfo"""
174 :     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" """)
175 :     return version
176 :    
177 :     def gkb_build(root,kinfo):
178 :     """performs actual kernel builds given root, kinfo (tuple containing relevant data) , premake and makeopts"""
179 :    
180 :     # make sure needed directoriess (for this build) exist, if not create them
181 :    
182 :     verifydir("%s/%s" % (logdir, kinfo["name"]),kinfo)
183 :     verifydir("%s/%s" % (patchdir, kinfo["name"]),kinfo)
184 :    
185 :     # sync the source to make sure we are up to date ...
186 :     log("calling gkb_getsource",kinfo)
187 :     gkb_getsource(kinfo)
188 :    
189 : tmcnulty 1.10 # go into the work directory
190 : tmcnulty 1.12 chdir(workdir, kinfo)
191 : tmcnulty 1.10
192 :     # archive the clean source for later uploading
193 : tmcnulty 1.12 log("archiving source to " + kinfo["mastertree"] + ".tar.bz2", kinfo)
194 : tmcnulty 1.16 runcmd("tar xjf " + kinfo["mastertree"] + ".tar.bz2 " + kinfo["mastertree"])
195 : tmcnulty 1.10
196 :     # now we'll go into the tree's work dir
197 : tmcnulty 1.1 chdir(kinfo["workdir"],kinfo)
198 :    
199 :     # check for patches and apply if necessary
200 :     gkb_patch(kinfo)
201 :    
202 :     if kinfo["type"] == "kernel24":
203 :     krn_build24(kinfo)
204 :     elif kinfo["type"] == "kernel26":
205 :     krn_build24(kinfo) #run kernel24 for now, change later
206 :    
207 :     # Gerk comment:
208 :     # Do we need to change this with 24/26? we probably don't ... I'd rather see us define the list of make targets
209 :     # i.e. "dep","clean","vmlinux","modules","modules_install" or "clean","all","modules_install" for 2.6
210 :     # also of note, make all is not what we will always want with 2.6 kernels ... i.e. zImage.prep, zImage.chrp, etc
211 :     # also for backward compat they will continue to support calling things individual .. the makefile just does
212 :     # this for us with 'all'
213 :    
214 :    
215 :     def krn_build24(kinfo):
216 :     """build a kernel, version 2.4.x"""
217 :    
218 :     if krn_querymgr("checkout",kinfo):
219 : tmcnulty 1.7 try:
220 :     myversion=krn_localversion(kinfo)
221 :    
222 :     # fetch and cp the config file to work/.config
223 :     krn_config(kinfo)
224 :    
225 :     # **Note** : we set the preprocessing command to premake inline instead
226 :     # of globally as it is only needed in this target
227 :     if dont_build==0:
228 :     gkb_runmake("oldconfig",kinfo,premake+" /bin/cat %s/newlines | " % buildroot,makeopts)
229 :    
230 :     # give option to only repackage for testing purposes, comment out clean=1 at top of this file to use this feature
231 :     if (clean==1 and dont_build==0):
232 :     gkb_runmake("clean", kinfo, premake, makeopts)
233 :    
234 :     if dont_build==0:
235 :     gkb_runmake("dep", kinfo, premake, makeopts)
236 :     gkb_runmake(kinfo["binname"], kinfo, premake, makeopts)
237 :    
238 :     # We should check to see if binary built ok, if not bail out
239 :     mybindir=bindir+"/linux-"+kinfo["name"]+"-"+myversion
240 :     verifydir(mybindir,kinfo)
241 :     verifydir(mybindir+"/boot",kinfo)
242 :    
243 :     kbinloc=kinfo["workdir"]+"/"+kinfo["binpath"]+"/"+kinfo["binname"]
244 :     if verifyfile(kbinloc,kinfo):
245 :     # the binary exists, so let's cp it to bin...
246 :     copy(kbinloc,mybindir+"/boot/"+kinfo["binname"]+"-"+myversion)
247 :     else:
248 :     # the binary is not there, inform user and bail out with error
249 :     raise BuildError("%s is not present, assuming build failure and exiting. See log for details." % kbinloc)
250 :    
251 :     # now that we know he binary built, let's continue
252 :     if dont_build==0:
253 :     gkb_runmake("modules",kinfo, premake, makeopts)
254 :    
255 :     # **Note** : we prepend the INSTALL_MOD_PATH to the makeopts inline instead
256 :     # of globally as it is only needed in this target
257 :     gkb_runmake("modules_install", kinfo, premake, "INSTALL_MOD_PATH=%s %s" % (mybindir, makeopts))
258 :    
259 : tmcnulty 1.10 # compress and upload source archive
260 :     chdir(kinfo["workdir"]+"/..",kinfo)
261 :     archive_name = "src-%s.tar.bz2" % kinfo["mastertree"],
262 :    
263 :     # compress and upload kernel binary
264 : tmcnulty 1.7 chdir(bindir,kinfo)
265 :     archive_name = "linux-%s-%s.tar.bz2" % (kinfo["name"], myversion)
266 :    
267 :     log("compressing binary archive "+archive_name,kinfo)
268 :    
269 : tmcnulty 1.16 if runcmd("tar cjf "+archive_name+" "+os.path.basename(mybindir)):
270 : tmcnulty 1.7 raise BuildError("failed to `tar cjf %s`" % archive_name)
271 :    
272 : tmcnulty 1.16 runcmd("rm -rf %s" % mybindir)
273 : tmcnulty 1.7
274 : tmcnulty 1.10 krn_upload(archive_name,"kernel",myversion,kinfo)
275 :     krn_querymgr("checkin",kinfo)
276 :    
277 :     if (os.fork() == 0):
278 :     #in child
279 :     krn_upload(workdir + "/" + kinfo["mastertree"] + ".tar.bz2", "source", myversion, kinfo)
280 :    
281 : tmcnulty 1.7 except BuildError, e:
282 :     log(e.message, kinfo)
283 :     krn_querymgr("checkin",kinfo)
284 : tmcnulty 1.8 except:
285 :     krn_querymgr("checkin",kinfo)
286 :     raise
287 :    
288 : tmcnulty 1.1 def krn_build26(kinfo):
289 :     """build a kernel, version 2.6"""
290 :    
291 :     # source get routines
292 :     def gkb_getsource(kinfo):
293 :     """method to perform source sync on demand, currenty only supports rsync, but others can be added"""
294 :    
295 :     method=mastertrees[kinfo["mastertree"]]["method"]
296 :    
297 :     if method == "rsync":
298 :     get_rsync(kinfo)
299 :     elif method == "wget":
300 :     get_wget(kinfo)
301 :     elif method == "vanilla":
302 :     get_vanilla(kinfo)
303 :    
304 :     def get_rsync(kinfo):
305 :     """sync the source using rsync"""
306 :     args=mastertrees[kinfo["mastertree"]]["args"]
307 :    
308 :     if clean==1:
309 :     syncoptions="rsync -azv --delete"
310 :     else:
311 :     syncoptions="rsync -azv"
312 :    
313 :     syncline=args+" "+kinfo["workdir"]
314 :    
315 :     log("running rsync : %s %s" % (syncoptions, syncline),kinfo)
316 : tmcnulty 1.16 if runcmd("%s %s" % (syncoptions, syncline), "%s/%s/rsync.log" % (logdir, kinfo["name"])):
317 : tmcnulty 1.7 raise BuildError("sync failed, tried %s. See log for details." % syncline)
318 : tmcnulty 1.1
319 :     def get_wget(kinfo):
320 :     #needs work
321 :     """sync the source using wget and a tar.bz2"""
322 :     args=mastertrees[kinfo["mastertree"]]["args"]
323 :    
324 :     log("fetching source archive " % args,kinfo)
325 :     mysourcefile="%s/%s.tar.bz2" % (kinfo["workdir"],kinfo["name"])
326 :    
327 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
328 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
329 : tmcnulty 1.1
330 :     log("decompressing source file",kinfo)
331 : tmcnulty 1.16 if runcmd("tar xjf " % (myconfigfile,msite,kinfo["name"])):
332 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
333 : tmcnulty 1.1
334 :     def get_vanilla(kinfo):
335 :     args=mastertrees[kinfo["mastertree"]]["args"]
336 :    
337 :     log("fetching source archive %s" % args)
338 :     mysourcefile="%s/%s.tar.bz2" % (workdir,kinfo["name"])
339 :    
340 : tmcnulty 1.16 if runcmd("wget -c --output-document=%s %s" % (mysourcefile,args)):
341 : tmcnulty 1.7 raise BuildError("unable to download source file %s, aborting." % args)
342 : tmcnulty 1.1
343 :     log("decompressing source file %s" % mysourcefile,kinfo)
344 :    
345 :     #save the current working ectory
346 :     cwd=getoutput("pwd")
347 :    
348 :     chdir(workdir,kinfo)
349 :     pfd=os.popen("tar vxjf %s" % mysourcefile,"r")
350 :     trash=data=pfd.read(255)
351 :    
352 :     while trash:
353 :     trash=pfd.read(4096)
354 :    
355 :     if pfd.close():
356 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
357 : tmcnulty 1.1
358 :     fnames=split(data)
359 :     name=fnames[0]
360 :    
361 : tmcnulty 1.16 runcmd("rm -rf %s" % kinfo["workdir"])
362 : tmcnulty 1.1 move(work + "/" + dirname, kinfo["workdir"])
363 :    
364 :     #restore the previous working ectory
365 :     chdir(cwd,kinfo)
366 :    
367 :     def gkb_patch(kinfo):
368 :     """method that applies patch found in kinfo config files for running kernel build"""
369 :     if kinfo["patches"]:
370 :     patches=split(kinfo["patches"],";")
371 :    
372 :     for patch in patches:
373 :     log("downloading patch %s" % patch,kinfo)
374 :    
375 :     #set a name for this patch file
376 :     mypatchfile="%s/%s/%s.patch" % (patchdir,kinfo["name"],patch)
377 :    
378 :     # download pathfile or bail
379 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/patches/%s/%s" % (mypatchfile,msite,kinfo["name"],patch)):
380 : tmcnulty 1.7 raise BuildError("unable to download patchfile %s, aborting." % patch)
381 : tmcnulty 1.1
382 :     # we have a patch file, apply it or bail
383 :     log("perfoming patch with %s" % patch,kinfo)
384 : tmcnulty 1.16
385 :     # former patchcommand was:
386 :     #patchcommand="patch -p1 < %s > %s/%s/patch-%s.log 2>&1" % (mypatchfile,logdir,kinfo["name"],patch)
387 :     #log("using %s from %s" % (patchcommand,kinfo["workdir"]),kinfo)
388 :    
389 : tmcnulty 1.1 chdir(kinfo["workdir"],kinfo)
390 : tmcnulty 1.16 if runcmd("patch -p1", "%s/%s/patch-%s.log" % (logdir,kinfo["name"],patch), False, mypatchfile):
391 : tmcnulty 1.7 raise BuildError("patchfile %s failed, aborting. See patch log for details." % patch)
392 : tmcnulty 1.1 else:
393 :     log("no patchfiles, continuing",kinfo)
394 :    
395 :     def krn_config(kinfo):
396 :     """method to fetch and place config file for running kernel build"""
397 :    
398 :     if kinfo["config"]==1:
399 :     log("fetching config file",kinfo)
400 :     myconfigfile="%s/%s.config" % (configdir,kinfo["name"])
401 :    
402 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
403 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
404 : tmcnulty 1.1
405 :     log("copying config file to %s/.config" % kinfo["workdir"],kinfo)
406 :     copy(verifyfile(myconfigfile,kinfo),"%s/.config" % kinfo["workdir"])
407 :    
408 :     # Methods to support build()
409 :     def gkb_runmake(command, kinfo, premake, makeopts):
410 :     """Supporting method for build() ... a stub to run a make target and auto log it, given make target (command) and name (kernel name)"""
411 :     log("running make %s" % command,kinfo)
412 : tmcnulty 1.16 if runcmd("%s make %s %s" % (premake, makeopts, command), "%s/%s/make-%s.log" % (logdir, kinfo["name"], command)):
413 : tmcnulty 1.7 raise BuildError("unable to run make %s, aborting." % command)
414 : tmcnulty 1.1
415 :     def gkb_parsexml(name):
416 :     """parse the xml build file into mastertrees and builds"""
417 :     def start_element(name, attrs):
418 :     #print "In start_element: %s %s" % (name, attrs)
419 :     if name=="mastertree":
420 :     mastertrees[attrs["name"]]=attrs
421 :     elif name=="build":
422 :     builds[attrs["name"]]=attrs
423 :    
424 :     p = xml.parsers.expat.ParserCreate()
425 :     p.StartElementHandler = start_element
426 :     p.ParseFile(open(name))
427 : tmcnulty 1.3
428 : tmcnulty 1.10 def krn_upload(file, type, version, kinfo):
429 : tmcnulty 1.3 """upload the indicated file to the distribution site (kernel archives)"""
430 : tmcnulty 1.10
431 :     if type=="kernel":
432 :     log("uploading kernel version "+version+" to "+msite,kinfo)
433 :     elif type=="source":
434 :     log("uploading source "+kinfo["mastertree"]+" to "+msite,kinfo)
435 :     else:
436 :     raise BuildException, "invalid file upload type: " + type
437 :    
438 :     forms = ParseResponse(urlopen(msite+"/upload.html"))
439 : tmcnulty 1.3 form = forms[0]
440 :    
441 :     form["host"] = host
442 :     form["pass"] = passwd
443 : tmcnulty 1.10 form["type"] = type
444 :     form["tree"] = kinfo["mastertree"]
445 : tmcnulty 1.3 form["build"] = kinfo["name"]
446 :     form["version"] = version
447 :    
448 : tmcnulty 1.5 form.add_file(open(file), "application/x-bzip2", os.path.basename(file))
449 : tmcnulty 1.10
450 : tmcnulty 1.3 # form.click() returns a urllib2.Request object
451 :     # (see HTMLForm.click.__doc__ if you don't have urllib2)
452 : tmcnulty 1.10 response = urlopen(form.click("cmd"))
453 : tmcnulty 1.3
454 : tmcnulty 1.10 if debug:
455 :     print response.geturl()
456 :     print response.info() # headers
457 :     print response.read() # body
458 :    
459 :     log("response: " + response.read(),kinfo)
460 : tmcnulty 1.3
461 : tmcnulty 1.10 response.close()
462 :    
463 : tmcnulty 1.1 def main():
464 :     """ main program gets executed here """
465 :    
466 :     # get our working ectory
467 :     root=getoutput("pwd")
468 :    
469 :     today=getoutput("date +%D")
470 :     buildtime=getoutput("date +'%R:%S %Z'")
471 :    
472 :     print "GKB started %s %s" % (today,buildtime)
473 :    
474 :     # verify the existence important directories, and create if necessary
475 :     verifydir(logdir)
476 :     verifydir(configdir)
477 :     verifydir(patchdir)
478 :     verifydir(bindir)
479 :     verifydir("%s/work" % buildroot) # build dir, make sure it exists
480 :    
481 :     # download the build jobs from the master site
482 : tmcnulty 1.16 if runcmd("wget --quiet --output-document=gkb.xml \"%s/manager.php?cmd=getjobs&host=%s&pass=%s\"" % (msite,host,passwd)):
483 : tmcnulty 1.12 raise FatalError, "Unable to download build config from master site %s, aborting." % msite
484 : tmcnulty 1.1
485 :     # sets up 'mastertrees' and 'builds' dicts
486 :     gkb_parsexml('gkb.xml')
487 :    
488 :     for bdict in builds.values():
489 :     myworkdir="%s/%s" % (workdir,bdict["mastertree"])
490 :     bdict["workdir"]=myworkdir
491 :    
492 : tmcnulty 1.9 try:
493 :     # for now just call the build
494 :     gkb_build(root, bdict)
495 :     except BuildError, e:
496 :     log(e.message, bdict)
497 : tmcnulty 1.12 except KeyboardInterrupt, e:
498 :     log("Caught keyboard interrupt, exiting...")
499 :     break
500 :     except:
501 :     log("Caught unknown exception, exiting...")
502 :     break
503 : tmcnulty 1.13
504 : tmcnulty 1.1 endtime=getoutput("date +'%R:%S %Z'")
505 :    
506 :     print "GKB finished %s %s" % (today,endtime)
507 :    
508 :     # and finally, call the mainloop to execute
509 :     main()

Tobias McNulty

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help