[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.6 clean=1
34 :     dont_build=0
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 :     def __init__(self, previous, next, message):
87 :     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 :     # now we'll go into the work
156 :     chdir(kinfo["workdir"],kinfo)
157 :    
158 :     # check for patches and apply if necessary
159 :     gkb_patch(kinfo)
160 :    
161 :     if kinfo["type"] == "kernel24":
162 :     krn_build24(kinfo)
163 :     elif kinfo["type"] == "kernel26":
164 :     krn_build24(kinfo) #run kernel24 for now, change later
165 :    
166 :     # Gerk comment:
167 :     # Do we need to change this with 24/26? we probably don't ... I'd rather see us define the list of make targets
168 :     # i.e. "dep","clean","vmlinux","modules","modules_install" or "clean","all","modules_install" for 2.6
169 :     # also of note, make all is not what we will always want with 2.6 kernels ... i.e. zImage.prep, zImage.chrp, etc
170 :     # also for backward compat they will continue to support calling things individual .. the makefile just does
171 :     # this for us with 'all'
172 :    
173 :    
174 :     def krn_build24(kinfo):
175 :     """build a kernel, version 2.4.x"""
176 :    
177 :     if krn_querymgr("checkout",kinfo):
178 : tmcnulty 1.7 try:
179 :     myversion=krn_localversion(kinfo)
180 :    
181 :     # fetch and cp the config file to work/.config
182 :     krn_config(kinfo)
183 :    
184 :     # **Note** : we set the preprocessing command to premake inline instead
185 :     # of globally as it is only needed in this target
186 :     if dont_build==0:
187 :     gkb_runmake("oldconfig",kinfo,premake+" /bin/cat %s/newlines | " % buildroot,makeopts)
188 :    
189 :     # give option to only repackage for testing purposes, comment out clean=1 at top of this file to use this feature
190 :     if (clean==1 and dont_build==0):
191 :     gkb_runmake("clean", kinfo, premake, makeopts)
192 :    
193 :     if dont_build==0:
194 :     gkb_runmake("dep", kinfo, premake, makeopts)
195 :     gkb_runmake(kinfo["binname"], kinfo, premake, makeopts)
196 :    
197 :     # We should check to see if binary built ok, if not bail out
198 :     mybindir=bindir+"/linux-"+kinfo["name"]+"-"+myversion
199 :     verifydir(mybindir,kinfo)
200 :     verifydir(mybindir+"/boot",kinfo)
201 :    
202 :     kbinloc=kinfo["workdir"]+"/"+kinfo["binpath"]+"/"+kinfo["binname"]
203 :     if verifyfile(kbinloc,kinfo):
204 :     # the binary exists, so let's cp it to bin...
205 :     copy(kbinloc,mybindir+"/boot/"+kinfo["binname"]+"-"+myversion)
206 :     else:
207 :     # the binary is not there, inform user and bail out with error
208 :     raise BuildError("%s is not present, assuming build failure and exiting. See log for details." % kbinloc)
209 :    
210 :     # now that we know he binary built, let's continue
211 :     if dont_build==0:
212 :     gkb_runmake("modules",kinfo, premake, makeopts)
213 :    
214 :     # **Note** : we prepend the INSTALL_MOD_PATH to the makeopts inline instead
215 :     # of globally as it is only needed in this target
216 :     gkb_runmake("modules_install", kinfo, premake, "INSTALL_MOD_PATH=%s %s" % (mybindir, makeopts))
217 :    
218 :     chdir(bindir,kinfo)
219 :     archive_name = "linux-%s-%s.tar.bz2" % (kinfo["name"], myversion)
220 :    
221 :     log("compressing binary archive "+archive_name,kinfo)
222 :    
223 :     if os.system("tar cjf "+archive_name+" "+os.path.basename(mybindir)):
224 :     raise BuildError("failed to `tar cjf %s`" % archive_name)
225 :    
226 :     os.system("rm -rf %s" % mybindir)
227 :    
228 :     krn_upload(archive_name,myversion,kinfo)
229 :     except BuildError, e:
230 :     log(e.message, kinfo)
231 :     krn_querymgr("checkin",kinfo)
232 : tmcnulty 1.8 except:
233 :     krn_querymgr("checkin",kinfo)
234 :     raise
235 :    
236 : tmcnulty 1.1 def krn_build26(kinfo):
237 :     """build a kernel, version 2.6"""
238 :    
239 :     # source get routines
240 :     def gkb_getsource(kinfo):
241 :     """method to perform source sync on demand, currenty only supports rsync, but others can be added"""
242 :    
243 :     method=mastertrees[kinfo["mastertree"]]["method"]
244 :    
245 :     if method == "rsync":
246 :     get_rsync(kinfo)
247 :     elif method == "wget":
248 :     get_wget(kinfo)
249 :     elif method == "vanilla":
250 :     get_vanilla(kinfo)
251 :    
252 :     def get_rsync(kinfo):
253 :     """sync the source using rsync"""
254 :     args=mastertrees[kinfo["mastertree"]]["args"]
255 :    
256 :     if clean==1:
257 :     syncoptions="rsync -azv --delete"
258 :     else:
259 :     syncoptions="rsync -azv"
260 :    
261 :     syncline=args+" "+kinfo["workdir"]
262 :    
263 :     log("running rsync : %s %s" % (syncoptions, syncline),kinfo)
264 :     if os.system("%s %s > %s/%s/rsync.log 2>&1" % (syncoptions, syncline, logdir, kinfo["name"])):
265 : tmcnulty 1.7 raise BuildError("sync failed, tried %s. See log for details." % syncline)
266 : tmcnulty 1.1
267 :     def get_wget(kinfo):
268 :     #needs work
269 :     """sync the source using wget and a tar.bz2"""
270 :     args=mastertrees[kinfo["mastertree"]]["args"]
271 :    
272 :     log("fetching source archive " % args,kinfo)
273 :     mysourcefile="%s/%s.tar.bz2" % (kinfo["workdir"],kinfo["name"])
274 :    
275 :     if os.system("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
276 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
277 : tmcnulty 1.1
278 :     log("decompressing source file",kinfo)
279 :     if os.system("tar xjf " % (myconfigfile,msite,kinfo["name"])):
280 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
281 : tmcnulty 1.1
282 :     def get_vanilla(kinfo):
283 :     args=mastertrees[kinfo["mastertree"]]["args"]
284 :    
285 :     log("fetching source archive %s" % args)
286 :     mysourcefile="%s/%s.tar.bz2" % (workdir,kinfo["name"])
287 :    
288 :     if os.system("wget -c --output-document=%s %s" % (mysourcefile,args)):
289 : tmcnulty 1.7 raise BuildError("unable to download source file %s, aborting." % args)
290 : tmcnulty 1.1
291 :     log("decompressing source file %s" % mysourcefile,kinfo)
292 :    
293 :     #save the current working ectory
294 :     cwd=getoutput("pwd")
295 :    
296 :     chdir(workdir,kinfo)
297 :     pfd=os.popen("tar vxjf %s" % mysourcefile,"r")
298 :     trash=data=pfd.read(255)
299 :    
300 :     while trash:
301 :     trash=pfd.read(4096)
302 :    
303 :     if pfd.close():
304 : tmcnulty 1.7 raise BuildError("unable to decompress source file, aborting.")
305 : tmcnulty 1.1
306 :     fnames=split(data)
307 :     name=fnames[0]
308 :    
309 :     os.system("rm -rf %s" % kinfo["workdir"])
310 :     move(work + "/" + dirname, kinfo["workdir"])
311 :    
312 :     #restore the previous working ectory
313 :     chdir(cwd,kinfo)
314 :    
315 :     def gkb_patch(kinfo):
316 :     """method that applies patch found in kinfo config files for running kernel build"""
317 :     if kinfo["patches"]:
318 :     patches=split(kinfo["patches"],";")
319 :    
320 :     for patch in patches:
321 :     log("downloading patch %s" % patch,kinfo)
322 :    
323 :     #set a name for this patch file
324 :     mypatchfile="%s/%s/%s.patch" % (patchdir,kinfo["name"],patch)
325 :    
326 :     # download pathfile or bail
327 :     if os.system("wget --quiet --output-document=%s %s/patches/%s/%s" % (mypatchfile,msite,kinfo["name"],patch)):
328 : tmcnulty 1.7 raise BuildError("unable to download patchfile %s, aborting." % patch)
329 : tmcnulty 1.1
330 :     # we have a patch file, apply it or bail
331 :     log("perfoming patch with %s" % patch,kinfo)
332 :     patchcommand="patch -p1 < %s > %s/%s/patch-%s.log 2>&1" % (mypatchfile,logdir,kinfo["name"],patch)
333 :     log("using %s from %s" % (patchcommand,kinfo["workdir"]),kinfo)
334 :     chdir(kinfo["workdir"],kinfo)
335 :     if os.system(patchcommand):
336 : tmcnulty 1.7 raise BuildError("patchfile %s failed, aborting. See patch log for details." % patch)
337 : tmcnulty 1.1 else:
338 :     log("no patchfiles, continuing",kinfo)
339 :    
340 :     def krn_config(kinfo):
341 :     """method to fetch and place config file for running kernel build"""
342 :    
343 :     if kinfo["config"]==1:
344 :     log("fetching config file",kinfo)
345 :     myconfigfile="%s/%s.config" % (configdir,kinfo["name"])
346 :    
347 :     if os.system("wget --quiet --output-document=%s %s/configs/%s" % (myconfigfile,msite,kinfo["name"])):
348 : tmcnulty 1.7 raise BuildError("unable to download configfile, aborting.")
349 : tmcnulty 1.1
350 :     log("copying config file to %s/.config" % kinfo["workdir"],kinfo)
351 :     copy(verifyfile(myconfigfile,kinfo),"%s/.config" % kinfo["workdir"])
352 :    
353 :     # Methods to support build()
354 :     def gkb_runmake(command, kinfo, premake, makeopts):
355 :     """Supporting method for build() ... a stub to run a make target and auto log it, given make target (command) and name (kernel name)"""
356 :     log("running make %s" % command,kinfo)
357 :     if os.system("%s make %s %s > %s/%s/make-%s.log 2>&1" % (premake, makeopts, command, logdir, kinfo["name"], command)):
358 : tmcnulty 1.7 raise BuildError("unable to run make %s, aborting." % command)
359 : tmcnulty 1.1
360 :     def gkb_parsexml(name):
361 :     """parse the xml build file into mastertrees and builds"""
362 :     def start_element(name, attrs):
363 :     #print "In start_element: %s %s" % (name, attrs)
364 :     if name=="mastertree":
365 :     mastertrees[attrs["name"]]=attrs
366 :     elif name=="build":
367 :     builds[attrs["name"]]=attrs
368 :    
369 :     p = xml.parsers.expat.ParserCreate()
370 :     p.StartElementHandler = start_element
371 :     p.ParseFile(open(name))
372 : tmcnulty 1.3
373 :     def krn_upload(file, version, kinfo):
374 :     """upload the indicated file to the distribution site (kernel archives)"""
375 :     forms = ParseResponse(urlopen(msite+"/fileupload.html"))
376 :     form = forms[0]
377 :    
378 :     form["host"] = host
379 :     form["pass"] = passwd
380 :     form["build"] = kinfo["name"]
381 :     form["version"] = version
382 :    
383 : tmcnulty 1.5 form.add_file(open(file), "application/x-bzip2", os.path.basename(file))
384 : tmcnulty 1.3
385 :     log("uploading kernel version "+version+" to "+msite,kinfo)
386 :     # form.click() returns a urllib2.Request object
387 :     # (see HTMLForm.click.__doc__ if you don't have urllib2)
388 :     response2 = urlopen(form.click("cmd"))
389 :    
390 :     #print response2.geturl()
391 :     #print response2.info() # headers
392 :     #print response2.read() # body
393 :     log("response: " + response2.read(),kinfo)
394 :    
395 :     response2.close()
396 :    
397 : tmcnulty 1.1 def main():
398 :     """ main program gets executed here """
399 :    
400 :     # get our working ectory
401 :     root=getoutput("pwd")
402 :    
403 :     today=getoutput("date +%D")
404 :     buildtime=getoutput("date +'%R:%S %Z'")
405 :    
406 :     print "GKB started %s %s" % (today,buildtime)
407 :    
408 :     # verify the existence important directories, and create if necessary
409 :     verifydir(logdir)
410 :     verifydir(configdir)
411 :     verifydir(patchdir)
412 :     verifydir(bindir)
413 :     verifydir("%s/work" % buildroot) # build dir, make sure it exists
414 :    
415 :     # download the build jobs from the master site
416 :     if os.system("wget --quiet --output-document=gkb.xml \"%s/manager.php?cmd=getjobs&host=%s&pass=%s\"" % (msite,host,passwd)):
417 :     deathbyerror("Unable to download build config from master site %s, aborting." % msite)
418 :    
419 :     # sets up 'mastertrees' and 'builds' dicts
420 :     gkb_parsexml('gkb.xml')
421 :    
422 :     for bdict in builds.values():
423 :     myworkdir="%s/%s" % (workdir,bdict["mastertree"])
424 :     bdict["workdir"]=myworkdir
425 :    
426 :     # for now just call the build
427 :     gkb_build(root, bdict)
428 :    
429 :     endtime=getoutput("date +'%R:%S %Z'")
430 :    
431 :     print "GKB finished %s %s" % (today,endtime)
432 :    
433 :     # and finally, call the mainloop to execute
434 :     main()

Tobias McNulty

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help