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

Tobias McNulty

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help