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