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