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