run_log retcod now is
[build.git] / lbuild-nightly.sh
1 #!/bin/bash
2
3 COMMANDPATH=$0
4 COMMAND=$(basename $0)
5
6 # old guests have e.g. mount in /bin but this is no longer part of 
7 # the standard PATH in recent hosts after usrmove, so let's keep it simple
8 export PATH=$PATH:/bin:/sbin
9
10 # default values, tunable with command-line options
11 DEFAULT_FCDISTRO=f20
12 DEFAULT_PLDISTRO=planetlab
13 DEFAULT_PERSONALITY=linux64
14 DEFAULT_BASE="@DATE@--@PLDISTRO@-@FCDISTRO@-@PERSONALITY@"
15 DEFAULT_BUILD_SCM_URL="git://git.onelab.eu/build"
16
17 # default gpg path used in signing yum repo
18 DEFAULT_GPGPATH="/etc/planetlab"
19 # default email to use in gpg secring
20 DEFAULT_GPGUID="root@$( /bin/hostname )"
21
22 DEFAULT_TESTCONFIG="default"
23 # for passing args to run_log
24 RUN_LOG_EXTRAS=""
25
26 # for publishing results, and the tests settings
27 x=$(hostname)
28 y=$(hostname|sed -e s,inria,,)
29 # INRIA defaults
30 if [ "$x" != "$y" ] ; then
31     DEFAULT_WEBPATH="/build/@PLDISTRO@/"
32     DEFAULT_TESTBUILDURL="http://build.onelab.eu/"
33     # this is where the buildurl is pointing towards
34     DEFAULT_WEBROOT="/build/"
35     DEFAULT_TESTMASTER="testmaster.onelab.eu"
36 else
37     DEFAULT_WEBPATH="/build/@FCDISTRO@/@PLDISTRO@/"
38     DEFAULT_TESTBUILDURL="http://build.planet-lab.org/"
39     # this is where the buildurl is pointing towards
40     DEFAULT_WEBROOT="/build/"
41     DEFAULT_TESTMASTER="manager.test.planet-lab.org"
42 fi    
43
44 ####################
45 # assuming vm runs in UTC
46 DATE=$(date +'%Y.%m.%d')
47 BUILD_BEG=$(date +'%H:%M')
48 BUILD_BEG_S=$(date +'%s')
49
50 # still using /vservers for legacy reasons
51 # as far as the build & test infra, we could adopt a new name
52 # but the PL code still uses this name for now, so let's keep it simple
53 function rootdir () {
54     slice=$1; shift
55     echo /vservers/$slice
56 }
57 function logfile () {
58     slice=$1; shift
59     echo /vservers/$slice.log.txt
60 }
61
62 # wrap a quick summary of suspicious stuff
63 # this is to focus on installation that go wrong
64 # use with care, a *lot* of other things can go bad as well
65 function summary () {
66     from=$1; shift
67     echo "******************** BEG SUMMARY" 
68     python - $from <<EOF
69 #!/usr/bin/env python
70 # read a full log and tries to extract the interesting stuff
71
72 import sys,re
73 m_show_line=re.compile(".* (BEG|END) (RPM|LXC).*|.*'boot'.*|\* .*| \* .*|.*is not installed.*|.*PROPFIND.*|.* (BEG|END).*:run_log.*|.* Within LXC (BEG|END) .*|.* MAIN (BEG|END).*")
74 m_installing_any=re.compile('\r  (Installing:[^\]]*]) ')
75 m_installing_err=re.compile('\r  (Installing:[^\]]*])(..+)')
76 m_installing_end=re.compile('Installed:.*')
77 m_installing_doc1=re.compile("(.*)install-info: No such file or directory for /usr/share/info/\S+(.*)")
78 m_installing_doc2=re.compile("(.*)grep: /usr/share/info/dir: No such file or directory(.*)")
79
80 def summary (filename):
81
82     try:
83         if filename=="-":
84             filename="stdin"
85             f=sys.stdin
86         else:
87             f=open(filename)
88         echo=False
89         for line in f.xreadlines():
90             # first off : discard warnings related to doc
91             if m_installing_doc1.match(line):
92                 (begin,end)=m_installing_doc1.match(line).groups()
93                 line=begin+end
94             if m_installing_doc2.match(line):
95                 (begin,end)=m_installing_doc2.match(line).groups()
96                 line=begin+end
97             # unconditionnally show these lines
98             if m_show_line.match(line):
99                 print '>>>',line,
100             # an 'installing' line with messages afterwards : needs to be echoed
101             elif m_installing_err.match(line):
102                 (installing,error)=m_installing_err.match(line).groups()
103                 print '>>>',installing
104                 print '>>>',error
105                 echo=True
106             # closing an 'installing' section
107             elif m_installing_end.match(line):
108                 echo=False
109             # any 'installing' line
110             elif m_installing_any.match(line):
111                 if echo: 
112                     installing=m_installing_any.match(line).group(1)
113                     print '>>>',installing
114                 echo=False
115             # print lines when echo is true
116             else:
117                 if echo: print '>>>',line,
118         f.close()
119     except:
120         print 'Failed to analyze',filename
121
122 for arg in sys.argv[1:]:
123     summary(arg)
124 EOF
125     echo "******************** END SUMMARY" 
126 }
127
128 ### we might build on a box other than the actual web server
129 # utilities for handling the pushed material (rpms, logfiles, ...)
130 function webpublish_misses_dir () { ssh root@${WEBHOST}  "bash -c \"test \! -d $1\"" ; }
131 function webpublish () { ssh root@${WEBHOST} "$@" ; }
132 function webpublish_cp_local_to_remote () { scp $1 root@${WEBHOST}:$2 ; }
133 function webpublish_cp_stdin_to_file () { ssh root@${WEBHOST} cat \> $1; }
134 function webpublish_append_stdin_to_file () { ssh root@${WEBHOST} cat \>\> $1; }
135 # provide remote dir as first argument, so any number of local files can be passed next
136 function webpublish_rsync_dir () { rsync --archive --delete $VERBOSE $2 root@${WEBHOST}:$1 ; }
137 function webpublish_rsync_files () {
138     remote="$1"; shift
139     rsync --archive $VERBOSE "$@" root@${WEBHOST}:"$remote" ;
140 }
141
142 # Notify recipient of failure or success, manage various stamps 
143 function failure() {
144     set -x
145     # early stage ? - let's not create /build/@PLDISTRO@
146     if test -z "$WEBLOG" ; then
147         WEBHOST=$(hostname)
148         WEBPATH=/tmp
149         WEBBASE=/tmp/lbuild-early-$(date +%Y-%m-%d)
150         WEBLOG=/tmp/lbuild-early-$(date +%Y-%m-%d).log.txt
151     fi
152     webpublish mkdir -p $WEBBASE ||:
153     webpublish_cp_local_to_remote $LOG $WEBLOG ||:
154     summary $LOG | webpublish_append_stdin_to_file $WEBLOG ||:
155     (echo -n "============================== $COMMAND: failure at " ; date ; \
156         webpublish tail --lines=1000 $WEBLOG) | \
157         webpublish_cp_stdin_to_file $WEBBASE.ko ||:
158     if [ -n "$MAILTO" ] ; then
159         ( \
160             echo "Subject: KO ${BASE} ${MAIL_SUBJECT}" ; \
161             echo "To: $MAILTO" ; \
162             echo "see build results at        $WEBBASE_URL" ; \
163             echo "including full build log at $WEBBASE_URL/log.txt" ; \
164             echo "and complete test logs at   $WEBBASE_URL/testlogs" ; \
165             echo "........................................" ; \
166             webpublish tail --lines=1000 $WEBLOG ) | \
167             sendmail $MAILTO
168     fi
169     exit 1
170 }
171
172 function success () {
173     set -x
174     # early stage ? - let's not create /build/@PLDISTRO@
175     if test -z "$WEBLOG" ; then
176         WEBHOST=$(hostname)
177         WEBPATH=/tmp
178         WEBLOG=/tmp/lbuild-early-$(date +%Y-%m-%d).log.txt
179     fi
180     webpublish mkdir -p $WEBBASE
181     webpublish_cp_local_to_remote $LOG $WEBLOG
182     summary $LOG | webpublish_append_stdin_to_file $WEBLOG
183     if [ -n "$DO_TEST" ] ; then
184         short_message="PASS"
185         ext="pass"
186         if [ -n "$IGNORED" ] ; then short_message="PASS/WARN"; ext="warn"; fi
187         ( \
188             echo "Successfully built and tested" ; \
189             echo "see build results at        $WEBBASE_URL" ; \
190             echo "including full build log at $WEBBASE_URL/log.txt" ; \
191             echo "and complete test logs at   $WEBBASE_URL/testlogs" ; \
192             [ -n "$IGNORED" ] && echo "WARNING: some tests steps failed but were ignored - see trace file" ; \
193             ) | webpublish_cp_stdin_to_file $WEBBASE.$ext
194         webpublish rm -f $WEBBASE.pkg-ok $WEBBASE.ko
195     else
196         short_message="PKGOK"
197         ( \
198             echo "Successful package-only build, no test requested" ; \
199             echo "see build results at        $WEBBASE_URL" ; \
200             echo "including full build log at $WEBBASE_URL/log.txt" ; \
201             ) | webpublish_cp_stdin_to_file $WEBBASE.pkg-ok
202         webpublish rm -f $WEBBASE.ko
203     fi
204     BUILD_END=$(date +'%H:%M')
205     BUILD_END_S=$(date +'%s')
206     if [ -n "$MAILTO" ] ; then
207         ( \
208             echo "Subject: $short_message ${BASE} ${MAIL_SUBJECT}" ; \
209             echo "To: $MAILTO" ; \
210             echo "$PLDISTRO ($BASE) build for $FCDISTRO completed on $(date)" ; \
211             echo "see build results at        $WEBBASE_URL" ; \
212             echo "including full build log at $WEBBASE_URL/log.txt" ; \
213             [ -n "$DO_TEST" ] && echo "and complete test logs at   $WEBBASE_URL/testlogs" ; \
214             [ -n "$IGNORED" ] && echo "WARNING: some tests steps failed but were ignored - see trace file" ; \
215             echo "BUILD TIME: begin $BUILD_BEG -- end $BUILD_END -- duration $(($BUILD_END_S-$BUILD_BEG_S))" ; \
216             ) | sendmail $MAILTO
217     fi
218     # XXX For some reason, we haven't been getting this email for successful builds. If this sleep
219     # doesn't fix the problem, I'll remove it -- Sapan.
220     sleep 5
221     exit 0
222 }
223
224 ##############################
225 # manage root / container contexts
226 function in_root_context () {
227     rpm -q libvirt > /dev/null 
228 }
229
230 # run in the vm - do not manage success/failure, will be done from the root ctx
231 function build () {
232     set -x
233     set -e
234
235     echo -n "============================== Starting $COMMAND:build on "
236     date
237
238     cd /build
239     show_env
240     
241     echo "Running make IN $(pwd)"
242     
243     # stuff our own variable settings
244     MAKEVARS=("build-GITPATH=${BUILD_SCM_URL}" "${MAKEVARS[@]}")
245     MAKEVARS=("PLDISTRO=${PLDISTRO}" "${MAKEVARS[@]}")
246     MAKEVARS=("PLDISTROTAGS=${PLDISTROTAGS}" "${MAKEVARS[@]}")
247     MAKEVARS=("PERSONALITY=${PERSONALITY}" "${MAKEVARS[@]}")
248     MAKEVARS=("MAILTO=${MAILTO}" "${MAKEVARS[@]}")
249     MAKEVARS=("WEBPATH=${WEBPATH}" "${MAKEVARS[@]}")
250     MAKEVARS=("TESTBUILDURL=${TESTBUILDURL}" "${MAKEVARS[@]}")
251     MAKEVARS=("WEBROOT=${WEBROOT}" "${MAKEVARS[@]}")
252
253     MAKEVARS=("BASE=${BASE}" "${MAKEVARS[@]}")
254
255     # initialize latex
256     /build/latex-first-run.sh || :
257
258     # stage1
259     make -C /build $DRY_RUN "${MAKEVARS[@]}" stage1=true 
260     # versions
261     make -C /build $DRY_RUN "${MAKEVARS[@]}" versions
262     # actual stuff
263     make -C /build $DRY_RUN "${MAKEVARS[@]}" "${MAKETARGETS[@]}"
264
265 }
266
267 # this was formerly run in the myplc-devel chroot but now is run in the root context,
268 # this is so that the .ssh config gets done manually, and once and for all
269 function run_log () {
270     set -x
271     set -e
272     trap failure ERR INT
273
274     echo "============================== BEG $COMMAND:run_log on $(date)"
275
276     ### the URL to the RPMS/<arch> location
277     # f12 now has everything in i686; try i386 first as older fedoras have both
278     url=""
279     for a in i386 i686 x86_64; do
280         archdir=$(rootdir $BASE)/build/RPMS/$a
281         if [ -d $archdir ] ; then
282             # where was that installed
283             url=$(echo $archdir | sed -e "s,$(rootdir $BASE)/build,${WEBPATH}/${BASE},")
284             url=$(echo $url | sed -e "s,${WEBROOT},${TESTBUILDURL},")
285             break
286         fi
287     done
288
289     if [ -z "$url" ] ; then
290         echo "$COMMAND: Cannot locate arch URL for testing"
291         failure
292         exit 1
293     fi
294
295     testmaster_ssh="root@${TESTMASTER}"
296
297     # test directory name on test box
298     testdir=${BASE}
299
300     # clean it
301     ssh -n ${testmaster_ssh} rm -rf ${testdir} ${testdir}.git
302
303     # check it out in the build
304     virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "make -C /build tests-module"
305     
306     # push it onto the testmaster - just the 'system' subdir is enough
307     rsync --verbose --archive $(rootdir $BASE)/build/MODULES/tests/system/ ${testmaster_ssh}:${BASE}
308     # toss the build in the bargain, so the tests don't need to mess with extracting it
309     rsync --verbose --archive $(rootdir $BASE)/build/MODULES/build ${testmaster_ssh}:${BASE}/
310
311     # invoke test on testbox - pass url and build url - so the tests can use vtest-init-lxc.sh
312     run_log_env="-p $PERSONALITY -d $PLDISTRO -f $FCDISTRO"
313
314     # temporarily turn off set -e
315     set +e
316     ssh 2>&1 -n ${testmaster_ssh} ${testdir}/run_log --build ${BUILD_SCM_URL} --url ${url} $run_log_env $RUN_LOG_EXTRAS $VERBOSE --all; retcod=$?
317     set -e
318     
319     # interpret retcod of TestMain.py; 2 means there were ignored steps that failed
320     echo "received from run_log" $retcod
321     case $retcod in
322         0) success=true; IGNORED="" ;;
323         2) success=true; IGNORED=true ;;
324         *) success="";   IGNORED="" ;; 
325     esac
326
327     # gather logs in the build vm
328     mkdir -p $(rootdir $BASE)/build/testlogs
329     rsync --verbose --archive ${testmaster_ssh}:$BASE/logs/ $(rootdir $BASE)/build/testlogs
330     # push them to the build web
331     chmod -R a+r $(rootdir $BASE)/build/testlogs/
332     webpublish_rsync_dir $WEBPATH/$BASE/testlogs/ $(rootdir $BASE)/build/testlogs/
333
334     echo  "============================== END $COMMAND:run_log on $(date)"
335
336     if [ -z "$success" ] ; then
337         echo "Tests have failed - bailing out"
338         failure
339     fi
340     
341 }
342
343 # this part won't work if WEBHOST does not match the local host
344 # would need to be made webpublish_* compliant
345 # but do we really need this feature anyway ?
346 function sign_node_packages () {
347
348     echo "Signing node packages"
349     
350     need_createrepo=""
351
352     repository=$WEBPATH/$BASE/RPMS/
353     # the rpms that need signing
354     new_rpms=
355     # and the corresponding stamps
356     new_stamps=
357
358     for package in $(find $repository/ -name '*.rpm') ; do
359         stamp=$repository/signed-stamps/$(basename $package).signed
360         # If package is newer than signature stamp
361         if [ $package -nt $stamp ] ; then
362             new_rpms="$new_rpms $package"
363             new_stamps="$new_stamps $stamp"
364         fi
365         # Or than createrepo database
366         [ $package -nt $repository/repodata/repomd.xml ] && need_createrepo=true
367     done
368
369     if [ -n "$new_rpms" ] ; then
370         # Create a stamp once the package gets signed
371         mkdir $repository/signed-stamps 2> /dev/null
372         
373         # Sign RPMS. setsid detaches rpm from the terminal,
374         # allowing the (hopefully blank) GPG password to be
375         # entered from stdin instead of /dev/tty.
376         echo | setsid rpm \
377             --define "_signature gpg" \
378             --define "_gpg_path $GPGPATH" \
379             --define "_gpg_name $GPGUID" \
380             --resign $new_rpms && touch $new_stamps
381     fi
382
383      # Update repository index / yum metadata. 
384     if [ -n "$need_createrepo" ] ; then
385         echo "Indexing node packages after signing"
386         if [ -f $repository/yumgroups.xml ] ; then
387             createrepo --quiet -g yumgroups.xml $repository
388         else
389             createrepo --quiet $repository
390         fi
391     fi
392 }
393
394 function show_env () {
395     set +x
396     echo FCDISTRO=$FCDISTRO
397     echo PLDISTRO=$PLDISTRO
398     echo PERSONALITY=$PERSONALITY
399     echo BASE=$BASE
400     echo BUILD_SCM_URL=$BUILD_SCM_URL
401     echo MAKEVARS="${MAKEVARS[@]}"
402     echo DRY_RUN="$DRY_RUN"
403     echo PLDISTROTAGS="$PLDISTROTAGS"
404     # this does not help, it's not yet set when we run show_env
405     #echo WEBPATH="$WEBPATH"
406     echo TESTBUILDURL="$TESTBUILDURL"
407     echo WEBHOST="$WEBHOST"
408     if in_root_context ; then
409         echo PLDISTROTAGS="$PLDISTROTAGS"
410     else
411         if [ -f /build/$PLDISTROTAGS ] ; then
412             echo "XXXXXXXXXXXXXXXXXXXX Contents of tags definition file /build/$PLDISTROTAGS"
413             cat /build/$PLDISTROTAGS
414             echo "XXXXXXXXXXXXXXXXXXXX end tags definition"
415         else
416             echo "XXXXXXXXXXXXXXXXXXXX Cannot find tags definition file /build/$PLDISTROTAGS, assuming remote pldistro"
417         fi
418     fi
419     set -x
420 }
421
422 function setupssh () {
423     base=$1; shift
424     sshkey=$1; shift
425     
426     if [ -f ${sshkey} ] ; then
427         SSHDIR=$(rootdir ${base})/root/.ssh
428         mkdir -p ${SSHDIR}
429         cp $sshkey ${SSHDIR}/thekey
430         (echo "host *"; \
431             echo "  IdentityFile ~/.ssh/thekey"; \
432             echo "  StrictHostKeyChecking no" ) > ${SSHDIR}/config
433         chmod 700 ${SSHDIR}
434         chmod 400 ${SSHDIR}/*
435     else 
436         echo "WARNING : could not find provided ssh key $sshkey - ignored"
437     fi
438 }
439
440 function usage () {
441     echo "Usage: $COMMAND [option] [var=value...] make-targets"
442     echo "Supported options"
443     echo " -f fcdistro - defaults to $DEFAULT_FCDISTRO"
444     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
445     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
446     echo " -m mailto - no default"
447     echo " -s build_scm_url - git URL where to fetch the build module - defaults to $DEFAULT_BUILD_SCM_URL"
448     echo "    define GIT tag or branch name appending @tagname to url"
449     echo " -t pldistrotags - defaults to \${PLDISTRO}-tags.mk"
450     echo " -b base - defaults to $DEFAULT_BASE"
451     echo "    @NAME@ replaced as appropriate"
452     echo " -o base: (overwrite) do not re-create vm, re-use base instead"
453     echo "    the -f/-d/-p/-m/-s/-t options are uneffective in this case"
454     echo " -c testconfig - defaults to $DEFAULT_TESTCONFIG"
455     echo " -y {pl,pg} - passed to run_log"
456     echo " -e step - passed to run_log"
457     echo " -i step - passed to run_log"
458     echo " -X : passes --lxc to run_log"
459     echo " -S : passes --vs to run_log"
460     echo " -x <run_log_args> - a hook to pass other arguments to run_log"
461     echo " -w webpath - defaults to $DEFAULT_WEBPATH"
462     echo " -W testbuildurl - defaults to $DEFAULT_TESTBUILDURL; this is also used to get the hostname where to publish builds"
463     echo " -r webroot - defaults to $DEFAULT_WEBROOT - the fs point where testbuildurl actually sits"
464     echo " -M testmaster - defaults to $DEFAULT_TESTMASTER"
465     echo " -Y - sign yum repo in webpath"
466     echo " -g gpg_path - to the gpg secring used to sign rpms.  Defaults to $DEFAULT_GPGPATH" 
467     echo " -u gpg_uid - email used in secring. Defaults to $DEFAULT_GPGUID"
468     echo " -K sshkey - specify ssh key to use when reaching git over ssh"
469     echo " -S - do not publish source rpms"
470     echo " -B - run build only"
471     echo " -T - run test only"
472     echo " -n - dry-run: -n passed to make - vm gets created though - no mail sent"
473     echo " -v - be verbose"
474     echo " -7 - uses weekday-@FCDISTRO@ as base"
475     echo " --build-branch branch - build using the branch from build module"
476     exit 1
477 }
478
479 function main () {
480
481     set -e
482
483     # parse arguments
484     MAKEVARS=()
485     MAKETARGETS=()
486     DRY_RUN=
487     DO_BUILD=true
488     DO_TEST=true
489     PUBLISH_SRPMS=true
490     SSH_KEY=""
491     SIGNYUMREPO=""
492
493     OPTS_ORIG=$@
494     OPTS=$(getopt -o "f:d:p:m:s:t:b:o:c:y:e:i:XSx:w:W:r:M:Yg:u:K:SBTnv7i:P:h" -l "build-branch:" -- $@)
495     if [ $? != 0 ]
496     then
497         usage
498     fi
499     eval set -- "$OPTS"
500     while true; do
501         case $1 in
502             -f) FCDISTRO=$2; shift 2 ;;
503             -d) PLDISTRO=$2; shift 2 ;;
504             -p) PERSONALITY=$2; shift 2 ;;
505             -m) MAILTO=$2; shift 2 ;;
506             -s) BUILD_SCM_URL=$2; shift 2 ;;
507             -t) PLDISTROTAGS=$2; shift 2 ;;
508             -b) BASE=$2; shift 2 ;;
509             -o) OVERBASE=$2; shift 2 ;;
510             -c) TESTCONFIG="$TESTCONFIG $2"; shift 2 ;;
511             ########## passing stuff to run_log
512             # -y foo -> run_log -y foo
513             -y) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --rspec-style $2"; shift 2 ;;
514             # -e foo -> run_log -e foo
515             -e) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --exclude $2"; shift 2 ;;
516             -i) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --ignore $2"; shift 2 ;;
517             # -X -> run_log --lxc
518             -X) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --lxc"; shift;;
519             # -S -> run_log --vs
520             -S) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --vs"; shift;;
521             # more general form to pass args to run_log
522             # -x foo -> run_log foo
523             -x) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS $2"; shift 2;;
524             ##########
525             -w) WEBPATH=$2; shift 2 ;;
526             -W) TESTBUILDURL=$2; shift 2 ;;
527             -r) WEBROOT=$2; shift 2 ;;
528             -M) TESTMASTER=$2; shift 2 ;;
529             -Y) SIGNYUMREPO=true; shift ;;
530             -g) GPGPATH=$2; shift 2 ;;
531             -u) GPGUID=$2; shift 2 ;;
532             -K) SSH_KEY=$2; shift 2 ;;
533             -S) PUBLISH_SRPMS="" ; shift ;;
534             -B) DO_TEST= ; shift ;;
535             -T) DO_BUILD= ; shift;;
536             -n) DRY_RUN="-n" ; shift ;;
537             -v) set -x ; VERBOSE="-v" ; shift ;;
538             -7) BASE="$(date +%a|tr A-Z a-z)-@FCDISTRO@" ; shift ;;
539             -P) PREINSTALLED="-P $2"; shift 2;;
540             -h) usage ; shift ;;
541             --) shift; break ;;
542         esac
543     done
544
545     # preserve options for passing them again later, together with expanded base
546     options=$OPTS_ORIG
547
548     # allow var=value stuff; 
549     for target in "$@" ; do
550         # check if contains '='
551         target1=$(echo $target | sed -e s,=,,)
552         if [ "$target" = "$target1" ] ; then
553             MAKETARGETS=(${MAKETARGETS[@]} "$target")
554         else
555             MAKEVARS=(${MAKEVARS[@]} "$target")
556         fi
557     done
558     
559     # set defaults
560     [ -z "$FCDISTRO" ] && FCDISTRO=$DEFAULT_FCDISTRO
561     [ -z "$PLDISTRO" ] && PLDISTRO=$DEFAULT_PLDISTRO
562     [ -z "$PERSONALITY" ] && PERSONALITY=$DEFAULT_PERSONALITY
563     [ -z "$PLDISTROTAGS" ] && PLDISTROTAGS="${PLDISTRO}-tags.mk"
564     [ -z "$BASE" ] && BASE="$DEFAULT_BASE"
565     [ -z "$WEBPATH" ] && WEBPATH="$DEFAULT_WEBPATH"
566     [ -z "$TESTBUILDURL" ] && TESTBUILDURL="$DEFAULT_TESTBUILDURL"
567     [ -z "$WEBROOT" ] && WEBROOT="$DEFAULT_WEBROOT"
568     [ -z "$GPGPATH" ] && GPGPATH="$DEFAULT_GPGPATH"
569     [ -z "$GPGUID" ] && GPGUID="$DEFAULT_GPGUID"
570     [ -z "$BUILD_SCM_URL" ] && BUILD_SCM_URL="$DEFAULT_BUILD_SCM_URL"
571     [ -z "$TESTCONFIG" ] && TESTCONFIG="$DEFAULT_TESTCONFIG"
572     [ -z "$TESTMASTER" ] && TESTMASTER="$DEFAULT_TESTMASTER"
573
574     [ -n "$DRY_RUN" ] && MAILTO=""
575
576     # elaborate the extra args to be passed to run_log
577     for config in ${TESTCONFIG} ; do
578         RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --config $config"
579     done
580     
581         
582     if [ -n "$OVERBASE" ] ; then
583         sedargs="-e s,@DATE@,${DATE},g"
584         BASE=$(echo ${OVERBASE} | sed $sedargs)
585     else
586         sedargs="-e s,@DATE@,${DATE},g -e s,@FCDISTRO@,${FCDISTRO},g -e s,@PLDISTRO@,${PLDISTRO},g -e s,@PERSONALITY@,${PERSONALITY},g"
587         BASE=$(echo ${BASE} | sed $sedargs)
588     fi
589
590     ### elaborate mail subject
591     if [ -n "$DO_BUILD" -a -n "$DO_TEST" ] ; then
592         MAIL_SUBJECT="full"
593     elif [ -n "$DO_BUILD" ] ; then
594         MAIL_SUBJECT="pkg-only"
595     elif [ -n "$DO_TEST" ] ; then
596         MAIL_SUBJECT="test-only"
597     fi
598     if [ -n "$OVERBASE" ] ; then
599         MAIL_SUBJECT="${MAIL_SUBJECT} rerun"
600     else
601         MAIL_SUBJECT="${MAIL_SUBJECT} fresh"
602     fi
603     short_hostname=$(hostname | cut -d. -f1)
604     MAIL_SUBJECT="on ${short_hostname} - ${MAIL_SUBJECT}"
605
606     ### compute WEBHOST from TESTBUILDURL 
607     # this is to avoid having to change the builds configs everywhere
608     # simplistic way to extract hostname from a URL
609     WEBHOST=$(echo "$TESTBUILDURL" | cut -d/ -f 3)
610
611     if ! in_root_context ; then
612         # in the vm
613         echo "==================== Within LXC BEG $(date)"
614         build
615         echo "==================== Within LXC END $(date)"
616
617     else
618         trap failure ERR INT
619         # we run in the root context : 
620         # (*) create or check for the vm to use
621         # (*) copy this command in the vm
622         # (*) invoke it
623         
624         if [ -n "$OVERBASE" ] ; then
625             ### Re-use a vm (finish an unfinished build..)
626             if [ ! -d $(rootdir ${BASE}) ] ; then
627                 echo $COMMAND : cannot find vm $BASE
628                 exit 1
629             fi
630             # manage LOG - beware it might be a symlink so nuke it first
631             LOG=$(logfile ${BASE})
632             rm -f $LOG
633             exec > $LOG 2>&1
634             set -x
635             echo "XXXXXXXXXX $COMMAND: using existing vm $BASE" $(date)
636             # start in case e.g. we just rebooted
637             virsh -c lxc:/// start ${BASE} || :
638             # retrieve environment from the previous run
639             FCDISTRO=$(virsh -c lxc:/// lxc-enter-namespace ${BASE} /build/getdistroname.sh)
640             BUILD_SCM_URL=$(virsh -c lxc:/// lxc-enter-namespace ${BASE} /bin/bash -c "make --no-print-directory -C /build stage1=skip +build-GITPATH")
641             # for efficiency, crop everything in one make run
642             tmp=/tmp/${BASE}-env.sh
643             virsh -c lxc:/// lxc-enter-namespace ${BASE} /bin/bash -c "make --no-print-directory -C /build stage1=skip \
644                 ++PLDISTRO ++PLDISTROTAGS ++PERSONALITY ++MAILTO ++WEBPATH ++TESTBUILDURL ++WEBROOT" > $tmp
645             . $tmp
646             rm -f $tmp
647             # update build
648             [ -n "$SSH_KEY" ] && setupssh ${BASE} ${SSH_KEY}
649             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "cd /build; git pull; make tests-clean"
650             # make sure we refresh the tests place in case it has changed
651             rm -f /build/MODULES/tests
652             options=(${options[@]} -d $PLDISTRO -t $PLDISTROTAGS -s $BUILD_SCM_URL)
653             [ -n "$PERSONALITY" ] && options=(${options[@]} -p $PERSONALITY)
654             [ -n "$MAILTO" ] && options=(${options[@]} -m $MAILTO)
655             [ -n "$WEBPATH" ] && options=(${options[@]} -w $WEBPATH)
656             [ -n "$TESTBUILDURL" ] && options=(${options[@]} -W $TESTBUILDURL)
657             [ -n "$WEBROOT" ] && options=(${options[@]} -r $WEBROOT)
658             show_env
659         else
660             # create vm: check it does not exist yet
661             i=
662             while [ -d $(rootdir ${BASE})${i} ] ; do
663                 # we name subsequent builds <base>-n<i> so the logs and builds get sorted properly
664                 [ -z ${i} ] && BASE=${BASE}-n
665                 i=$((${i}+1))
666                 if [ $i -gt 100 ] ; then
667                     echo "$COMMAND: Failed to create build vm $(rootdir ${BASE})${i}"
668                     exit 1
669                 fi
670             done
671             BASE=${BASE}${i}
672             # need update
673             # manage LOG - beware it might be a symlink so nuke it first
674             LOG=$(logfile ${BASE})
675             rm -f $LOG
676             exec > $LOG 2>&1 
677             set -x
678             echo "XXXXXXXXXX $COMMAND: creating vm $BASE" $(date)
679             show_env
680
681             ### extract the whole build - much simpler
682             tmpdir=/tmp/$COMMAND-$$
683             GIT_REPO=$(echo $BUILD_SCM_URL | cut -d@ -f1)
684             GIT_TAG=$(echo $BUILD_SCM_URL | cut -s -d@ -f2)
685             GIT_TAG=${GIT_TAG:-master}
686             mkdir -p $tmpdir; git archive --remote=$GIT_REPO $GIT_TAG | tar -C $tmpdir -xf -
687
688             # Create lxc vm
689             cd $tmpdir
690             ./lbuild-initvm.sh $VERBOSE -f ${FCDISTRO} -d ${PLDISTRO} -p ${PERSONALITY} ${PREINSTALLED} ${BASE} 
691             # cleanup
692             cd -
693             rm -rf $tmpdir
694             # Extract build again - in the vm
695             [ -n "$SSH_KEY" ] && setupssh ${BASE} ${SSH_KEY}
696             # xxx not working as of now - waiting for Sapan to look into this
697             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "git clone $GIT_REPO /build; cd /build; git checkout $GIT_TAG"
698         fi
699         echo "XXXXXXXXXX $COMMAND: preparation of vm $BASE done" $(date)
700
701         # The log inside the vm contains everything
702         LOG2=$(rootdir ${BASE})/log.txt
703         (echo "==================== BEG LXC Transcript of vm creation" ; \
704          cat $LOG ; \
705          echo "==================== END LXC Transcript of vm creation" ; \
706          echo "xxxxxxxxxx Messing with logs, symlinking $LOG2 to $LOG" ) >> $LOG2
707         ### not too nice : nuke the former log, symlink it to the new one
708         rm $LOG; ln -s $LOG2 $LOG
709         LOG=$LOG2
710         # redirect log again
711         exec >> $LOG 2>&1 
712
713         sedargs="-e s,@DATE@,${DATE},g -e s,@FCDISTRO@,${FCDISTRO},g -e s,@PLDISTRO@,${PLDISTRO},g -e s,@PERSONALITY@,${PERSONALITY},g"
714         WEBPATH=$(echo ${WEBPATH} | sed $sedargs)
715         webpublish mkdir -p ${WEBPATH}
716
717         # where to store the log for web access
718         WEBBASE=${WEBPATH}/${BASE}
719         WEBLOG=${WEBPATH}/${BASE}/log.txt
720         # compute the log URL - inserted in the mail messages for convenience
721         WEBBASE_URL=$(echo $WEBBASE | sed -e "s,//,/,g" -e "s,${WEBROOT},${TESTBUILDURL},")
722     
723         if [ -n "$DO_BUILD" ] ; then 
724
725             # invoke this command into the build directory of the vm
726             cp $COMMANDPATH $(rootdir ${BASE})/build/
727
728             # invoke this command in the vm for building (-T)
729             virsh -c lxc:/// lxc-enter-namespace ${BASE} /bin/bash -c "chmod +x /build/$COMMAND"
730             virsh -c lxc:/// lxc-enter-namespace ${BASE} /build/$COMMAND "${options[@]}" -b "${BASE}" "${MAKEVARS[@]}" "${MAKETARGETS[@]}"
731         fi
732
733         # publish to the web so run_log can find them
734         set +e
735         webpublish rm -rf $WEBPATH/$BASE 
736         # guess if we've been doing any debian-related build
737         if [ ! -f $(rootdir $BASE)/etc/debian_version  ] ; then
738             webpublish mkdir -p $WEBPATH/$BASE/{RPMS,SRPMS}
739             webpublish_rsync_dir $WEBPATH/$BASE/RPMS/ $(rootdir $BASE)/build/RPMS/
740             [[ -n "$PUBLISH_SRPMS" ]] && webpublish_rsync_dir $WEBPATH/$BASE/SRPMS/ $(rootdir $BASE)/build/SRPMS/
741         else
742             # run scanpackages so we can use apt-get on this
743             # (not needed on fedora b/c this is done by the regular build already)
744             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "(cd /build ; dpkg-scanpackages DEBIAN/ | gzip -9c > Packages.gz)"
745             webpublish mkdir -p $WEBPATH/$BASE/DEBIAN
746             webpublish_rsync_files $WEBPATH/$BASE/DEBIAN/ $(rootdir $BASE)/build/DEBIAN/*.deb 
747             webpublish_rsync_files $WEBPATH/$BASE/ $(rootdir $BASE)/build/Packages.gz
748         fi
749         # publish myplc-release if this exists
750         release=$(rootdir $BASE)/build/myplc-release
751         [ -f $release ] && webpublish_rsync_files $WEBPATH/$BASE $release
752         set -e
753
754         # create yum repo and sign packages.
755         if [ -n "$SIGNYUMREPO" ] ; then
756             # this script does not yet support signing on a remote (webhost) repo
757             sign_here=$(hostname) ; sign_web=$(webpublish hostname)
758             if [ "$hostname" = "$sign_here" ] ; then
759                 sign_node_packages
760             else
761                 echo "$COMMAND does not support signing on a remote yum repo"
762                 echo "you might want to turn off the -y option, or run this on the web server box itself"
763                 exit 1
764             fi
765         fi
766
767         if [ -n "$DO_TEST" ] ; then 
768             run_log
769         fi
770
771         success 
772
773         echo "==================== MAIN END $(date)"    
774     fi
775
776 }
777
778 ##########
779 main "$@"