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