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