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