Opt arg parsing for gpg and createrepo.
[build.git] / vbuild-nightly.sh
1 #!/bin/bash
2 REVISION=$(echo '$Revision$' | sed -e 's,\$,,g' -e 's,^\w*:\s,,' )
3
4 COMMANDPATH=$0
5 COMMAND=$(basename $0)
6
7 # default values, tunable with command-line options
8 DEFAULT_FCDISTRO=f8
9 DEFAULT_PLDISTRO=planetlab
10 DEFAULT_PERSONALITY=linux32
11 DEFAULT_BASE="@DATE@--@PLDISTRO@-@FCDISTRO@-@PERSONALITY@"
12 DEFAULT_SVNPATH="http://svn.planet-lab.org/svn/build/trunk"
13 # TESTSVNPATH to be computed from the -tags.mk file - no default anymore
14 DEFAULT_TESTCONFIG="default"
15 DEFAULT_IFNAME=eth0
16
17 # web publishing results
18 DEFAULT_WEBPATH="/build/@PLDISTRO@/"
19
20 # default gpg path used in signing yum repo
21 DEFAULT_GPGPATH="/etc/planetlab"
22 # default email to use in gpg secring
23 DEFAULT_GPGUID="root@$( /bin/hostname )"
24
25 # for the test part
26 TESTBUILDURL="http://build.one-lab.org/"
27 TESTBOXSSH=root@testbox.one-lab.org
28 ####################
29 # assuming vserver runs in UTC
30 DATE=$(date +'%Y.%m.%d')
31
32 # temporary - wrap a quick summary of suspicious stuff
33 # this is to focus on installation that go wrong
34 # use with care, a *lot* of other things can go bad as well
35 function summary () {
36     from=$1; shift
37     echo "******************** BEG SUMMARY" 
38     python - $from <<EOF
39 #!/usr/bin/env python
40 # read a full log and tries to extract the interesting stuff
41
42 import sys,re
43 m_show_line=re.compile(".* BEG (RPM|VSERVER).*|.*'boot'.*|\* .*|.*is not installed.*")
44 m_installing_any=re.compile('\r  (Installing:[^\]]*]) ')
45 m_installing_err=re.compile('\r  (Installing:[^\]]*])(..+)')
46 m_installing_end=re.compile('Installed:.*')
47 m_installing_doc1=re.compile("(.*)install-info: No such file or directory for /usr/share/info/\S+(.*)")
48 m_installing_doc2=re.compile("(.*)grep: /usr/share/info/dir: No such file or directory(.*)")
49
50 def summary (filename):
51
52     try:
53         if filename=="-":
54             filename="stdin"
55             f=sys.stdin
56         else:
57             f=open(filename)
58         echo=False
59         for line in f.xreadlines():
60             # first off : discard warnings related to doc
61             if m_installing_doc1.match(line):
62                 (begin,end)=m_installing_doc1.match(line).groups()
63                 line=begin+end
64             if m_installing_doc2.match(line):
65                 (begin,end)=m_installing_doc2.match(line).groups()
66                 line=begin+end
67             # unconditionnally show these lines
68             if m_show_line.match(line):
69                 print '>>>',line,
70             # an 'installing' line with messages afterwards : needs to be echoed
71             elif m_installing_err.match(line):
72                 (installing,error)=m_installing_err.match(line).groups()
73                 print '>>>',installing
74                 print '>>>',error
75                 echo=True
76             # closing an 'installing' section
77             elif m_installing_end.match(line):
78                 echo=False
79             # any 'installing' line
80             elif m_installing_any.match(line):
81                 if echo: 
82                     installing=m_installing_any.match(line).group(1)
83                     print '>>>',installing
84                 echo=False
85             # print lines when echo is true
86             else:
87                 if echo: print '>>>',line,
88         f.close()
89     except:
90         print 'Failed to analyze',filename
91
92 for arg in sys.argv[1:]:
93     summary(arg)
94 EOF
95     echo "******************** END SUMMARY" 
96 }
97
98
99 # Notify recipient of failure or success, manage various stamps 
100 function failure() {
101     set -x
102     WEBLOG=${WEBPATH}/${BASE}.log.txt
103     mkdir -p ${WEBPATH}
104     cp $LOG ${WEBLOG}
105     summary $LOG >> ${WEBLOG}
106     (echo -n "============================== $COMMAND: failure at " ; date ; tail -c 30k $WEBLOG) > ${WEBLOG}.ko
107     if [ -n "$MAILTO" ] ; then
108         tail -c 30k ${WEBLOG} | mail -s "Failures for build ${BASE}" $MAILTO
109     fi
110     exit 1
111 }
112
113 function success () {
114     set -x
115     WEBLOG=${WEBPATH}/${BASE}.log.txt
116     mkdir -p ${WEBPATH}
117     cp $LOG ${WEBLOG}
118     summary $LOG >> ${WEBLOG}
119     if [ -n "$DO_TEST" ] ; then
120         echo "Successfully built and tested - see testlogs for details" > ${WEBLOG}.pass
121         rm -f ${WEBLOG}.ok
122     else
123         echo "Successfully built"> ${WEBLOG}.ok
124     fi
125     if [ -n "$MAILTO" ] ; then
126         (echo "$PLDISTRO ($BASE) build for $FCDISTRO completed on $(date)" ) | mail -s "Successful build for ${BASE}" $MAILTO
127     fi
128     exit 0
129 }
130
131 # run in the vserver - do not manage success/failure, will be done from the root ctx
132 function build () {
133     set -x
134     set -e
135
136     echo -n "============================== Starting $COMMAND:build on "
137     date
138
139     cd /build
140   # if TAGSRELEASE specified : update PLDISTROTAGS with this tag
141     if [ -n "$TAGSRELEASE" ] ; then
142         svn up -r $TAGSRELEASE $PLDISTROTAGS
143     fi
144
145     show_env
146     
147     echo "Running make IN $(pwd)"
148     
149     # stuff our own variable settings
150     MAKEVARS=("PLDISTRO=${PLDISTRO}" "${MAKEVARS[@]}")
151     MAKEVARS=("PLDISTROTAGS=${PLDISTROTAGS}" "${MAKEVARS[@]}")
152     MAKEVARS=("NIGHTLY_BASE=${BASE}" "${MAKEVARS[@]}")
153     MAKEVARS=("NIGHTLY_PERSONALITY=${PERSONALITY}" "${MAKEVARS[@]}")
154     MAKEVARS=("build-SVNPATH=${SVNPATH}" "${MAKEVARS[@]}")
155
156     # stage1
157     make -C /build $DRY_RUN "${MAKEVARS[@]}" stage1=true 
158     # versions
159     make -C /build $DRY_RUN "${MAKEVARS[@]}" versions
160     # store testsvnpath
161     make -C /build $DRY_RUN "${MAKEVARS[@]}" stage1=true testsvnpath
162     # actual stuff
163     make -C /build $DRY_RUN "${MAKEVARS[@]}" $MAKETARGETS
164
165 }
166
167 # this was formerly run in the myplc-devel chroot but now is run in the root context,
168 # this is so that the .ssh config gets done manually, and once and for all
169 function runtest () {
170     set -x
171     set -e
172     trap failure ERR INT
173
174     echo -n "============================== Starting $COMMAND:runtest on $(date)"
175
176     # where to find TESTSVNPATH
177     stamp=/vservers/$BASE/build/testsvnpath
178     if [ ! -f $stamp ] ; then
179         echo "$COMMAND: Cannot figure TESTSVNPATH from missing $stamp"
180         failure
181         exit 1
182     fi
183     TESTSVNPATH=$(cat $stamp)
184     # use only this pat of the tests right now
185     TESTSVNPATH=${TESTSVNPATH}/system
186
187     ### the URL to the RPMS/<arch> location
188     url=""
189     for a in i386 x86_64; do
190         archdir=/vservers/$BASE/build/RPMS/$a
191         if [ -d $archdir ] ; then
192             url=$(echo $archdir | sed -e "s,/vservers/$BASE/build,${TESTBUILDURL}${PLDISTRO}/${BASE},")
193             break
194         fi
195     done
196
197     if [ -z "$url" ] ; then
198         echo "$COMMAND: Cannot locate arch URL for testing"
199         failure
200         exit 1
201     fi
202
203     # test directory name on test box
204     testdir=${BASE}
205     # clean it
206     ssh -n ${TESTBOXSSH} rm -rf ${testdir}
207     # check it out
208     ssh -n ${TESTBOXSSH} svn co ${TESTSVNPATH} ${testdir}
209     # invoke test on testbox - pass url and build url - so the tests can use vtest-init-vserver.sh
210     configs=""
211     for config in ${TESTCONFIG} ; do
212         configs="$configs --config $config"
213     done
214     
215     # need to proceed despite of set -e
216     success=true
217     ssh 2>&1 -n ${TESTBOXSSH} ${testdir}/runtest --build ${SVNPATH} --url ${url} $configs --all || success=
218
219     # gather logs in the vserver
220     mkdir -p /vservers/$BASE/build/testlogs
221     ssh 2>&1 -n ${TESTBOXSSH} tar -C ${testdir}/logs -cf - . | tar -C /vservers/$BASE/build/testlogs -xf - || true
222     # push them to the build web
223     rsync --archive --delete /vservers/$BASE/build/testlogs/ $WEBPATH/$BASE/testlogs/
224     chmod -R a+r $WEBPATH/$BASE/testlogs/
225
226     if [ -z "$success" ] ; then
227         failure
228     fi
229     
230     echo -n "============================== End $COMMAND:runtest on $(date)"
231 }
232
233 function show_env () {
234     set +x
235     echo FCDISTRO=$FCDISTRO
236     echo PLDISTRO=$PLDISTRO
237     echo BASE=$BASE
238     echo SVNPATH=$SVNPATH
239     echo MAKEVARS="${MAKEVARS[@]}"
240     echo DRY_RUN="$DRY_RUN"
241     echo PLDISTROTAGS="$PLDISTROTAGS"
242     echo TAGSRELEASE="$TAGSRELEASE"
243     echo -n "(might be unexpanded)"
244     echo WEBPATH="$WEBPATH"
245     if [ -d /vservers ] ; then
246         echo PLDISTROTAGS="$PLDISTROTAGS"
247     else
248         echo "XXXXXXXXXXXXXXXXXXXX Contents of tags definition file /build/$PLDISTROTAGS"
249         cat /build/$PLDISTROTAGS
250         echo "XXXXXXXXXXXXXXXXXXXX end tags definition"
251     fi
252     set -x
253 }
254
255 function usage () {
256     echo "Usage: $COMMAND [option] make-targets"
257     echo "This is $REVISION"
258     echo "Supported options"
259     echo " -f fcdistro - defaults to $DEFAULT_FCDISTRO"
260     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
261     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
262     echo " -b base - defaults to $DEFAULT_BASE"
263     echo "    @NAME@ replaced as appropriate"
264     echo " -t pldistrotags - defaults to \${PLDISTRO}-tags.mk"
265     echo " -r tagsrelease - a release number that refers to PLDISTROTAGS - defaults to HEAD"
266     echo " -s svnpath - where to fetch the build module"
267     echo " -c testconfig - defaults to $DEFAULT_TESTCONFIG"
268     echo " -w webpath - defaults to $DEFAULT_WEBPATH"
269     echo " -y create (and sign) yum repo in webpath"
270     echo " -g path to gpg secring used to sign rpms.  Defaults to $DEFAULT_GPGPATH" 
271     echo " -u gpg email used in secring. Defaults to $DEFAULT_GPGUID"
272     echo " -m mailto - no default"
273     echo " -O : overwrite - re-run in base directory, do not re-create vserver"
274     echo " -B : run build only"
275     echo " -T : run test only"
276     echo " -n dry-run : -n passed to make - vserver gets created though - no mail sent"
277     echo " -v : be verbose"
278     echo " -7 : uses weekday-@FCDISTRO@ as base"
279     echo " -a makevar=value - space in values are not supported"
280     echo " -i ifname - defaults to $DEFAULT_IFNAME - used to determine local IP"
281     exit 1
282 }
283
284 function main () {
285
286     set -e
287
288     # parse arguments
289     MAKEVARS=()
290     DRY_RUN=
291     DO_BUILD=true
292     DO_TEST=true
293     while getopts "f:d:p:b:t:r:s:x:c:w:y:g:um:OBTnv7a:i:" opt ; do
294         case $opt in
295             f) FCDISTRO=$OPTARG ;;
296             d) PLDISTRO=$OPTARG ;;
297             p) PERSONALITY=$OPTARG ;;
298             b) BASE=$OPTARG ;;
299             t) PLDISTROTAGS=$OPTARG ;;
300             r) TAGSRELEASE=$OPTARG ;;
301             s) SVNPATH=$OPTARG ;;
302             c) TESTCONFIG="$TESTCONFIG $OPTARG" ;;
303             w) WEBPATH=$OPTARG ;;
304         y) MKYUMREPO=$OPTARG;;
305         g) GPGPATH=$OPTARG;;
306         u) GPGUID=$OPTARG;;
307             m) MAILTO=$OPTARG ;;
308             O) OVERWRITEMODE=true ;;
309             B) DO_TEST= ;;
310             T) DO_BUILD= ; OVERWRITEMODE=true ;;
311             n) DRY_RUN="-n" ;;
312             v) set -x ;;
313             7) BASE="$(date +%a|tr A-Z a-z)-@FCDISTRO@" ;;
314             a) MAKEVARS=(${MAKEVARS[@]} "$OPTARG") ;;
315             i) IFNAME=$OPTARG ;;
316             h|*) usage ;;
317         esac
318     done
319         
320     # preserve options for passing them again later, together with expanded base
321     declare -a options
322     toshift=$(($OPTIND - 1))
323     arg=1; while [ $arg -le $toshift ] ; do options=(${options[@]} "$1") ; shift; arg=$(($arg+1)) ; done
324
325     MAKETARGETS="$@"
326     
327     # set defaults
328     [ -z "$FCDISTRO" ] && FCDISTRO=$DEFAULT_FCDISTRO
329     [ -z "$PLDISTRO" ] && PLDISTRO=$DEFAULT_PLDISTRO
330     [ -z "$PERSONALITY" ] && PERSONALITY=$DEFAULT_PERSONALITY
331     [ -z "$PLDISTROTAGS" ] && PLDISTROTAGS="${PLDISTRO}-tags.mk"
332     [ -z "$BASE" ] && BASE="$DEFAULT_BASE"
333     [ -z "$WEBPATH" ] && WEBPATH="$DEFAULT_WEBPATH"
334     [ -z "$IFNAME" ] && IFNAME="$DEFAULT_IFNAME"
335     [ -z "$SVNPATH" ] && SVNPATH="$DEFAULT_SVNPATH"
336     [ -z "$TESTCONFIG" ] && TESTCONFIG="$DEFAULT_TESTCONFIG"
337
338     [ -n "$DRY_RUN" ] && MAILTO=""
339         
340     ### set BASE from DISTRO, if unspecified
341     sedargs="-e s,@DATE@,${DATE},g -e s,@FCDISTRO@,${FCDISTRO},g -e s,@PLDISTRO@,${PLDISTRO},g -e s,@PERSONALITY@,${PERSONALITY},g"
342     BASE=$(echo ${BASE} | sed $sedargs)
343     WEBPATH=$(echo ${WEBPATH} | sed $sedargs)
344
345     if [ ! -d /vservers ] ; then
346         # in the vserver
347         echo "==================== Within vserver BEG $(date)"
348         build
349         echo "==================== Within vserver END $(date)"
350
351     else
352         trap failure ERR INT
353         # we run in the root context : 
354         # (*) create or check for the vserver to use
355         # (*) copy this command in the vserver
356         # (*) invoke it
357         
358         if [ -n "$OVERWRITEMODE" ] ; then
359             ### Re-use a vserver (finish an unfinished build..)
360             if [ ! -d /vservers/${BASE} ] ; then
361                 echo $COMMAND : cannot find vserver $BASE
362                 exit 1
363             fi
364             # manage LOG - beware it might be a symlink so nuke it first
365             LOG=/vservers/${BASE}.log.txt
366             rm -f $LOG
367             exec > $LOG 2>&1
368             set -x
369             echo "XXXXXXXXXX $COMMAND: using existing vserver $BASE" $(date)
370             show_env
371             # start in case e.g. we just rebooted
372             vserver ${BASE} start || :
373             # update build
374             vserver ${BASE} exec svn update /build
375         else
376             # create vserver: check it does not exist yet
377             i=
378             while [ -d /vservers/${BASE}${i} ] ; do
379                 # we name subsequent builds <base>-n<i> so the logs and builds get sorted properly
380                 [ -z ${i} ] && BASE=${BASE}-n
381                 i=$((${i}+1))
382                 if [ $i -gt 100 ] ; then
383                     echo "$COMMAND: Failed to create build vserver /vservers/${BASE}${i}"
384                     exit 1
385                 fi
386             done
387             BASE=${BASE}${i}
388             # need update
389             # manage LOG - beware it might be a symlink so nuke it first
390             LOG=/vservers/${BASE}.log.txt
391             rm -f $LOG
392             exec > $LOG 2>&1 
393             set -x
394             echo "XXXXXXXXXX $COMMAND: creating vserver $BASE" $(date)
395             show_env
396
397             ### extract the whole build - much simpler
398             tmpdir=/tmp/$COMMAND-$$
399             svn export $SVNPATH $tmpdir
400             # Create vserver
401             cd $tmpdir
402             ./vbuild-init-vserver.sh -f ${FCDISTRO} -d ${PLDISTRO} -p ${PERSONALITY} -i ${IFNAME} ${BASE} 
403             # cleanup
404             cd -
405             rm -rf $tmpdir
406             # Extract build again - in the vserver
407             vserver ${BASE} exec svn checkout ${SVNPATH} /build
408         fi
409         echo "XXXXXXXXXX $COMMAND: preparation of vserver $BASE done" $(date)
410
411         # The log inside the vserver contains everything
412         LOG2=/vservers/${BASE}/log.txt
413         (echo "==================== BEG VSERVER Transcript of vserver creation" ; \
414          cat $LOG ; \
415          echo "==================== END VSERVER Transcript of vserver creation" ; \
416          echo "xxxxxxxxxx Messing with logs, symlinking $LOG2 to $LOG" ) >> $LOG2
417         ### not too nice : nuke the former log, symlink it to the new one
418         rm $LOG; ln -s $LOG2 $LOG
419         LOG=$LOG2
420         # redirect log again
421         exec >> $LOG 2>&1 
422
423         if [ -n "$DO_BUILD" ] ; then 
424
425             cp $COMMANDPATH /vservers/${BASE}/build/
426
427             # invoke this command in the vserver for building (-T)
428             vserver ${BASE} exec chmod +x /build/$COMMAND
429             vserver ${BASE} exec /build/$COMMAND "${options[@]}" -b "${BASE}" $MAKETARGETS
430         fi
431
432         # publish to the web so runtest can find them
433         rm -rf $WEBPATH/$BASE ; mkdir -p $WEBPATH/$BASE/{RPMS,SRPMS}
434         rsync --archive --delete --verbose /vservers/$BASE/build/RPMS/ $WEBPATH/$BASE/RPMS/
435         rsync --archive --delete --verbose /vservers/$BASE/build/SRPMS/ $WEBPATH/$BASE/SRPMS/
436         # publish myplc-release
437         rsync --verbose /vservers/$BASE/build/myplc-release $WEBPATH/$BASE
438
439     # create yum repo and sign packages.
440     if [ -n $MKYUMREPO ] ; then
441         echo "Signing signing node packages"
442
443         ### availability of repo indexing tools
444         # old one - might be needed for old-style nodes
445         type -p yum-arch > /dev/null && have_yum_arch="true"
446         # new one
447         type -p createrepo > /dev/null && have_createrepo="true"
448
449         repository=$WEBPATH/$BASE/RPMS/
450         # the rpms that need signing
451         new_rpms=
452         # and the corresponding stamps
453         new_stamps=
454         # is there a need to refresh yum metadata
455         need_yum_arch=
456         need_createrepo=
457
458         # right after installation, no package is present
459         # but we still need to create index 
460         [ -n "$have_yum_arch" -a ! -f $repository/headers/header.info ] && need_yum_arch=true
461         [ -n "$have_createrepo" -a ! -f $repository/repodata/repomd.xml ] && need_createrepo=true
462
463         for package in $(find $repository/ -name '*.rpm') ; do
464             stamp=$repository/signed-stamps/$(basename $package).signed
465             # If package is newer than signature stamp
466             if [ $package -nt $stamp ] ; then
467                 new_rpms="$new_rpms $package"
468                 new_stamps="$new_stamps $stamp"
469             fi
470             # Or than yum-arch headers
471             [ -n "$have_yum_arch" ] && [ $package -nt $repository/headers/header.info ] && need_yum
472 _arch=true
473             # Or than createrepo database
474             [ -n "$have_createrepo" ] && [ $package -nt $repository/repodata/repomd.xml ] && need_c
475 reaterepo=true
476         done
477
478         if [ -n "$new_rpms" ] ; then
479             # Create a stamp once the package gets signed
480             mkdir $repository/signed-stamps 2> /dev/null
481
482             # Sign RPMS. setsid detaches rpm from the terminal,
483             # allowing the (hopefully blank) GPG password to be
484             # entered from stdin instead of /dev/tty.
485             echo | setsid rpm \
486                 --define "_signature gpg" \
487                 --define "_gpg_path $GPGPATH" \
488                 --define "_gpg_name $GPGUID" \
489                 --resign $new_rpms && touch $new_stamps
490             check
491         fi
492
493          # Update repository index / yum metadata. 
494
495         if [ -n "$need_yum_arch" ] ; then
496             # yum-arch sometimes leaves behind
497             # .oldheaders and .olddata directories accidentally.
498             rm -rf $repository/{.oldheaders,.olddata}
499             yum-arch $repository
500             check
501         fi
502
503         if [ -n "$need_createrepo" ] ; then
504             if [ -f $repository/yumgroups.xml ] ; then
505                 createrepo --quiet -g yumgroups.xml $repository
506             else
507                 createrepo --quiet $repository
508             fi
509             check
510         fi
511
512     fi
513
514         if [ -n "$DO_TEST" ] ; then 
515             runtest
516         fi
517
518         success 
519         
520     fi
521
522 }  
523
524 ##########
525 main "$@"