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