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