have to duplicate bin_in_container..
[build.git] / build.common
1 # -*-Shell-script-*-
2 #
3 # Common functions for build scripts used by various packages
4 # incorporated (e.g., build, bootcd, nodeimage, sliceimage)
5 #
6 # Marc E. Fiuczynski <mef@cs.princeton.edu>
7 # Copyright (C) 2007 The Trustees of Princeton University
8 # Thierry Parmentelat <thierry.parmentelat@inria.fr> INRIA
9 #
10 # supported distros f12 f14 f16 f18 f20 
11 # and debians/ubuntus to a lesser extent
12 #
13 # for locating pkgs.py
14 export PATH=.:$PATH
15
16 # old guests have e.g. mount in /bin but this is no longer part of 
17 # the standard PATH in recent hosts after usrmove, so let's keep it simple
18 export PATH=$PATH:/bin:/sbin
19
20 # would be much simpler if enter-lxc-namespace was looking along a PATH...
21 function bin_in_container () {
22     lxc=$1; shift
23     binary=$1; shift
24     for path in $(echo $PATH | sed -e 's,:, ,g' ); do
25         [ -f /vservers/$lxc/$path/$binary ] && { echo $path/$binary; return; }
26         [ -f /vservers/$lxc/rootfs/$path/$binary ] && { echo $path/$binary; return; }
27     done
28     echo bin_in_container_cannot_find_$binary
29 }
30
31 # returns 'Fedora' or 'CentOS' for now
32 function pl_getDistro() {
33     if [ -f "/etc/redhat-release" ] ; then
34         distro=$(awk ' { print $1 } ' /etc/redhat-release)
35         case $distro in Scientific*) distro="SL" ; esac
36     elif [ -f /etc/lsb-release ] ; then
37         . /etc/lsb-release
38         echo $DISTRIB_CODENAME 
39     elif [ -f /etc/debian_version ] ; then
40         case $(cat /etc/debian_version) in
41             6.*) distro=squeeze ;;
42             7.*)   distro=wheezy  ;;
43             *)     distro=unknown.debian.in.build.common ;;
44         esac
45     fi
46     [ -z "$distro" ] && { echo "build.common.pl_getDistro-unknown"; exit 1; }
47     echo "$distro"
48     return 0
49 }
50
51 # returns something like 8, 10, or 5.3
52 function pl_getRelease() {
53     if [ -f "/etc/redhat-release" ] ; then
54         release=$(awk ' { if ($1=="Fedora" && $2=="Core") print $4 ; if (($1=="Fedora" && $2!="Core")||$1=="CentOS") print $3 ; if ($1=="Scientific") print $4 } ' /etc/redhat-release)
55     else
56         echo "build.common.pl_getRelease-unknown"
57         exit 1
58     fi
59     # keep only the major number
60     echo "$release" | cut -d. -f1
61     return 0
62 }
63
64 # returns distro shortname, something like 'f8' or 'centos5'
65 function pl_getReleaseName () {
66     distro=$1; shift
67     release=$1; shift
68     case $distro in
69         [Ff]edora*)
70             releasename=f$release
71             ;;
72         [Cc]entOS*)
73             old_IFS="$IFS"
74             IFS="."
75             set -- $release
76             IFS="$old_IFS"
77             releasename=centos$1
78             ;;
79         [Ss]L*)
80             releasename=sl$release
81             ;;
82         squeeze|wheezy|oneiric|precise|quantal|raring|saucy)
83             releasename=$distro
84             ;;
85         *)
86             releasename="unknown-name-for-${pl_DISTRO}-please-edit-build.common"
87             echo 1>&2 "build.common: WARNING - releasename not set for distro=$distro" 
88             return 1
89             ;;
90     esac
91     echo "$releasename"
92     return 0
93 }
94
95 # yum exclusions are now defined in yumexclude.pkgs
96 # so they can now depend both on the linux distro and the pl distro
97 function pl_yumexclude () {
98     keyword=$1; shift
99     fcdistro=$1; shift
100     pldistro=$1; shift
101     builddir=$1; shift
102     # search for file "yumexclude.pkgs"
103     yumexclude_file=$(pl_locateDistroFile $builddir $pldistro "yumexclude.pkgs")
104     #
105     # check if pkgs.py is in PATH
106     type -p pkgs.py >& /dev/null || export PATH=$builddir:$PATH
107
108     # parse it
109     pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro $keyword $yumexclude_file || \
110         { echo pl_yumexclude failed with fcdistro=$fcdistro and pldistro=$pldistro; return 1 ; }
111 }
112
113 # <> fcdistro pldistro builddir
114 # node side : use the 'nodeyumexclude' keywork in yumexclude.pkgs
115 function pl_nodeyumexclude () { pl_yumexclude 'nodeyumexclude' "$@" ; }
116 # server side : use the 'plcyumexclude' keywork in yumexclude.pkgs
117 function pl_plcyumexclude () { pl_yumexclude 'plcyumexclude' "$@" ; }
118
119
120 # figure out which redhat distro we are using (fedora, centos, redhat)
121 pl_DISTRO=$(pl_getDistro)
122
123 # select basearch of the host devel environment - protected for macos for local tests
124 # try arch for testing stuff on a mac
125 pl_DISTRO_ARCH=$(uname -i 2>/dev/null || arch 2> /dev/null || echo unknownarch)
126
127 # the release number (plain number)
128 pl_DISTRO_RELEASE=$(pl_getRelease)
129
130 # the release name - something like 'f8' or 'sl6'
131 pl_DISTRO_NAME=$(pl_getReleaseName $pl_DISTRO $pl_DISTRO_RELEASE)
132
133 # get path to appropriate yumgroups.xml file
134 # Thierry: quick & dirty improvement 
135 # this file is updated by the toplevel build, from the .pkgs files
136 pl_DISTRO_YUMGROUPS="../../../RPMS/yumgroups.xml"
137
138 function pl_process_fedora_options () {
139     # Get options
140     shiftcount=0
141     while getopts "l:r:a:h" opt ; do
142         case $opt in
143             l)
144                 pl_DISTRO_URL=$OPTARG
145                 let shiftcount=$shiftcount+2
146                 ;;
147             r)
148                 pl_DISTRO_RELEASE=$OPTARG
149                 let shiftcount=$shiftcount+2
150                 ;;
151             a)
152                 pl_DISTRO_ARCH=$OPTARG
153                 let shiftcount=$shiftcount+2
154                 ;;
155             h|*)
156                 echo "Usage: $0 [OPTION]..."
157                 echo "  -l url          distro mirror location (default: $pl_DISTRO_URL)"
158                 echo "  -r release      distro release number (default: $pl_DISTRO_RELEASE)"
159                 echo "  -a arch         distro architecture (default: $pl_DISTRO_ARCH)"
160                 echo "where distro can be either fedora, centos, or redhat"
161                 echo "  -h              This message"
162                 exit 1
163                 ;;
164         esac
165     done
166     return $shiftcount
167 }
168
169 ######################################## handling a root image
170 function pl_root_rpm_macros () {
171     cat <<EOF
172 %_install_langs C:en_US:en
173 %_netsharedpath /proc:/dev/pts:/usr/share/info
174 %_excludedocs 1
175 %__file_context_path /dev/null
176 EOF
177 }
178
179 function pl_root_makedevs() {
180     vroot=$1
181     # Clean ${vroot}/dev, but only when ${vroot}!=""
182     [ -n $vroot ] && rm -rf $vroot/dev
183     
184     mkdir -p $vroot/dev
185     mknod -m 666 $vroot/dev/null c 1 3
186     mknod -m 666 $vroot/dev/zero c 1 5
187     mknod -m 666 $vroot/dev/full c 1 7
188     mknod -m 644 $vroot/dev/random c 1 8
189     mknod -m 644 $vroot/dev/urandom c 1 9
190     mknod -m 666 $vroot/dev/tty c 5 0
191     mknod -m 666 $vroot/dev/ptmx c 5 2
192     # For bash command substitution
193     ln -nsf ../proc/self/fd $vroot/dev/fd
194
195     # For df and linuxconf
196     touch $vroot/dev/hdv1
197
198     # For pseudo ttys
199     mkdir -p $vroot/dev/pts
200
201     # for tmpfs mount
202     mkdir -p $vroot/dev/shm
203
204     # For TUN/TAP
205     mkdir -p $vroot/dev/net
206     mknod -m 600 $vroot/dev/net/tun c 10 200
207
208     # For mkinitrd (in case a kernel is being installed)
209     # As well as for loop back mounting within a vm. 
210     for i in $(seq 0 255) ; do
211         mknod -m 640 $vroot/dev/loop$i b 7 $i
212     done
213 }
214
215 function mkfedora_usage() {
216     echo "Usage: pl_root_mkfedora [OPTION]... basedir pldistro pkgsfile(s)"
217     echo "      -l url          Fedora mirror location."
218     echo "                      Defaults are searched in <pldistro>.mirrors"
219     echo "      -v              Be verbose"
220     echo "      -h              This message"
221     echo " target selection (defaults based on current build VM context)"
222     echo "      -r release      Fedora release number (default: $releasever)"
223     echo "      -a arch         Fedora architecture (default: $basearch)"
224     exit 1
225 }
226
227 function pl_root_mkfedora () {
228
229     echo "* Entering pl_root_mkfedora" "$@"
230
231     if [ $UID -ne 0 ] ; then
232         echo "Error: You must run this script as root."
233         exit 1
234     fi
235
236 # Verbosity
237     verbose=0
238
239 # Release and architecture to install : defaults to current vm settings or previously parsed fedora_options
240     releasever=$pl_DISTRO_RELEASE
241     basearch=$pl_DISTRO_ARCH
242
243 # Get options
244     while getopts "vh" opt ; do
245         case $opt in
246             v) verbose=1; set -x ;;
247             h|*) mkfedora_usage ;;
248         esac
249     done
250
251     shift $(($OPTIND - 1))
252     [[ "$#" -lt 3 ]] && mkfedora_usage
253     vroot=$1 ; shift
254     pldistro=$1 ; shift
255     pkgsfile="$@"
256     vroot=$(cd $vroot && pwd -P)
257     [ -d $vroot ] || mkfedora_usage
258
259
260     # parse pkgsfile and add to local vars
261     fcdistro=${pl_DISTRO_NAME}
262     pkgs_packages=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro package $pkgsfile) 
263     pkgs_groups=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro group $pkgsfile)
264     # what can get trashed to save space
265     pkgs_junk=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro junk $pkgsfile)
266     # but not this
267     pkgs_precious=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro precious $pkgsfile)
268     # formerly related to mkfedora -k : packages to take from our own build 
269     # and thus need be excluded frem the stock repos
270     # locate builddir by looking for pkgs.py
271     builddir=$(dirname $(type -p pkgs.py))
272     SUBST_NODEYUMEXCLUDE=$(pl_nodeyumexclude $fcdistro $pldistro $builddir)
273     pkgs_yumexclude=$(pkgs.py -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro yumexclude $pkgsfile | sed -e s,@NODEYUMEXCLUDE@,"$SUBST_NODEYUMEXCLUDE",)
274     # get mirrors if not specified with -l
275     if [ -z "$mirrors" ] ; then
276         mirrorsfile=$(pl_locateDistroFile ../build/ $pldistro "$pldistro.mirrors")
277         # do not sort mirrors, keep order from input
278         mirrors=$(pkgs.py -u -a $pl_DISTRO_ARCH -f $fcdistro -d $pldistro mirror $mirrorsfile)
279     fi
280
281     yumexclude_line=""
282     [ -n "$pkgs_yumexclude" ] && yumexclude_line="exclude=$pkgs_yumexclude"
283
284     echo "$0: candidate mirrors"
285     for mirror in $mirrors ; do
286         echo "* candidate mirror $mirror"
287     done
288
289     # the repo part of the final yum.conf
290     yum_conf_repos=$vroot/xxxmkfedora-repos.confxxx
291     if ! yumconf_mirrors $yum_conf_repos ../build/ $fcdistro "$yumexclude_line" $mirrors ; then
292         echo xxx -- error ; return 1
293     fi
294     
295     # Do not tolerate errors
296     set -e
297
298     public_gpg_key=$(yumconf_gpgkey $yum_conf_repos)
299
300     ## make rpms ignore installing stuff to special fs entries like /proc
301     # Because of https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=52725
302     # you have to use at least one language beside 'C'
303     # Prevent all locales from being installed in reference image
304     mkdir -p $vroot/etc/rpm
305     pl_root_rpm_macros > $vroot/etc/rpm/macros 
306
307     # Trick rpm and yum, who read the real root /etc/rpm/macros file
308     # rather than the one installed in the reference image, despite what
309     # you might expect the --root and --installroot options to mean. Both
310     # programs always read $HOME/.rpmmacros.
311     export HOME=$vroot/tmp
312     mkdir -p $vroot/tmp
313     pl_root_rpm_macros > $vroot/tmp/.rpmmacros
314
315     function mkfedora_cleanup () {
316         umount -l $vroot/proc
317         umount -l $vroot/dev/shm
318         umount -l $vroot/dev/pts
319     }
320
321     # Clean up before exiting if anything goes wrong
322     trap "mkfedora_cleanup" ERR INT
323
324     # Mount in reference image
325     mount -t devpts none $vroot/dev/pts
326     mount -t tmpfs none $vroot/dev/shm
327     mkdir -p $vroot/proc
328     mount -t proc none $vroot/proc
329     
330     # Create a /var/lib dirs for yum & rpm
331     mkdir -p $vroot/var/lib/yum
332     mkdir -p $vroot/var/lib/rpm
333     mkdir -p $vroot/usr/share/info
334
335     # Create a dummy /etc/fstab in reference image
336     mkdir -p $vroot/etc
337     cat >$vroot/etc/fstab <<EOF
338 # This fake fstab exists only to please df and linuxconf.
339 /dev/hdv1       /       ext2    defaults        1 1
340 EOF
341     cp $vroot/etc/fstab $vroot/etc/mtab
342
343     # Necessary for some scripts
344     mkdir -p $vroot/etc/sysconfig
345     echo "NETWORKING=yes" > $vroot/etc/sysconfig/network
346
347     # Initialize RPM database in reference image
348     mkdir -p $vroot/var/lib/rpm
349     rpm --root $vroot --initdb
350     rpm --root $vroot --import $public_gpg_key
351
352     # Initialize yum in reference image
353     mkdir -p $vroot/var/cache/yum $vroot/var/log
354
355 # yum.conf is for building only - store in different location than /etc/yum.conf
356     yum_conf=$vroot/etc/mkfedora-yum.conf
357     cat > $yum_conf <<EOF
358 [main]
359 cachedir=/var/cache/yum
360 debuglevel=2
361 logfile=/var/log/yum.log
362 pkgpolicy=newest
363 multilib_policy=best
364 distroverpkg=redhat-release
365 tolerant=1
366 exactarch=1
367 retries=20
368 obsoletes=1
369 gpgcheck=0
370 # Prevent yum-2.4 from loading additional repository definitions
371 # (e.g., from /etc/yum.repos.d/)
372 reposdir=/dev/null
373 EOF
374     
375     cat $yum_conf_repos >> $yum_conf
376
377     # If we are being built as part of an automated RPM build, solve the
378     # bootstrap problem by including any just built packages in the yum
379     # configuration. This cooperates with the PlanetLab build system.
380     if [ -n "$RPM_BUILD_DIR" ] ; then
381         RPM_RPMS_DIR=$(cd $(dirname $RPM_BUILD_DIR)/RPMS && pwd -P)
382         # If run under sudo, allow user to delete the headers/ and
383         # repodata/ directories.
384         if [ -n "$SUDO_USER" ] ; then
385             chown -R $SUDO_USER $RPM_RPMS_DIR
386         fi
387         cat >> $yum_conf <<EOF
388
389 [building]
390 name=Building - $basearch - $RPM_RPMS_DIR/
391 baseurl=file://$RPM_RPMS_DIR/
392 EOF
393 fi
394
395     echo "========== Dumping $yum_conf"
396     cat $yum_conf
397     echo "========== EndDump $yum_conf"
398
399     yum_options=""
400 #    yum --help | grep verbose &> /dev/null && yum_options="$yum_options --verbose"
401     yum_options="$yum_options -y"
402     yum_options="$yum_options -c $yum_conf"
403     yum_options="$yum_options --installroot=$vroot"
404
405     # glibc must be specified explicitly for the correct arch to be
406     # chosen.
407     echo "* Installing glibc"
408     # ignore yum's return code that is basically undefined
409     yum $yum_options install glibc || :
410
411     # Go, baby, go
412     if [ -n "$pkgs_packages" ] ; then
413         echo "* Installing optional packages" $pkgs_packages
414         # ignore yum's return code that is basically undefined
415         echo "* Install options" $vroot $yum_options 
416         yum $yum_options install $pkgs_packages || :
417         if ! rpm --root $vroot -q $pkgs_packages >/dev/null ; then
418             echo "* Warning: Missing packages"
419             rpm --root $vroot -q $pkgs_packages | grep "not installed"
420         fi
421     fi
422
423     if [ -n "$pkgs_groups" ] ; then
424        ## call yum sequentially to get finer-grained info on dependencies
425         for group_plus in $pkgs_groups ; do
426             group=$(echo $group_plus | sed -e "s,+++, ,g")
427             echo "* Installing optional group $group" 
428             # ignore yum's return code that is basically undefined
429             yum $yum_options groupinstall "$group" || :
430         done
431     fi
432
433     # formerly in bootcd/prep.sh : to optimize footprint
434     if [ -n "$pkgs_junk" ] ; then
435         echo "* Removing unnecessary junk"
436         pushd $vroot
437         # Save precious files
438         [ -n "$pkgs_precious" ] && tar --ignore-failed-read -cpf precious.tar $pkgs_precious
439         # Remove unnecessary junk
440         [ -n "$pkgs_junk" ] && rm -rf $pkgs_junk
441         # Restore precious files
442         [ -n "$pkgs_precious" ] && tar -xpf precious.tar && rm -f precious.tar
443         popd
444     fi
445
446     # Clean yum cache
447     echo "* Cleaning up"
448
449     # NOTE: this hack is for Fedora >= 12.
450     # if kernel-debug is installed, clean it up
451     # we link to our version of kernel/initrd and clean up
452     # kernel-debug manually
453     if rpm --root $vroot --quiet -q kernel-debug ; then
454         echo "* Cleaning up kernel-debug - (workaround for f12)"
455         pushd $vroot/boot/
456         rm -rf kernel-boot kernel-bootsmp initrd-boot initrd-bootsmp
457         ln -s vmlinuz-*${pldistro}* kernel-boot
458         ln -s vmlinuz-*${pldistro}* kernel-bootsmp
459         ln -s initrd-*${pldistro}* initrd-boot
460         ln -s initrd-*${pldistro}* initrd-bootsmp
461         rpm --root $vroot --nodeps -e kernel-debug || :
462         popd
463     fi
464
465     # ignore yum's return code that is basically undefined
466     yum $yum_options clean all || :
467
468     # Clean RPM state
469     rm -f $vroot/var/lib/rpm/__db*
470
471     # Set time zone to UTC
472     if [ -f $vroot/usr/share/zoneinfo/UTC -a -f $vroot/etc/localtime ] ; then
473         rm -f $vroot/etc/localtime
474         ln -s /usr/share/zoneinfo/UTC $vroot/etc/localtime
475     fi
476
477     echo "Dumping current list of rpms in /etc/mkfedora-rpms.txt"
478     chroot $vroot rpm -aq | sort > $vroot/etc/mkfedora-rpms.txt
479
480     # remove trap handler, as we are about to call it directly.
481     trap - ERR INT
482
483     # Clean up
484     mkfedora_cleanup
485
486     return 0
487 }
488
489 function pl_root_tune_image () {
490     root=$1; shift
491
492     # Disable all services in reference image
493     chroot $root sh -c "/sbin/chkconfig --list | awk '{ print \$1 }' | xargs -i /sbin/chkconfig {} off"
494
495     # FC2 minilogd starts up during shutdown and makes unmounting
496     # impossible. Just get rid of it.
497     rm -f $root/sbin/minilogd
498     ln -nsf /bin/true $root/sbin/minilogd
499
500     # This tells the Boot Manager that it is okay to update
501     # /etc/resolv.conf and /etc/hosts whenever the network configuration
502     # changes. Users are free to delete this file.
503     touch $root/etc/AUTO_UPDATE_NET_FILES
504 }
505
506 # Move specified directories out of a src tree into a dst tree, and
507 # then for each moved directory create a symlink in src to dst.
508 function pl_move_dirs() {
509     root=$1
510     data=$2
511     store=$3
512     shift 3
513
514     mkdir -p $root/data
515     for datadir in "$@" ; do
516         mkdir -p ${data}${datadir}
517         if [ -d ${root}/${datadir} -a ! -h ${root}/${datadir} ] ; then
518             (cd ${root} && find ./${datadir} | cpio -p -d -u ../${data}/)
519         fi
520         rm -rf ${root}/${datadir}
521         mkdir -p $(dirname ${root}/${datadir})
522         ln -nsf ${store}/${datadir} ${root}/${datadir}
523     done
524 }
525
526 # Construct an image file from given some directory
527 # XXX in the future maybe use livecdtools?
528 function pl_make_image() {
529     root=$1
530     image=$2
531     extraspace=$3
532
533     # Leave about 100 MB free space and allow for about 20% inode overhead
534     bytes=$((($(du -sb $root | cut -f1) + $extraspace) * 120 / 100))
535     bs=4096
536     blocks=$(($bytes / $bs))
537     dd bs=$bs count=$blocks if=/dev/zero of=$image
538     mkfs.ext3 -b $bs -j -F $image
539
540     # Temporarily mount it
541     tmp=$(mktemp -d tmp.XXXXXX)
542     mount -o loop $image $tmp
543     trap "umount $tmp; rmdir $tmp" ERR INT
544
545     # Move files to it
546     (cd $root && tar cpf - .) | (cd $tmp && tar xpf -)
547
548     # Unmount it
549     umount $tmp
550     rmdir $tmp
551     trap - ERR INT
552 }
553
554 # Fix permissions on tmp directories
555 function pl_fixtmp_permissions() {
556     root=$1
557     chmod 1777 $root/tmp $root/usr/tmp $root/var/tmp
558 }
559
560 function pl_fixdirs() {
561     root=$1
562     datadirs=$2
563     for datadir in datadirs ; do
564         if [ -h ${root}/${datadir} ] ; then
565             rm -f ${root}/${datadir}
566             mkdir -p ${root}/${datadir}
567         fi
568     done
569 }
570
571 ########## .pkgs format
572 # Usage: pl_parsePkgs keyword [-a arch] fcdistro pldistro pkgs-file[..s]
573 # pkgs.py should be found in PATH, like this file build.common
574 # only usage should be for pl_getPackages and pl_getGroups,
575 # which in turn are usednow be in {node,slice}image/build.sh
576 function pl_parsePkgs () {
577     target_arch=$pl_DISTRO_ARCH
578     keyword=$1;shift
579     [ "$1" == "-a" ] && { shift; target_arch="$1"; shift; }
580     fcdistro=$1; shift
581     pldistro=$1; shift
582
583     echo 1>&2 "pl_parsePkgs: using -a $target_arch -f $fcdistro -d $pldistro $keyword $@"
584     pkgs.py -a $target_arch -f $fcdistro -d $pldistro $keyword "$@" 
585 }
586 # usage: pl_getPackages [-a arch] fcdistro pldistro pkg-file[..s]
587 function pl_getPackages() { pl_parsePkgs package "$@" ; }
588 function pl_getGroups() { pl_parsePkgs group "$@" ; }
589
590 ##############################
591
592 # locates a pldistro-dependant file
593 # tries first in build/<pldistro>/, then in build/planetlab/
594 function pl_locateDistroFile () {
595     builddir=$1; shift
596     pldistro=$1; shift
597     pkgsfile=$1; shift
598
599     pkgspath=""
600     # if config dir is missing but a .svnpath or a .gitpath exists, use it to extract the config dir
601     configdir="$builddir/config.${pldistro}"
602     if [ ! -d $configdir ] ; then
603         if [ -f "${configdir}.svnpath" -o -f "${configdir}.gitpath" ] ; then
604             echo 1>&2 "Invoking make to extract remote config.${pldistro}"
605             # we set PLDISTROTAGS here to /dev/null because when dealing with remote distros
606             # at a very early stage (like searching for devel.pkgs even before the build VM is created)
607             # then make screams because it cannot find a mandatory include file
608             # OTOH this mechanism here is not intended to depend on tags specifically
609             make 1>&2 --no-print-directory -C $builddir stage1=true config.${pldistro} PLDISTROTAGS=/dev/null
610         fi
611     fi
612     # locate it
613     paths="$builddir/config.$pldistro/$pkgsfile $builddir/config.planetlab/$pkgsfile"
614     for path in $paths; do
615         if [ -f $path ] ; then
616             pkgspath=$path
617             break
618         fi
619     done
620     if [ -z "$pkgspath" ] ; then
621         echo 1>&2 "pl_locateDistroFile - in $(pwd) : cannot locate $pkgsfile in $builddir"
622         echo 1>&2 "candidates were $paths"
623         echo "not-found-by-pl_locateDistroFile"
624         return 1
625     else
626         echo 1>&2 "pl_locateDistroFile: using $pkgspath"
627         echo $pkgspath
628         return 0
629     fi
630 }
631
632 function yumgroups_from_pkgs () {
633     builddir=$1; shift
634     pldistro=$1; shift
635     fcdistro=$1; shift
636     pkgsnames=$@
637
638     sedargs="-e s,@FCDISTRO@,$fcdistro,g"
639
640    cat <<__header
641 <?xml version="1.0"?>
642 <!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd">
643 <comps>
644 __header
645
646     for pkgsname in $pkgsnames; do
647         pkgsfile=$(pl_locateDistroFile $builddir $pldistro $pkgsname)
648         packages=$(pl_getPackages $fcdistro $pldistro $pkgsfile)
649
650         groupname=$(pkgs.py groupname $pkgsfile | sed $sedargs)
651         groupdesc=$(pkgs.py groupdesc $pkgsfile | sed $sedargs)
652
653         if [ -z "$groupname" -o -z "$groupdesc" ] ; then
654             echo "Cannot find groupname: and groupdesc: in $pkgsfile -- skipped" 1>&2
655             continue
656         fi
657         
658         cat << __group_header
659   <group>
660     <id>$(echo $groupname|tr A-Z a-z)</id>
661     <name>$groupname</name>
662     <description>$groupdesc</description>
663     <uservisible>true</uservisible>
664     <packagelist>
665 __group_header
666         for package in $packages; do 
667             echo "<packagereq type=\"mandatory\">$package</packagereq>"
668         done
669         cat << __group_footer
670     </packagelist>
671   </group>
672 __group_footer
673     done
674 cat <<__footer
675 </comps>
676 __footer
677 }
678
679
680 function build_fetch () {
681     curl --fail --silent --max-time 60 --output /dev/null "$1" 
682 }
683
684 # tries to compute a valid yum.conf for that pldistro from the template in mirroring/
685 # returns 0 and writes <dest_yumconf> on success
686 # returns 1 on failure, in which case <dest_yumconf> is deleted
687 function yumconf_mirrors () {
688     dest_yumconf=$1; shift
689     builddir=$1; shift
690     fcdistro=$1; shift
691     yumexclude_line="$1" ; shift
692     mirrors="$@"
693
694     template=$builddir/mirroring/$fcdistro/yum.repos.d/building.repo.in
695     
696     if [ ! -f $template ] ; then
697         echo "yumconf_mirrors: cannot locate template $template"
698         rm -f $dest_yumconf
699         return 1
700     fi
701
702     for mirror in $mirrors; do
703         if yumconf_mirror $dest_yumconf $template "$yumexclude_line" $mirror; then
704             return 0
705         fi
706     done
707     echo 'yumconf_mirrors in build.common : ran out of mirrors -- BAILING OUT'
708     rm -f $dest_yumconf
709     return 1
710 }
711
712 # computes a yum.conf from the template, and checks that all baseurl defined in there are valid repos
713 # returns 0 on success and 1 on failure
714 function yumconf_mirror () {
715     dest_yumconf=$1; shift
716     template=$1; shift
717     yumexclude_line="$1" ; shift
718     mirror=$1; shift
719
720     sed -e "s,@MIRRORURL@,$mirror,g" \
721         -e "/baseurl=/i\\
722 $yumexclude_line" $template > $dest_yumconf
723     
724     # capture all lines defining baseurl
725     baseurl_defs=$(grep '^baseurl=' $dest_yumconf)
726     if [ -z "$baseurl_defs" ] ; then
727         return 1
728     fi
729
730     for baseurl_def in $baseurl_defs; do
731         baseurl=$(echo $baseurl_def | sed \
732             -e s,baseurl=,, \
733             -e 's,$basearch,'"$pl_DISTRO_ARCH",g)
734         repomd=$baseurl/repodata/repomd.xml
735
736         echo "* Trying to fetch $repomd"
737         if ! build_fetch $repomd ; then
738             echo "* Failed to fetch $repomd"
739             return 1
740         fi
741     done
742     echo "* Selected mirror $mirror"
743     return 0
744 }
745
746 # from a yum.conf as generated above, computes the gpgkey urls
747 function yumconf_gpgkey () {
748     dest_yumconf=$1; shift
749
750     values=$(grep -h '^gpgkey=' $dest_yumconf | sed -e s,gpgkey=,, | sed -e 's,$basearch,'"$pl_DISTRO_ARCH",g | sed -e 's, ,\n,g' | sort | uniq | xargs)
751     [ -n "$values" ] || return 1
752     echo $values
753     return 0
754 }
755
756 # patches a yum conf to insert an exclude line in each declared repo
757 function yumconf_exclude () {
758     repo=$1; shift
759     yumexclude_line="$1" ; shift
760     
761     sed -i -e "/#baseurl=.*$/i\\
762 $yumexclude_line" $repo
763 }