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