major cleanup of lxc vm creation script
[build.git] / lbuild-initvm.sh
1 #!/bin/bash
2 # -*-shell-*-
3
4 #shopt -s huponexit
5
6 COMMAND=$(basename $0)
7 DIRNAME=$(dirname $0)
8 BUILD_DIR=$(pwd)
9
10 # pkgs parsing utilities
11 PATH=$(dirname $0):$PATH export PATH
12 . build.common
13
14 DEFAULT_FCDISTRO=f20
15 DEFAULT_PLDISTRO=lxc
16 DEFAULT_PERSONALITY=linux64
17
18 COMMAND_LBUILD="lbuild-initvm.sh"
19 COMMAND_LTEST="ltest-initvm.sh"
20
21 ##########
22 # when creating build boxes we use private NAT'ed addresses for the VMs
23 # as per virbr0 that is taken care of by libvirt at startup
24 PRIVATE_PREFIX="192.168.122."
25 PRIVATE_GATEWAY="192.168.122.1"
26 # beware that changing this would break the logic of random_private_byte...
27 PRIVATE_MASKLEN=24
28
29 # we just try randomly in that range until a free IP address shows up
30 PRIVATE_ATTEMPTS=20
31
32 # constant
33 INTERFACE_BRIDGE=br0
34
35 # the network interface name as seen from the container
36 VIFNAME=eth0
37
38 ##############################
39 ## stolen from tests/system/template-qemu/qemu-bridge-init
40 # use /proc/net/dev instead of a hard-wired list
41 function gather_interfaces () {
42     python <<EOF
43 for line in file("/proc/net/dev"):
44     if ':' not in line: continue
45     ifname=line.replace(" ","").split(":")[0]
46     if ifname.find("lo")==0: continue
47     if ifname.find("br")==0: continue
48     if ifname.find("virbr")==0: continue
49     if ifname.find("tap")==0: continue
50     print ifname
51 EOF
52 }
53
54 function discover_interface () {
55     for ifname in $(gather_interfaces); do
56         ip link show $ifname | grep -qi 'state UP' && { echo $ifname; return; }
57     done
58     # still not found ? that's bad
59     echo unknown
60 }
61 ########## check for a free IP
62 function ip_is_busy () {
63     target=$1; shift
64     ping -c 1 -W 1 $target >& /dev/null
65 }
66
67 function random_private_byte () {
68     for attempt in $(seq $PRIVATE_ATTEMPTS); do
69         byte=$(($RANDOM % 256))
70         if [ "$byte" == 0 -o "$byte" == 1 ] ; then continue; fi
71         ip=${PRIVATE_PREFIX}${byte}
72         ip_is_busy $ip || { echo $byte; return; }
73     done
74     echo "Cannot seem to find a free IP address in range ${PRIVATE_PREFIX}.xx/24 after $PRIVATE_ATTEMPTS attempts - exiting"
75     exit 1
76 }
77
78 ########## networking -- ctd
79 function gethostbyname () {
80     hostname=$1
81     python -c "import socket; print socket.gethostbyname('"$hostname"')" 2> /dev/null
82 }
83
84 # e.g. 21 -> 255.255.248.0
85 function masklen_to_netmask () {
86     masklen=$1; shift
87     python <<EOF
88 import sys
89 masklen=$masklen
90 if not (masklen>=1 and masklen<=32): 
91   print "Wrong masklen",masklen
92   exit(1)
93 result=[]
94 for i in range(4):
95     if masklen>=8:
96        result.append(8)
97        masklen-=8
98     else:
99        result.append(masklen)
100        masklen=0
101 print ".".join([ str(256-2**(8-i)) for i in result ])
102   
103 EOF
104 }
105
106 #################### bridge initialization
107 function create_bridge_if_needed() {
108    
109     # turn on verbosity
110     set -x
111
112     # already created ? - we're done
113     ip addr show $INTERFACE_BRIDGE >& /dev/null && {
114         echo "Bridge already set up - skipping create_bridge_if_needed"
115         return 0
116     }
117
118     # find out the physical interface to bridge onto
119     if_lan=$(discover_interface)
120
121     ip addr show $if_lan &>/dev/null || {
122         echo "Cannot use interface $if_lan - exiting"
123         exit 1
124     }
125
126     #################### bride initialization
127     check_yum_installed bridge-utils
128
129     echo "========== $COMMAND: entering create_bridge - beg"
130     hostname
131     uname -a
132     ip addr show
133     ip route
134     echo "========== $COMMAND: entering create_bridge - end"
135
136     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
137     #
138     # another option would be to accept the all forward packages for
139     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
140     sysctl net.bridge.bridge-nf-call-iptables=0
141     sysctl net.bridge.bridge-nf-call-ip6tables=0
142     sysctl net.bridge.bridge-nf-call-arptables=0
143
144     
145     #Getting host IP/masklen
146     address=$(ip addr show $if_lan | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
147     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $if_lan" ; exit 1 ; }
148
149     broadcast=$(ip addr show $if_lan | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
150     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $if_lan"
151
152     gateway=$(ip route show | grep default | awk '{print $3;}')
153     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
154
155
156     # creating the bridge
157     echo "Creating bridge INTERFACE_BRIDGE=$INTERFACE_BRIDGE"
158     brctl addbr $INTERFACE_BRIDGE
159     brctl addif $INTERFACE_BRIDGE $if_lan
160     echo "Activating promiscuous mode if_lan=$if_lan"
161     ip link set $if_lan up promisc on
162     sleep 2
163     # rely on dhcp to re assign IP.. 
164     echo "Starting dhclient on $INTERFACE_BRIDGE"
165     dhclient $INTERFACE_BRIDGE
166     sleep 1
167
168     #Reconfigure the routing table
169     echo "Configuring gateway=$gateway"
170     ip route add default via $gateway dev $INTERFACE_BRIDGE
171     ip route del default via $gateway dev $if_lan
172     # at this point we have an extra route like e.g.
173     ## ip route show
174     #default via 138.96.112.250 dev br0
175     #138.96.112.0/21 dev em1  proto kernel  scope link  src 138.96.112.57
176     #138.96.112.0/21 dev br0  proto kernel  scope link  src 138.96.112.57
177     #192.168.122.0/24 dev virbr0  proto kernel  scope link  src 192.168.122.1
178     route_dest=$(ip route show | grep -v default | grep "dev $INTERFACE_BRIDGE" | awk '{print $1;}')
179     ip route del $route_dest dev $if_lan
180
181     echo "========== $COMMAND: exiting create_bridge - beg"
182     ip addr show
183     ip route show
184     echo "========== $COMMAND: exiting create_bridge - end"
185
186     # for safety
187     sleep 3
188     return 0
189
190 }
191
192
193 ##############################
194 function check_yum_installed () {
195     package=$1; shift
196     rpm -q $package >& /dev/null || yum -y install $package
197 }
198
199 function check_yumgroup_installed () {
200     group="$1"; shift
201     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
202 }
203
204 ##############################
205
206 function configure_fedora() {
207
208     # disable selinux in fedora
209     mkdir -p $rootfs_path/selinux
210     echo 0 > $rootfs_path/selinux/enforce
211
212    # configure the network 
213
214     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$VIFNAME
215 DEVICE=$VIFNAME
216 BOOTPROTO=static
217 ONBOOT=yes
218 HOSTNAME=$HOSTNAME
219 IPADDR=$IP
220 NETMASK=$NETMASK
221 GATEWAY=$GATEWAY
222 NM_CONTROLLED=no
223 TYPE=Ethernet
224 MTU=1500
225 EOF
226
227     # set the hostname
228     case "$fcdistro" in 
229         f18|f2?)
230             cat <<EOF > ${rootfs_path}/etc/hostname
231 $HOSTNAME
232 EOF
233             echo ;;
234         *)
235             cat <<EOF > ${rootfs_path}/etc/sysconfig/network
236 NETWORKING=yes
237 HOSTNAME=$HOSTNAME
238 EOF
239             # set minimal hosts
240             cat <<EOF > $rootfs_path/etc/hosts
241 127.0.0.1 localhost $HOSTNAME
242 EOF
243             echo ;;
244     esac
245
246     dev_path="${rootfs_path}/dev"
247     rm -rf $dev_path
248     mkdir -p $dev_path
249     mknod -m 666 ${dev_path}/null c 1 3
250     mknod -m 666 ${dev_path}/zero c 1 5
251     mknod -m 666 ${dev_path}/random c 1 8
252     mknod -m 666 ${dev_path}/urandom c 1 9
253     mkdir -m 755 ${dev_path}/pts
254     mkdir -m 1777 ${dev_path}/shm
255     mknod -m 666 ${dev_path}/tty c 5 0
256     mknod -m 666 ${dev_path}/tty0 c 4 0
257     mknod -m 666 ${dev_path}/tty1 c 4 1
258     mknod -m 666 ${dev_path}/tty2 c 4 2
259     mknod -m 666 ${dev_path}/tty3 c 4 3
260     mknod -m 666 ${dev_path}/tty4 c 4 4
261     mknod -m 600 ${dev_path}/console c 5 1
262     mknod -m 666 ${dev_path}/full c 1 7
263     mknod -m 600 ${dev_path}/initctl p
264     mknod -m 666 ${dev_path}/ptmx c 5 2
265
266     #echo "setting root passwd to $root_password"
267     #echo "root:$root_password" | chroot $rootfs_path chpasswd
268
269     return 0
270 }
271
272 function configure_fedora_init() {
273
274     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
275     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
276     # don't mount devpts, for pete's sake
277     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.sysinit
278     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.d/rc.sysinit
279     chroot ${rootfs_path} /sbin/chkconfig udev-post off
280     chroot ${rootfs_path} /sbin/chkconfig network on
281 }
282
283 # this code of course is for guests that do run on systemd
284 function configure_fedora_systemd() {
285     # so ignore if we can't find /etc/systemd at all 
286     [ -d ${rootfs_path}/etc/systemd ] || return 0
287     # otherwise let's proceed
288     ln -sf /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
289     touch ${rootfs_path}/etc/fstab
290     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/udev.service
291 # Thierry - Feb 2013
292 # this was intended for f16 initially, in order to enable getty that otherwise would not start
293 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
294 # VM's that refuse to lxc-stop and VM's that run crazy getty's
295 # so, turning getty off for now instead
296 #   #dependency on a device unit fails it specially that we disabled udev
297 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
298     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
299     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
300 # can't seem to handle this one with systemctl
301     chroot ${rootfs_path} /sbin/chkconfig network on
302 }
303
304 function download_fedora() {
305 set -x
306     # check the mini fedora was not already downloaded
307     INSTALL_ROOT=$cache/partial
308     echo $INSTALL_ROOT
309
310     # download a mini fedora into a cache
311     echo "Downloading fedora minimal ..."
312
313     mkdir -p $INSTALL_ROOT
314     if [ $? -ne 0 ]; then
315         echo "Failed to create '$INSTALL_ROOT' directory"
316         return 1
317     fi
318
319     mkdir -p $INSTALL_ROOT/etc/yum.repos.d   
320     mkdir -p $INSTALL_ROOT/dev
321     mknod -m 0444 $INSTALL_ROOT/dev/random c 1 8
322     mknod -m 0444 $INSTALL_ROOT/dev/urandom c 1 9
323
324     # copy yum config and repo files
325     cp /etc/yum.conf $INSTALL_ROOT/etc/
326     cp /etc/yum.repos.d/fedora* $INSTALL_ROOT/etc/yum.repos.d/
327
328     # append fedora repo files with desired $release and $basearch
329     for f in $INSTALL_ROOT/etc/yum.repos.d/*
330     do
331       sed -i "s/\$basearch/$arch/g; s/\$releasever/$release/g;" $f
332     done 
333
334     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
335     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
336     # with fedora18 the rpms are scattered by first name
337     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
338     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
339     found=""
340     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
341         if curl -f $attempt -o $RELEASE_TARGET ; then
342             echo "Retrieved $attempt"
343             found=true
344             break
345         else
346             echo "Failed attempt $attempt"
347         fi
348     done
349     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
350     
351     mkdir -p $INSTALL_ROOT/var/lib/rpm
352     rpm --root $INSTALL_ROOT  --initdb
353     # when installing f12 this apparently is already present, so ignore result
354     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm || :
355     # however f12 root images won't get created on a f18 host
356     # (the issue here is the same as the one we ran into when dealing with a vs-box)
357     # in a nutshell, in f12 the glibc-common and filesystem rpms have an apparent conflict
358     # >>> file /usr/lib/locale from install of glibc-common-2.11.2-3.x86_64 conflicts 
359     #          with file from package filesystem-2.4.30-2.fc12.x86_64
360     # in fact this was - of course - allowed by f12's rpm but later on a fix was made 
361     #   http://rpm.org/gitweb?p=rpm.git;a=commitdiff;h=cf1095648194104a81a58abead05974a5bfa3b9a
362     # So ideally if we want to be able to build f12 images from f18 we need an rpm that has
363     # this patch undone, like we have in place on our f14 boxes (our f14 boxes need a f18-like rpm)
364
365     YUM="yum --installroot=$INSTALL_ROOT --nogpgcheck -y"
366     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
367     echo "$YUM install $PKG_LIST"
368     $YUM install $PKG_LIST
369
370     if [ $? -ne 0 ]; then
371         echo "Failed to download the rootfs, aborting."
372         return 1
373     fi
374
375     mv "$INSTALL_ROOT" "$cache/rootfs"
376     echo "Download complete."
377
378     return 0
379 }
380
381
382 function copy_fedora() {
383 set -x
384     # make a local copy of the minifedora
385     echo -n "Copying rootfs to $rootfs_path ..."
386     mkdir -p $rootfs_path
387     rsync -a $cache/rootfs/ $rootfs_path/
388     return 0
389 }
390
391
392 function update_fedora() {
393 set -x
394     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
395     $YUM update
396 }
397
398
399 function install_fedora() {
400     set -x
401
402     mkdir -p /var/lock/subsys/
403     (
404         flock -n -x 200
405         if [ $? -ne 0 ]; then
406             echo "Cache repository is busy."
407             return 1
408         fi
409
410         echo "Checking cache download in $cache/rootfs ... "
411         if [ ! -e "$cache/rootfs" ]; then
412             download_fedora
413             if [ $? -ne 0 ]; then
414                 echo "Failed to download 'fedora base'"
415                 return 1
416             fi
417         else
418             echo "Cache found. Updating..."
419             update_fedora
420             if [ $? -ne 0 ]; then
421                 echo "Failed to update 'fedora base', continuing with last known good cache"
422             else
423                 echo "Update finished"
424             fi
425         fi
426
427         echo "Copy $cache/rootfs to $rootfs_path ... "
428         copy_fedora
429         if [ $? -ne 0 ]; then
430             echo "Failed to copy rootfs"
431             return 1
432         fi
433
434         return 0
435
436         ) 200>/var/lock/subsys/lxc
437
438     return $?
439 }
440
441
442 # overwrite lxc's internal yum config
443 function configure_yum_in_lxc () {
444     set -x 
445     set -e 
446     trap failure ERR INT
447
448     lxc=$1; shift
449     fcdistro=$1; shift
450     pldistro=$1; shift
451
452     echo "Initializing yum.repos.d in $lxc"
453     rm -f $rootfs_path/etc/yum.repos.d/*
454
455     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
456 [fedora]
457 name=Fedora $release - $arch
458 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os/
459 enabled=1
460 metadata_expire=7d
461 gpgcheck=1
462 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
463
464 [updates]
465 name=Fedora $release - $arch - Updates
466 baseurl=http://mirror.onelab.eu/fedora/updates/$release/$arch/
467 enabled=1
468 metadata_expire=7d
469 gpgcheck=1
470 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
471 EOF
472     
473     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
474     # just mention 'none' as the repo url
475     if [ -n "$REPO_URL" ] ; then
476         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
477             echo "WARNING : cannot create myplc repo"
478         else
479             # exclude kernel from fedora repos 
480             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
481             for repo in $rootfs_path/etc/yum.repos.d/* ; do
482                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
483             done
484             # the build repo is not signed at this stage
485             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
486 [myplc]
487 name= MyPLC
488 baseurl=$REPO_URL
489 enabled=1
490 gpgcheck=0
491 EOF
492         fi
493     fi
494 }    
495
496 # return yum or debootstrap
497 function package_method () {
498     fcdistro=$1; shift
499     case $fcdistro in
500         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
501         squeeze|wheezy|oneiric|precise|quantal|raring|saucy) echo debootstrap ;;
502         *) echo Unknown distro $fcdistro ;;
503     esac 
504 }
505
506 # return arch from debian distro and personality
507 function canonical_arch () {
508     personality=$1; shift
509     fcdistro=$1; shift
510     case $(package_method $fcdistro) in
511         yum)
512             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
513         debootstrap)
514             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
515         *)
516             echo Unknown-arch-3 ;;
517     esac
518 }
519
520 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
521 function almost_empty () { 
522     dir="$1"; shift ; 
523     # non existing is fine
524     [ ! -d $dir ] && return 0; 
525     # need to have at most one file
526     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
527 }
528
529 function setup_lxc() {
530
531     set -x
532     set -e
533     #trap failure ERR INT
534
535     lxc=$1; shift
536     fcdistro=$1; shift
537     pldistro=$1; shift
538     personality=$1; shift
539
540     # create lxc container 
541     
542     pkg_method=$(package_method $fcdistro)
543     case $pkg_method in
544         yum)
545             install_fedora || { echo "failed to install fedora"; exit 1 ; }
546             configure_fedora || { echo "failed to configure fedora for a container"; exit 1 ; }
547             if [ "$(echo $fcdistro | cut -d"f" -f2)" -le "14" ]; then
548                 configure_fedora_init
549             else
550                 configure_fedora_systemd
551             fi
552             ;;
553         debootstrap)
554             echo "$COMMAND: no support for debootstrap-based systems - yet"
555             exit 1
556             ;;
557         *)
558             echo "$COMMAND:: unknown package_method - exiting"
559             exit 1
560             ;;
561     esac
562
563     # Enable cgroup
564     mkdir $rootfs_path/cgroup
565     
566     # set up resolv.conf
567     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
568     # and /etc/hosts for at least localhost
569     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
570     
571     # grant ssh access from host to guest
572     mkdir $rootfs_path/root/.ssh
573     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
574     
575     # copy libvirt xml template
576     veth_pair="i$(echo $HOSTNAME | cut -d. -f1)" 
577     tmpl_name="$lxc.xml"
578     cat > $config_path/$tmpl_name<<EOF
579 <domain type='lxc'>
580   <name>$lxc</name>
581   <memory>524288</memory>
582   <os>
583     <type arch='$arch2'>exe</type>
584     <init>/sbin/init</init>
585   </os>
586   <features>
587     <acpi/>
588   </features>
589   <vcpu>1</vcpu>
590   <clock offset='utc'/>
591   <on_poweroff>destroy</on_poweroff>
592   <on_reboot>restart</on_reboot>
593   <on_crash>destroy</on_crash>
594   <devices>
595     <emulator>/usr/libexec/libvirt_lxc</emulator>
596     <filesystem type='mount'>
597       <source dir='$rootfs_path'/>
598       <target dir='/'/>
599     </filesystem>
600     <interface type="bridge">
601       <source bridge="$INTERFACE_BRIDGE"/>
602       <target dev='$veth_pair'/>
603     </interface>
604     <console type='pty' />
605   </devices>
606   <network>
607     <name>host-bridge</name>
608     <forward mode="bridge"/>
609     <bridge name="$INTERFACE_BRIDGE"/>
610   </network>
611 </domain>
612 EOF
613
614     # define lxc container for libvirt
615     virsh -c lxc:// define $config_path/$tmpl_name
616
617     # rpm --rebuilddb
618     chroot $rootfs_path /bin/rpm --rebuilddb
619
620     configure_yum_in_lxc $lxc $fcdistro $pldistro
621
622     return 0
623 }
624
625 function devel_or_vtest_tools () {
626
627     set -x 
628     set -e 
629     trap failure ERR INT
630
631     lxc=$1; shift
632     fcdistro=$1; shift
633     pldistro=$1; shift
634     personality=$1; shift
635
636     pkg_method=$(package_method $fcdistro)
637
638     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $PREINSTALLED)
639
640     ### install individual packages, then groups
641     # get target arch - use uname -i here (we want either x86_64 or i386)
642    
643     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
644     # on debian systems we get arch through the 'arch' command
645     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
646
647     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
648     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
649
650     case "$pkg_method" in
651         yum)
652             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
653             for group_plus in $groups; do
654                 group=$(echo $group_plus | sed -e "s,+++, ,g")
655                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
656             done
657             # store current rpm list in /init-lxc.rpms in case we need to check the contents
658             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
659             ;;
660         debootstrap)
661             chroot $rootfs_path /usr/bin/apt-get update
662             for package in $packages ; do 
663                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
664             done
665             ### xxx todo install groups with apt..
666             ;;
667         *)
668             echo "unknown pkg_method $pkg_method"
669             ;;
670     esac
671
672     return 0
673 }
674
675 function post_install () {
676     lxc=$1; shift 
677     personality=$1; shift
678     if [ -n "$BUILD_MODE" ] ; then
679         post_install_build $lxc $personality
680         start_lxc $lxc
681     else
682         post_install_myplc $lxc $personality
683         start_lxc $lxc
684         wait_for_ssh $lxc
685     fi
686     # setup localtime from the host
687     cp /etc/localtime $rootfs_path/etc/localtime
688 }
689
690 function post_install_build () {
691
692     set -x 
693     set -e 
694     trap failure ERR INT
695
696     lxc=$1; shift
697     personality=$1; shift
698
699 ### From myplc-devel-native.spec
700 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
701     cat << EOF | chroot $rootfs_path /bin/bash -x
702     # set up /dev/loop* in lxc
703     for i in \$(seq 0 255) ; do
704         /bin/mknod -m 640 /dev/loop\$i b 7 \$i
705     done
706     
707     # create symlink for /dev/fd
708     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
709
710     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
711     /bin/sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
712     if [ -h "/sbin/new-kernel-pkg" ] ; then
713         filename=\$(/bin/readlink -f /sbin/new-kernel-pkg)
714         if [ "\$filename" == "/sbin/true" ] ; then
715                 /bin/echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
716                 /bin/echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
717                 /bin/echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
718                 exit 1
719         fi
720     fi
721     
722     # customize root's prompt
723     /bin/cat << PROFILE > /root/.profile
724 export PS1="[$lxc] \\w # "
725 PROFILE
726
727     uid=2000
728     gid=2000
729     
730     # add a "build" user to the system
731     builduser=\$(grep "^build:" /etc/passwd | wc -l)
732     if [ \$builduser -eq 0 ] ; then
733         groupadd -o -g \$gid build;
734         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
735     fi
736
737 # Allow build user to build certain RPMs as root
738     if [ -f /etc/sudoers ] ; then
739         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
740         if [ \$buildsudo -eq 0 ] ; then
741             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
742         fi
743         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
744     fi
745 #
746 EOF
747         
748 }
749
750 function post_install_myplc  () {
751     set -x 
752     set -e 
753     trap failure ERR INT
754
755     lxc=$1; shift
756     personality=$1; shift
757
758 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
759     cat << EOF | chroot $rootfs_path /bin/bash -x
760
761     # create /etc/sysconfig/network if missing
762     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
763
764     # create symlink for /dev/fd
765     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
766
767     # turn off regular crond, as plc invokes plc_crond
768     /sbin/chkconfig crond off
769
770     # take care of loginuid in /etc/pam.d 
771     /bin/sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
772
773     # customize root's prompt
774     /bin/cat << PROFILE > /root/.profile
775 export PS1="[$lxc] \\w # "
776 PROFILE
777
778 EOF
779 }
780
781 function start_lxc() {
782
783     set -x
784     set -e
785     #trap failure ERR INT
786
787     lxc=$1; shift
788   
789     virsh -c lxc:// start $lxc
790   
791     return 0
792 }
793
794 function wait_for_ssh () {
795     set -x
796     set -e
797     #trap failure ERR INT
798
799     lxc=$1; shift
800   
801     echo $IP is up, waiting for ssh...
802
803     #wait max 5 min for sshd to start 
804     ssh_up=""
805     stop_time=$(($(date +%s) + 300))
806     current_time=$(date +%s)
807     
808     counter=1
809     while [ "$current_time" -lt "$stop_time" ] ; do
810          echo "$counter-th attempt to reach sshd in container $lxc ..."
811          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
812          sleep 10
813          current_time=$(($current_time + 10))
814          counter=$(($counter+1))
815     done
816
817     # Thierry: this is fatal, let's just exit with a failure here
818     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
819     return 0
820 }
821
822 ####################
823 function failure () {
824     echo "$COMMAND : Bailing out"
825     exit 1
826 }
827
828 function usage () {
829     set +x 
830     echo "Usage: $COMMAND_LBUILD [options] lxc-name"
831     echo "Usage: $COMMAND_LTEST [options] lxc-name"
832     echo "Description:"
833     echo "   This command creates a fresh lxc instance, for building, or running a test myplc"
834     echo "Supported options"
835     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
836     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
837     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
838     echo " -n hostname - the hostname to use in container - required with $COMMAND_LTEST"
839     echo " -r repo-url - used to populate yum.repos.d - required with $COMMAND_LTEST"
840     echo " -P pkgs_file - defines the set of extra pacakges"
841     echo "    by default we use vtest.pkgs or devel.pkgs according to $COMMAND"
842     echo " -v be verbose"
843     exit 1
844 }
845
846 ### parse args and 
847 function main () {
848
849     #set -e
850     #trap failure ERR INT
851
852     if [ "$(id -u)" != "0" ]; then
853           echo "This script should be run as 'root'"
854           exit 1
855     fi
856
857     case "$COMMAND" in
858         $COMMAND_LBUILD)
859             BUILD_MODE=true ;;
860         $COMMAND_LTEST)
861             TEST_MODE=true;;
862         *)
863             usage ;;
864     esac
865
866     echo 'build mode=' $BUILD_MODE 'test mode=' $TEST_MODE
867
868     # the set of preinstalled packages - depends on vbuild or vtest
869     if [ -n "$VBUILD_MODE" ] ; then
870         PREINSTALLED=devel.pkgs
871     else
872         PREINSTALLED=vtest.pkgs
873     fi
874     while getopts "f:d:p:n:r:P:v" opt ; do
875         case $opt in
876             f) fcdistro=$OPTARG;;
877             d) pldistro=$OPTARG;;
878             p) personality=$OPTARG;;
879             n) HOSTNAME=$OPTARG;;
880             r) REPO_URL=$OPTARG;;
881             P) PREINSTALLED=$OPTARG;;
882             v) VERBOSE=true; set -x;;
883             *) usage ;;
884         esac
885     done
886         
887     shift $(($OPTIND - 1))
888
889     # parse fixed arguments
890     [[ -z "$@" ]] && usage
891     lxc=$1 ; shift
892
893     # check we've exhausted the arguments
894     [[ -n "$@" ]] && usage
895
896     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
897     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
898     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
899     
900     if [ -n "$BUILD_MODE" ] ; then
901         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
902     else
903         [[ -z "$HOSTNAME" ]] && usage
904         [[ -z "$REPO_URL" ]] && echo "WARNING -- setting up a yum repo is recommended" 
905     fi
906
907     ##########
908     release=$(echo $fcdistro | cut -df -f2)
909
910     if [ "$personality" == "linux32" ]; then
911         arch=i386
912         arch2=i686
913     elif [ "$personality" == "linux64" ]; then
914         arch=x86_64
915         arch2=x86_64
916     else
917         echo "Unknown personality: $personality"
918     fi
919
920     # need lxc installed before we can run lxc-ls
921     # need bridge installed
922     create_bridge_if_needed
923
924     if [ -n "$BUILD_MODE" ] ; then
925
926         # Bridge IP affectation
927         byte=$(random_private_byte)
928         IP=${PRIVATE_PREFIX}$byte
929         NETMASK=$(masklen_to_netmask $PRIVATE_MASKLEN)
930         GATEWAY=$PRIVATE_GATEWAY
931         
932         lxc_network_type=veth
933         lxc_network_link=virbr0
934         veth_pair="veth$byte"
935         echo "the IP address of container $lxc is $IP "
936     else
937         [[ -z "HOSTNAME" ]] && usage
938        
939         IP=$(gethostbyname $HOSTNAME)
940         # use same NETMASK as bridge interface br0
941         MASKLEN=$(ip addr show $INTERFACE_BRIDGE | grep -v inet6 | grep inet | awk '{print $2;}' | cut -d/ -f2)
942         
943         NETMASK=$(masklen_to_netmask $MASKLEN)
944         GATEWAY=$(ip route show | grep default | awk '{print $3}')
945         lxc_network_type=veth
946         lxc_network_link=$INTERFACE_BRIDGE
947         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
948
949     fi
950
951     path=/vservers
952     [ ! -d $path ] && mkdir $path
953     rootfs_path=$path/$lxc/rootfs
954     config_path=$path/$lxc
955     cache_base=/var/cache/lxc/fedora/$arch
956     cache=$cache_base/$release
957     root_password=root
958     
959     # check whether the rootfs directory is created to know if the container exists
960     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
961     [ -d $rootfs_path ] && \
962         { echo "container $lxc already exists in filesystem - exiting" ; exit 1 ; }
963     virsh --connect lxc:// domuuid $lxc >& /dev/null && \
964         { echo "container $lxc already exists in libvirt - exiting" ; exit 1 ; }
965
966     setup_lxc $lxc $fcdistro $pldistro $personality 
967
968     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
969
970     post_install $lxc $personality
971     
972     echo $COMMAND Done
973 }
974
975 main "$@"