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