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