have to duplicate bin_in_container..
[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/rootfs
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         [ -f /vservers/$lxc/rootfs/$path/$binary ] && { echo $path/$binary; return; }
230     done
231     echo bin_in_container_cannot_find_$binary
232 }
233
234 # run in the vm - do not manage success/failure, will be done from the root ctx
235 function build () {
236     set -x
237     set -e
238
239     echo -n "============================== Starting $COMMAND:build on "
240     date
241
242     cd /build
243     show_env
244     
245     echo "Running make IN $(pwd)"
246     
247     # stuff our own variable settings
248     MAKEVARS=("build-GITPATH=${BUILD_SCM_URL}" "${MAKEVARS[@]}")
249     MAKEVARS=("PLDISTRO=${PLDISTRO}" "${MAKEVARS[@]}")
250     MAKEVARS=("PLDISTROTAGS=${PLDISTROTAGS}" "${MAKEVARS[@]}")
251     MAKEVARS=("PERSONALITY=${PERSONALITY}" "${MAKEVARS[@]}")
252     MAKEVARS=("MAILTO=${MAILTO}" "${MAKEVARS[@]}")
253     MAKEVARS=("WEBPATH=${WEBPATH}" "${MAKEVARS[@]}")
254     MAKEVARS=("TESTBUILDURL=${TESTBUILDURL}" "${MAKEVARS[@]}")
255     MAKEVARS=("WEBROOT=${WEBROOT}" "${MAKEVARS[@]}")
256
257     MAKEVARS=("BASE=${BASE}" "${MAKEVARS[@]}")
258
259     # initialize latex
260     /build/latex-first-run.sh || :
261
262     # stage1
263     make -C /build $DRY_RUN "${MAKEVARS[@]}" stage1=true 
264     # versions
265     make -C /build $DRY_RUN "${MAKEVARS[@]}" versions
266     # actual stuff
267     make -C /build $DRY_RUN "${MAKEVARS[@]}" "${MAKETARGETS[@]}"
268
269 }
270
271 # this was formerly run in the myplc-devel chroot but now is run in the root context,
272 # this is so that the .ssh config gets done manually, and once and for all
273 function run_log () {
274     set -x
275     set -e
276     trap failure ERR INT
277
278     echo "============================== BEG $COMMAND:run_log on $(date)"
279
280     ### the URL to the RPMS/<arch> location
281     # f12 now has everything in i686; try i386 first as older fedoras have both
282     url=""
283     for a in i386 i686 x86_64; do
284         archdir=$(rootdir $BASE)/build/RPMS/$a
285         if [ -d $archdir ] ; then
286             # where was that installed
287             url=$(echo $archdir | sed -e "s,$(rootdir $BASE)/build,${WEBPATH}/${BASE},")
288             url=$(echo $url | sed -e "s,${WEBROOT},${TESTBUILDURL},")
289             break
290         fi
291     done
292
293     if [ -z "$url" ] ; then
294         echo "$COMMAND: Cannot locate arch URL for testing"
295         failure
296         exit 1
297     fi
298
299     testmaster_ssh="root@${TESTMASTER}"
300
301     # test directory name on test box
302     testdir=${BASE}
303
304     # clean it
305     ssh -n ${testmaster_ssh} rm -rf ${testdir} ${testdir}.git
306
307     # check it out in the build
308     virsh -c lxc:/// lxc-enter-namespace $BASE -- $(bin_in_container $BASE make) -C /build tests-module
309     
310     # push it onto the testmaster - just the 'system' subdir is enough
311     rsync --verbose --archive $(rootdir $BASE)/build/MODULES/tests/system/ ${testmaster_ssh}:${BASE}
312     # toss the build in the bargain, so the tests don't need to mess with extracting it
313     rsync --verbose --archive $(rootdir $BASE)/build/MODULES/build ${testmaster_ssh}:${BASE}/
314
315     # invoke test on testbox - pass url and build url - so the tests can use vtest-init-lxc.sh
316     run_log_env="-p $PERSONALITY -d $PLDISTRO -f $FCDISTRO"
317
318     # need to proceed despite of set -e
319     success=true
320     # passing the build_scm_url should not be needed anymore
321     ssh 2>&1 -n ${testmaster_ssh} ${testdir}/run_log --build ${BUILD_SCM_URL} --url ${url} $run_log_env $RUN_LOG_EXTRAS $VERBOSE --all || success=
322
323     # gather logs in the build vm
324     mkdir -p $(rootdir $BASE)/build/testlogs
325     rsync --verbose --archive ${testmaster_ssh}:$BASE/logs/ $(rootdir $BASE)/build/testlogs
326     # push them to the build web
327     chmod -R a+r $(rootdir $BASE)/build/testlogs/
328     webpublish_rsync_dir $WEBPATH/$BASE/testlogs/ $(rootdir $BASE)/build/testlogs/
329
330     echo  "============================== END $COMMAND:run_log on $(date)"
331
332     if [ -z "$success" ] ; then
333         echo "Tests have failed - bailing out"
334         failure
335     fi
336     
337 }
338
339 # this part won't work if WEBHOST does not match the local host
340 # would need to be made webpublish_* compliant
341 # but do we really need this feature anyway ?
342 function sign_node_packages () {
343
344     echo "Signing node packages"
345     
346     need_createrepo=""
347
348     repository=$WEBPATH/$BASE/RPMS/
349     # the rpms that need signing
350     new_rpms=
351     # and the corresponding stamps
352     new_stamps=
353
354     for package in $(find $repository/ -name '*.rpm') ; do
355         stamp=$repository/signed-stamps/$(basename $package).signed
356         # If package is newer than signature stamp
357         if [ $package -nt $stamp ] ; then
358             new_rpms="$new_rpms $package"
359             new_stamps="$new_stamps $stamp"
360         fi
361         # Or than createrepo database
362         [ $package -nt $repository/repodata/repomd.xml ] && need_createrepo=true
363     done
364
365     if [ -n "$new_rpms" ] ; then
366         # Create a stamp once the package gets signed
367         mkdir $repository/signed-stamps 2> /dev/null
368         
369         # Sign RPMS. setsid detaches rpm from the terminal,
370         # allowing the (hopefully blank) GPG password to be
371         # entered from stdin instead of /dev/tty.
372         echo | setsid rpm \
373             --define "_signature gpg" \
374             --define "_gpg_path $GPGPATH" \
375             --define "_gpg_name $GPGUID" \
376             --resign $new_rpms && touch $new_stamps
377     fi
378
379      # Update repository index / yum metadata. 
380     if [ -n "$need_createrepo" ] ; then
381         echo "Indexing node packages after signing"
382         if [ -f $repository/yumgroups.xml ] ; then
383             createrepo --quiet -g yumgroups.xml $repository
384         else
385             createrepo --quiet $repository
386         fi
387     fi
388 }
389
390 function show_env () {
391     set +x
392     echo FCDISTRO=$FCDISTRO
393     echo PLDISTRO=$PLDISTRO
394     echo PERSONALITY=$PERSONALITY
395     echo BASE=$BASE
396     echo BUILD_SCM_URL=$BUILD_SCM_URL
397     echo MAKEVARS="${MAKEVARS[@]}"
398     echo DRY_RUN="$DRY_RUN"
399     echo PLDISTROTAGS="$PLDISTROTAGS"
400     # this does not help, it's not yet set when we run show_env
401     #echo WEBPATH="$WEBPATH"
402     echo TESTBUILDURL="$TESTBUILDURL"
403     echo WEBHOST="$WEBHOST"
404     if in_root_context ; then
405         echo PLDISTROTAGS="$PLDISTROTAGS"
406     else
407         if [ -f /build/$PLDISTROTAGS ] ; then
408             echo "XXXXXXXXXXXXXXXXXXXX Contents of tags definition file /build/$PLDISTROTAGS"
409             cat /build/$PLDISTROTAGS
410             echo "XXXXXXXXXXXXXXXXXXXX end tags definition"
411         else
412             echo "XXXXXXXXXXXXXXXXXXXX Cannot find tags definition file /build/$PLDISTROTAGS, assuming remote pldistro"
413         fi
414     fi
415     set -x
416 }
417
418 function setupssh () {
419     base=$1; shift
420     sshkey=$1; shift
421     
422     if [ -f ${sshkey} ] ; then
423         SSHDIR=$(rootdir ${base})/root/.ssh
424         mkdir -p ${SSHDIR}
425         cp $sshkey ${SSHDIR}/thekey
426         (echo "host *"; \
427             echo "  IdentityFile ~/.ssh/thekey"; \
428             echo "  StrictHostKeyChecking no" ) > ${SSHDIR}/config
429         chmod 700 ${SSHDIR}
430         chmod 400 ${SSHDIR}/*
431     else 
432         echo "WARNING : could not find provided ssh key $sshkey - ignored"
433     fi
434 }
435
436 function usage () {
437     echo "Usage: $COMMAND [option] [var=value...] make-targets"
438     echo "Supported options"
439     echo " -f fcdistro - defaults to $DEFAULT_FCDISTRO"
440     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
441     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
442     echo " -m mailto - no default"
443     echo " -s build_scm_url - git URL where to fetch the build module - defaults to $DEFAULT_BUILD_SCM_URL"
444     echo "    define GIT tag or branch name appending @tagname to url"
445     echo " -t pldistrotags - defaults to \${PLDISTRO}-tags.mk"
446     echo " -b base - defaults to $DEFAULT_BASE"
447     echo "    @NAME@ replaced as appropriate"
448     echo " -o base: (overwrite) do not re-create vm, re-use base instead"
449     echo "    the -f/-d/-p/-m/-s/-t options are uneffective in this case"
450     echo " -c testconfig - defaults to $DEFAULT_TESTCONFIG"
451     echo " -y {pl,pg} - passed to run_log"
452     echo " -e step - passed to run_log"
453     echo " -i step - passed to run_log"
454     echo " -X : passes --lxc to run_log"
455     echo " -S : passes --vs to run_log"
456     echo " -x <run_log_args> - a hook to pass other arguments to run_log"
457     echo " -w webpath - defaults to $DEFAULT_WEBPATH"
458     echo " -W testbuildurl - defaults to $DEFAULT_TESTBUILDURL; this is also used to get the hostname where to publish builds"
459     echo " -r webroot - defaults to $DEFAULT_WEBROOT - the fs point where testbuildurl actually sits"
460     echo " -M testmaster - defaults to $DEFAULT_TESTMASTER"
461     echo " -Y - sign yum repo in webpath"
462     echo " -g gpg_path - to the gpg secring used to sign rpms.  Defaults to $DEFAULT_GPGPATH" 
463     echo " -u gpg_uid - email used in secring. Defaults to $DEFAULT_GPGUID"
464     echo " -K sshkey - specify ssh key to use when reaching git over ssh"
465     echo " -S - do not publish source rpms"
466     echo " -B - run build only"
467     echo " -T - run test only"
468     echo " -n - dry-run: -n passed to make - vm gets created though - no mail sent"
469     echo " -v - be verbose"
470     echo " -7 - uses weekday-@FCDISTRO@ as base"
471     echo " --build-branch branch - build using the branch from build module"
472     exit 1
473 }
474
475 function main () {
476
477     set -e
478
479     # parse arguments
480     MAKEVARS=()
481     MAKETARGETS=()
482     DRY_RUN=
483     DO_BUILD=true
484     DO_TEST=true
485     PUBLISH_SRPMS=true
486     SSH_KEY=""
487     SIGNYUMREPO=""
488
489     OPTS_ORIG=$@
490     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:" -- $@)
491     if [ $? != 0 ]
492     then
493         usage
494     fi
495     eval set -- "$OPTS"
496     while true; do
497         case $1 in
498             -f) FCDISTRO=$2; shift 2 ;;
499             -d) PLDISTRO=$2; shift 2 ;;
500             -p) PERSONALITY=$2; shift 2 ;;
501             -m) MAILTO=$2; shift 2 ;;
502             -s) BUILD_SCM_URL=$2; shift 2 ;;
503             -t) PLDISTROTAGS=$2; shift 2 ;;
504             -b) BASE=$2; shift 2 ;;
505             -o) OVERBASE=$2; shift 2 ;;
506             -c) TESTCONFIG="$TESTCONFIG $2"; shift 2 ;;
507             ########## passing stuff to run_log
508             # -y foo -> run_log -y foo
509             -y) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --rspec-style $2"; shift 2 ;;
510             # -e foo -> run_log -e foo
511             -e) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --exclude $2"; shift 2 ;;
512             -i) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --ignore $2"; shift 2 ;;
513             # -X -> run_log --lxc
514             -X) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --lxc"; shift;;
515             # -S -> run_log --vs
516             -S) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --vs"; shift;;
517             # more general form to pass args to run_log
518             # -x foo -> run_log foo
519             -x) RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS $2"; shift 2;;
520             ##########
521             -w) WEBPATH=$2; shift 2 ;;
522             -W) TESTBUILDURL=$2; shift 2 ;;
523             -r) WEBROOT=$2; shift 2 ;;
524             -M) TESTMASTER=$2; shift 2 ;;
525             -Y) SIGNYUMREPO=true; shift ;;
526             -g) GPGPATH=$2; shift 2 ;;
527             -u) GPGUID=$2; shift 2 ;;
528             -K) SSH_KEY=$2; shift 2 ;;
529             -S) PUBLISH_SRPMS="" ; shift ;;
530             -B) DO_TEST= ; shift ;;
531             -T) DO_BUILD= ; shift;;
532             -n) DRY_RUN="-n" ; shift ;;
533             -v) set -x ; VERBOSE="-v" ; shift ;;
534             -7) BASE="$(date +%a|tr A-Z a-z)-@FCDISTRO@" ; shift ;;
535             -P) PREINSTALLED="-P $2"; shift 2;;
536             -h) usage ; shift ;;
537             --) shift; break ;;
538         esac
539     done
540
541     # preserve options for passing them again later, together with expanded base
542     options=$OPTS_ORIG
543
544     # allow var=value stuff; 
545     for target in "$@" ; do
546         # check if contains '='
547         target1=$(echo $target | sed -e s,=,,)
548         if [ "$target" = "$target1" ] ; then
549             MAKETARGETS=(${MAKETARGETS[@]} "$target")
550         else
551             MAKEVARS=(${MAKEVARS[@]} "$target")
552         fi
553     done
554     
555     # set defaults
556     [ -z "$FCDISTRO" ] && FCDISTRO=$DEFAULT_FCDISTRO
557     [ -z "$PLDISTRO" ] && PLDISTRO=$DEFAULT_PLDISTRO
558     [ -z "$PERSONALITY" ] && PERSONALITY=$DEFAULT_PERSONALITY
559     [ -z "$PLDISTROTAGS" ] && PLDISTROTAGS="${PLDISTRO}-tags.mk"
560     [ -z "$BASE" ] && BASE="$DEFAULT_BASE"
561     [ -z "$WEBPATH" ] && WEBPATH="$DEFAULT_WEBPATH"
562     [ -z "$TESTBUILDURL" ] && TESTBUILDURL="$DEFAULT_TESTBUILDURL"
563     [ -z "$WEBROOT" ] && WEBROOT="$DEFAULT_WEBROOT"
564     [ -z "$GPGPATH" ] && GPGPATH="$DEFAULT_GPGPATH"
565     [ -z "$GPGUID" ] && GPGUID="$DEFAULT_GPGUID"
566     [ -z "$BUILD_SCM_URL" ] && BUILD_SCM_URL="$DEFAULT_BUILD_SCM_URL"
567     [ -z "$TESTCONFIG" ] && TESTCONFIG="$DEFAULT_TESTCONFIG"
568     [ -z "$TESTMASTER" ] && TESTMASTER="$DEFAULT_TESTMASTER"
569
570     [ -n "$DRY_RUN" ] && MAILTO=""
571
572     # elaborate the extra args to be passed to run_log
573     for config in ${TESTCONFIG} ; do
574         RUN_LOG_EXTRAS="$RUN_LOG_EXTRAS --config $config"
575     done
576     
577         
578     if [ -n "$OVERBASE" ] ; then
579         sedargs="-e s,@DATE@,${DATE},g"
580         BASE=$(echo ${OVERBASE} | sed $sedargs)
581     else
582         sedargs="-e s,@DATE@,${DATE},g -e s,@FCDISTRO@,${FCDISTRO},g -e s,@PLDISTRO@,${PLDISTRO},g -e s,@PERSONALITY@,${PERSONALITY},g"
583         BASE=$(echo ${BASE} | sed $sedargs)
584     fi
585
586     ### elaborate mail subject
587     if [ -n "$DO_BUILD" -a -n "$DO_TEST" ] ; then
588         MAIL_SUBJECT="full"
589     elif [ -n "$DO_BUILD" ] ; then
590         MAIL_SUBJECT="pkg-only"
591     elif [ -n "$DO_TEST" ] ; then
592         MAIL_SUBJECT="test-only"
593     fi
594     if [ -n "$OVERBASE" ] ; then
595         MAIL_SUBJECT="${MAIL_SUBJECT} rerun"
596     else
597         MAIL_SUBJECT="${MAIL_SUBJECT} fresh"
598     fi
599     short_hostname=$(hostname | cut -d. -f1)
600     MAIL_SUBJECT="on ${short_hostname} - ${MAIL_SUBJECT}"
601
602     ### compute WEBHOST from TESTBUILDURL 
603     # this is to avoid having to change the builds configs everywhere
604     # simplistic way to extract hostname from a URL
605     WEBHOST=$(echo "$TESTBUILDURL" | cut -d/ -f 3)
606
607     if ! in_root_context ; then
608         # in the vm
609         echo "==================== Within LXC BEG $(date)"
610         build
611         echo "==================== Within LXC END $(date)"
612
613     else
614         trap failure ERR INT
615         # we run in the root context : 
616         # (*) create or check for the vm to use
617         # (*) copy this command in the vm
618         # (*) invoke it
619         
620         if [ -n "$OVERBASE" ] ; then
621             ### Re-use a vm (finish an unfinished build..)
622             if [ ! -d $(rootdir ${BASE}) ] ; then
623                 echo $COMMAND : cannot find vm $BASE
624                 exit 1
625             fi
626             # manage LOG - beware it might be a symlink so nuke it first
627             LOG=$(logfile ${BASE})
628             rm -f $LOG
629             exec > $LOG 2>&1
630             set -x
631             echo "XXXXXXXXXX $COMMAND: using existing vm $BASE" $(date)
632             # start in case e.g. we just rebooted
633             virsh -c lxc:/// start ${BASE} || :
634             # retrieve environment from the previous run
635             FCDISTRO=$(virsh -c lxc:/// lxc-enter-namespace ${BASE} /build/getdistroname.sh)
636             BUILD_SCM_URL=$(virsh -c lxc:/// lxc-enter-namespace ${BASE} -- $(bin_in_container $BASE make) --no-print-directory -C /build stage1=skip +build-GITPATH)
637             # for efficiency, crop everything in one make run
638             tmp=/tmp/${BASE}-env.sh
639             virsh -c lxc:/// lxc-enter-namespace ${BASE} -- $(bin_in_container $BASE make) --no-print-directory -C /build stage1=skip \
640                 ++PLDISTRO ++PLDISTROTAGS ++PERSONALITY ++MAILTO ++WEBPATH ++TESTBUILDURL ++WEBROOT > $tmp
641             . $tmp
642             rm -f $tmp
643             # update build
644             [ -n "$SSH_KEY" ] && setupssh ${BASE} ${SSH_KEY}
645             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "cd /build; git pull; make tests-clean"
646             # make sure we refresh the tests place in case it has changed
647             rm -f /build/MODULES/tests
648             options=(${options[@]} -d $PLDISTRO -t $PLDISTROTAGS -s $BUILD_SCM_URL)
649             [ -n "$PERSONALITY" ] && options=(${options[@]} -p $PERSONALITY)
650             [ -n "$MAILTO" ] && options=(${options[@]} -m $MAILTO)
651             [ -n "$WEBPATH" ] && options=(${options[@]} -w $WEBPATH)
652             [ -n "$TESTBUILDURL" ] && options=(${options[@]} -W $TESTBUILDURL)
653             [ -n "$WEBROOT" ] && options=(${options[@]} -r $WEBROOT)
654             show_env
655         else
656             # create vm: check it does not exist yet
657             i=
658             while [ -d $(rootdir ${BASE})${i} ] ; do
659                 # we name subsequent builds <base>-n<i> so the logs and builds get sorted properly
660                 [ -z ${i} ] && BASE=${BASE}-n
661                 i=$((${i}+1))
662                 if [ $i -gt 100 ] ; then
663                     echo "$COMMAND: Failed to create build vm $(rootdir ${BASE})${i}"
664                     exit 1
665                 fi
666             done
667             BASE=${BASE}${i}
668             # need update
669             # manage LOG - beware it might be a symlink so nuke it first
670             LOG=$(logfile ${BASE})
671             rm -f $LOG
672             exec > $LOG 2>&1 
673             set -x
674             echo "XXXXXXXXXX $COMMAND: creating vm $BASE" $(date)
675             show_env
676
677             ### extract the whole build - much simpler
678             tmpdir=/tmp/$COMMAND-$$
679             GIT_REPO=$(echo $BUILD_SCM_URL | cut -d@ -f1)
680             GIT_TAG=$(echo $BUILD_SCM_URL | cut -s -d@ -f2)
681             GIT_TAG=${GIT_TAG:-master}
682             mkdir -p $tmpdir; git archive --remote=$GIT_REPO $GIT_TAG | tar -C $tmpdir -xf -
683
684             # Create lxc vm
685             cd $tmpdir
686             ./lbuild-initvm.sh $VERBOSE -f ${FCDISTRO} -d ${PLDISTRO} -p ${PERSONALITY} ${PREINSTALLED} ${BASE} 
687             # cleanup
688             cd -
689             rm -rf $tmpdir
690             # Extract build again - in the vm
691             [ -n "$SSH_KEY" ] && setupssh ${BASE} ${SSH_KEY}
692             # xxx not working as of now - waiting for Sapan to look into this
693             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "git clone $GIT_REPO /build; cd /build; git checkout $GIT_TAG"
694         fi
695         echo "XXXXXXXXXX $COMMAND: preparation of vm $BASE done" $(date)
696
697         # The log inside the vm contains everything
698         LOG2=$(rootdir ${BASE})/log.txt
699         (echo "==================== BEG LXC Transcript of vm creation" ; \
700          cat $LOG ; \
701          echo "==================== END LXC Transcript of vm creation" ; \
702          echo "xxxxxxxxxx Messing with logs, symlinking $LOG2 to $LOG" ) >> $LOG2
703         ### not too nice : nuke the former log, symlink it to the new one
704         rm $LOG; ln -s $LOG2 $LOG
705         LOG=$LOG2
706         # redirect log again
707         exec >> $LOG 2>&1 
708
709         sedargs="-e s,@DATE@,${DATE},g -e s,@FCDISTRO@,${FCDISTRO},g -e s,@PLDISTRO@,${PLDISTRO},g -e s,@PERSONALITY@,${PERSONALITY},g"
710         WEBPATH=$(echo ${WEBPATH} | sed $sedargs)
711         webpublish mkdir -p ${WEBPATH}
712
713         # where to store the log for web access
714         WEBBASE=${WEBPATH}/${BASE}
715         WEBLOG=${WEBPATH}/${BASE}/log.txt
716         # compute the log URL - inserted in the mail messages for convenience
717         WEBBASE_URL=$(echo $WEBBASE | sed -e "s,//,/,g" -e "s,${WEBROOT},${TESTBUILDURL},")
718     
719         if [ -n "$DO_BUILD" ] ; then 
720
721             # invoke this command into the build directory of the vm
722             cp $COMMANDPATH $(rootdir ${BASE})/build/
723
724             # invoke this command in the vm for building (-T)
725             virsh -c lxc:/// lxc-enter-namespace ${BASE} $(bin_in_container $BASE chmod) +x /build/$COMMAND
726             virsh -c lxc:/// lxc-enter-namespace ${BASE} /build/$COMMAND "${options[@]}" -b "${BASE}" "${MAKEVARS[@]}" "${MAKETARGETS[@]}"
727         fi
728
729         # publish to the web so run_log can find them
730         set +e
731         webpublish rm -rf $WEBPATH/$BASE 
732         # guess if we've been doing any debian-related build
733         if [ ! -f $(rootdir $BASE)/etc/debian_version  ] ; then
734             webpublish mkdir -p $WEBPATH/$BASE/{RPMS,SRPMS}
735             webpublish_rsync_dir $WEBPATH/$BASE/RPMS/ $(rootdir $BASE)/build/RPMS/
736             [[ -n "$PUBLISH_SRPMS" ]] && webpublish_rsync_dir $WEBPATH/$BASE/SRPMS/ $(rootdir $BASE)/build/SRPMS/
737         else
738             # run scanpackages so we can use apt-get on this
739             # (not needed on fedora b/c this is done by the regular build already)
740             virsh -c lxc:/// lxc-enter-namespace $BASE /bin/bash -c "(cd /build ; dpkg-scanpackages DEBIAN/ | gzip -9c > Packages.gz)"
741             webpublish mkdir -p $WEBPATH/$BASE/DEBIAN
742             webpublish_rsync_files $WEBPATH/$BASE/DEBIAN/ $(rootdir $BASE)/build/DEBIAN/*.deb 
743             webpublish_rsync_files $WEBPATH/$BASE/ $(rootdir $BASE)/build/Packages.gz
744         fi
745         # publish myplc-release if this exists
746         release=$(rootdir $BASE)/build/myplc-release
747         [ -f $release ] && webpublish_rsync_files $WEBPATH/$BASE $release
748         set -e
749
750         # create yum repo and sign packages.
751         if [ -n "$SIGNYUMREPO" ] ; then
752             # this script does not yet support signing on a remote (webhost) repo
753             sign_here=$(hostname) ; sign_web=$(webpublish hostname)
754             if [ "$hostname" = "$sign_here" ] ; then
755                 sign_node_packages
756             else
757                 echo "$COMMAND does not support signing on a remote yum repo"
758                 echo "you might want to turn off the -y option, or run this on the web server box itself"
759                 exit 1
760             fi
761         fi
762
763         if [ -n "$DO_TEST" ] ; then 
764             run_log
765         fi
766
767         success 
768
769         echo "==================== MAIN END $(date)"    
770     fi
771
772 }
773
774 ##########
775 main "$@"