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