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