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