trying out ipfw's from the new sourceforge repo on all fedora's
[build.git] / vbuild-init-lxc.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=f16
15 DEFAULT_PLDISTRO=planetlab
16 DEFAULT_PERSONALITY=linux64
17 DEFAULT_IFNAME=eth0
18
19 COMMAND_VBUILD="vbuild-init-lxc.sh"
20 COMMAND_MYPLC="vtest-init-lxc.sh"
21
22 libvirt_version="1.0.3"
23 function bridge_init () {
24
25     # turn on verbosity
26     set -x
27
28     # constant
29     INTERFACE_BRIDGE=br0
30
31     # Default Value for INTERFACE_LAN
32     INTERFACE_LAN=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
33
34
35     echo "========== $COMMAND: entering start - beg"
36     hostname
37     uname -a
38     ifconfig
39     netstat -rn
40     echo "========== $COMMAND: entering start - end"
41
42     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
43     #
44     # another option would be to accept the all forward packages for
45     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
46     sysctl net.bridge.bridge-nf-call-iptables=0
47     sysctl net.bridge.bridge-nf-call-ip6tables=0
48     sysctl net.bridge.bridge-nf-call-arptables=0
49
50     # take extra arg for ifname, if provided
51     [ -n "$1" ] && { INTERFACE_LAN=$1; shift ; }
52
53     #if we have already configured the same host_box no need to do it again
54     /sbin/ifconfig $INTERFACE_BRIDGE &> /dev/null && {
55         echo "Bridge interface $INTERFACE_BRIDGE already set up - $COMMAND start exiting"
56         return 0
57     }
58     /sbin/ifconfig $INTERFACE_LAN &>/dev/null || {
59         echo "Cannot use interface $INTERFACE_LAN - exiting"
60         exit 1
61     }
62
63     
64     #Getting host IP/masklen
65     address=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
66     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $INTERFACE_LAN" ; exit 1 ; }
67
68 broadcast=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
69     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $INTERFACE_LAN"
70
71     gateway=$(netstat -rn | grep '^0.0.0.0' | awk '{print $2;}')
72     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
73
74     # creating the bridge
75     echo "Creating bridge INTERFACE_BRIDGE=$INTERFACE_BRIDGE"
76     brctl addbr $INTERFACE_BRIDGE
77     #brctl stp $INTERFACE_BRIDGE yes
78     brctl addif $INTERFACE_BRIDGE $INTERFACE_LAN
79     echo "Activating promiscuous mode INTERFACE_LAN=$INTERFACE_LAN"
80     /sbin/ifconfig $INTERFACE_LAN 0.0.0.0 promisc up
81     sleep 2
82     echo "Setting bridge address=$address broadcast=$broadcast"
83     # static
84     #/sbin/ifconfig $INTERFACE_BRIDGE $address broadcast $broadcast up
85     dhclient $INTERFACE_BRIDGE
86     sleep 1
87
88     #Reconfigure the routing table
89     echo "Configuring gateway=$gateway"
90     route add default gw $gateway
91
92     echo "========== $COMMAND: exiting start - beg"
93     ifconfig
94     netstat -rn
95     echo "========== $COMMAND: exiting start - end"
96
97
98 return 0
99
100 }
101
102
103 function failure () {
104     echo "$COMMAND : Bailing out"
105     exit 1
106 }
107
108 function cidr_notation () {
109
110 netmask=$1; shift
111 cidr=0
112 for i in $(seq 1 4) ; do
113     part=$(echo $netmask | cut -d. -f $i)
114     case $part in
115         "255") cidr=$((cidr + 8));;
116         "254") cidr=$((cidr + 7));;
117         "252") cidr=$((cidr + 6));;
118         "248") cidr=$((cidr + 5));;
119         "240") cidr=$((cidr + 4));;
120         "224") cidr=$((cidr + 3));;
121         "192") cidr=$((cidr + 2));;
122         "128") cidr=$((cidr + 1));;
123         "0") cidr=$((cidr + 0));;
124      esac
125 done
126 echo $cidr
127
128 }
129
130 function check_yum_installed () {
131     package=$1; shift
132     rpm -q $package >& /dev/null || yum -y install $package
133 }
134
135 function check_yumgroup_installed () {
136     group="$1"; shift
137     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
138 }
139
140 function prepare_host() {
141    
142     host_fcdistro="$(cat /etc/fedora-release | cut -d' ' -f3)"    
143     ## check if libvirt 1.0.2-1 is installed
144     virsh -v | grep -e "1.0.3" || { echo "Libvirt 1.0.3 needs to be installed!!!" ; exit 1 ; }
145
146 #    host_fcdistro="$(cat /etc/fedora-release | cut -d' ' -f3)"
147 #    if [ ! -f /etc/yum.repos.d/libvirt.repo ] ; then
148 #       touch /etc/yum.repos.d/libvirt.repo
149 #       cat <<EOF > /etc/yum.repos.d/libvirt.repo
150 #[libvirt]
151 #name=libvirt-1.0.2-1
152 #baseurl=http://build.onelab.eu/lxc/2013.02.25--lxc$host_fcdistro/RPMS/
153 #enabled=1
154 #gpgcheck=0
155 #EOF
156 #
157 #       yum --assumeno update
158 #       check_yumgroup_installed "Development Tools"
159 #       check_yum_installed libcap-devel
160 #       check_yum_installed libvirt
161 #       systemctl start libvirtd
162 #    fi
163
164     #################### bride initialization
165     check_yum_installed bridge-utils
166     #Bridge init
167     isInstalled=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
168     if [ "$isInstalled" != "br0" ] ; then
169         bridge_init
170         sleep 5
171     fi
172
173     return 0
174 }
175
176
177
178 function configure_fedora() {
179
180     # disable selinux in fedora
181     mkdir -p $rootfs_path/selinux
182     echo 0 > $rootfs_path/selinux/enforce
183
184    # configure the network 
185
186     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$IFNAME
187 DEVICE=$IFNAME
188 BOOTPROTO=static
189 ONBOOT=yes
190 HOSTNAME=$HOSTNAME
191 IPADDR=$IP
192 NETMASK=$NETMASK
193 GATEWAY=$GATEWAY
194 NM_CONTROLLED=no
195 TYPE=Ethernet
196 MTU=1500
197 EOF
198
199 # set the hostname
200 if [[ "$fcdistro" == "f18" ]] ; then
201     cat <<EOF > ${rootfs_path}/etc/hostname
202 $HOSTNAME
203 EOF
204 else
205     cat <<EOF > ${rootfs_path}/etc/sysconfig/network
206 NETWORKING=yes
207 HOSTNAME=$HOSTNAME
208 EOF
209     # set minimal hosts
210     cat <<EOF > $rootfs_path/etc/hosts
211 127.0.0.1 localhost $HOSTNAME
212 EOF
213 fi
214
215     dev_path="${rootfs_path}/dev"
216     rm -rf $dev_path
217     mkdir -p $dev_path
218     mknod -m 666 ${dev_path}/null c 1 3
219     mknod -m 666 ${dev_path}/zero c 1 5
220     mknod -m 666 ${dev_path}/random c 1 8
221     mknod -m 666 ${dev_path}/urandom c 1 9
222     mkdir -m 755 ${dev_path}/pts
223     mkdir -m 1777 ${dev_path}/shm
224     mknod -m 666 ${dev_path}/tty c 5 0
225     mknod -m 666 ${dev_path}/tty0 c 4 0
226     mknod -m 666 ${dev_path}/tty1 c 4 1
227     mknod -m 666 ${dev_path}/tty2 c 4 2
228     mknod -m 666 ${dev_path}/tty3 c 4 3
229     mknod -m 666 ${dev_path}/tty4 c 4 4
230     mknod -m 600 ${dev_path}/console c 5 1
231     mknod -m 666 ${dev_path}/full c 1 7
232     mknod -m 600 ${dev_path}/initctl p
233     mknod -m 666 ${dev_path}/ptmx c 5 2
234
235     #echo "setting root passwd to $root_password"
236     #echo "root:$root_password" | chroot $rootfs_path chpasswd
237
238     return 0
239 }
240
241
242 function configure_fedora_init() {
243
244     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
245     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
246     chroot ${rootfs_path} /sbin/chkconfig udev-post off
247     chroot ${rootfs_path} /sbin/chkconfig network on
248 }
249
250
251 function configure_fedora_systemd() {
252     unlink ${rootfs_path}/etc/systemd/system/default.target
253     ln -s /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
254     touch ${rootfs_path}/etc/fstab
255     ln -s /dev/null ${rootfs_path}/etc/systemd/system/udev.service
256 # Thierry - Feb 2013
257 # this was intended for f16 initially, in order to enable getty that otherwise would not start
258 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
259 # VM's that refuse to lxc-stop and VM's that run crazy getty's
260 # so, turning getty off for now instead
261 #   #dependency on a device unit fails it specially that we disabled udev
262 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
263     ln -s /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
264     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
265 # can't seem to handle this one with systemctl
266     chroot ${rootfs_path} /sbin/chkconfig network on
267 }
268
269 function download_fedora() {
270 set -x
271     # check the mini fedora was not already downloaded
272     INSTALL_ROOT=$cache/partial
273     echo $INSTALL_ROOT
274     mkdir -p $INSTALL_ROOT
275     if [ $? -ne 0 ]; then
276         echo "Failed to create '$INSTALL_ROOT' directory"
277         return 1
278     fi
279
280     # download a mini fedora into a cache
281     echo "Downloading fedora minimal ..."
282     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
283     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
284   
285     
286     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
287     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
288     # with fedora18 the rpms are scattered by first name
289     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
290     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
291     found=""
292     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
293         if curl -f $attempt -o $RELEASE_TARGET ; then
294             echo "Retrieved $attempt"
295             found=true
296             break
297         else
298             echo "Failed attempt $attempt"
299         fi
300     done
301     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
302     
303     mkdir -p $INSTALL_ROOT/var/lib/rpm
304     rpm --root $INSTALL_ROOT  --initdb
305     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
306     echo "$YUM install $PKG_LIST"
307     $YUM install $PKG_LIST
308
309     if [ $? -ne 0 ]; then
310         echo "Failed to download the rootfs, aborting."
311         return 1
312     fi
313
314     mv "$INSTALL_ROOT" "$cache/rootfs"
315     echo "Download complete."
316
317     return 0
318 }
319
320
321 function copy_fedora() {
322 set -x
323     # make a local copy of the minifedora
324     echo -n "Copying rootfs to $rootfs_path ..."
325     mkdir -p $rootfs_path
326     rsync -a $cache/rootfs/ $rootfs_path/
327     return 0
328 }
329
330
331 function update_fedora() {
332 set -x
333     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
334     $YUM update
335 }
336
337
338 function install_fedora() {
339     set -x
340
341     mkdir -p /var/lock/subsys/
342     (
343         flock -n -x 200
344         if [ $? -ne 0 ]; then
345             echo "Cache repository is busy."
346             return 1
347         fi
348
349         echo "Checking cache download in $cache/rootfs ... "
350         if [ ! -e "$cache/rootfs" ]; then
351             download_fedora
352             if [ $? -ne 0 ]; then
353                 echo "Failed to download 'fedora base'"
354                 return 1
355             fi
356         else
357             echo "Cache found. Updating..."
358             update_fedora
359             if [ $? -ne 0 ]; then
360                 echo "Failed to update 'fedora base', continuing with last known good cache"
361             else
362                 echo "Update finished"
363             fi
364         fi
365
366         echo "Copy $cache/rootfs to $rootfs_path ... "
367         copy_fedora
368         if [ $? -ne 0 ]; then
369             echo "Failed to copy rootfs"
370             return 1
371         fi
372
373         return 0
374
375         ) 200>/var/lock/subsys/lxc
376
377     return $?
378 }
379
380
381 function copy_configuration() {
382
383     mkdir -p $config_path
384     cat <<EOF >> $config_path/config
385 lxc.utsname = $lxc
386 lxc.arch = $arch2
387 lxc.tty = 4
388 lxc.pts = 1024
389 lxc.rootfs = $rootfs_path
390 lxc.mount  = $config_path/fstab
391 #networking
392 lxc.network.type = $lxc_network_type
393 lxc.network.flags = up
394 lxc.network.link = $lxc_network_link
395 lxc.network.name = $IFNAME
396 lxc.network.mtu = 1500
397 lxc.network.ipv4 = $IP/$CIDR
398 lxc.network.veth.pair = $veth_pair
399 #cgroups
400 #lxc.cgroup.devices.deny = a
401 # /dev/null and zero
402 lxc.cgroup.devices.allow = c 1:3 rwm
403 lxc.cgroup.devices.allow = c 1:5 rwm
404 # consoles
405 lxc.cgroup.devices.allow = c 5:1 rwm
406 lxc.cgroup.devices.allow = c 5:0 rwm
407 lxc.cgroup.devices.allow = c 4:0 rwm
408 lxc.cgroup.devices.allow = c 4:1 rwm
409 # /dev/{,u}random
410 lxc.cgroup.devices.allow = c 1:9 rwm
411 lxc.cgroup.devices.allow = c 1:8 rwm
412 lxc.cgroup.devices.allow = c 136:* rwm
413 lxc.cgroup.devices.allow = c 5:2 rwm
414 # rtc
415 lxc.cgroup.devices.allow = c 254:0 rwm
416 lxc.cgroup.devices.allow = b 255:0 rwm
417 EOF
418
419
420
421     cat <<EOF > $config_path/fstab
422 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
423 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
424 sysfs           $rootfs_path/sys          sysfs defaults  0 0
425 EOF
426     if [ $? -ne 0 ]; then
427         echo "Failed to add configuration"
428         return 1
429     fi
430
431     return 0
432 }
433
434
435
436
437 # overwrite lxc's internal yum config
438 function configure_yum_in_lxc () {
439     set -x 
440     set -e 
441     trap failure ERR INT
442
443     lxc=$1; shift
444     fcdistro=$1; shift
445     pldistro=$1; shift
446
447     echo "Initializing yum.repos.d in $lxc"
448     rm -f $rootfs_path/etc/yum.repos.d/*
449
450     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
451 [fedora]
452 name=Fedora $release - \$basearch
453 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
454 enabled=1
455 metadata_expire=7d
456 gpgcheck=1
457 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
458
459 [updates]
460 name=Fedora $release - \$basearch - Updates
461 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
462 enabled=1
463 metadata_expire=7d
464 gpgcheck=1
465 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
466 EOF
467     
468     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
469     # just mention 'none' as the repo url
470     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
471         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
472             echo "WARNING : cannot create myplc repo"
473         else
474             # exclude kernel from fedora repos 
475             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
476             for repo in $rootfs_path/etc/yum.repos.d/* ; do
477                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
478             done
479             # the build repo is not signed at this stage
480             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
481 [myplc]
482 name= MyPLC
483 baseurl=$REPO_URL
484 enabled=1
485 gpgcheck=0
486 EOF
487         fi
488     fi
489 }    
490
491 # return yum or debootstrap
492 function package_method () {
493     fcdistro=$1; shift
494     case $fcdistro in
495         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
496         lenny|etch) echo debootstrap ;;
497         *) echo Unknown distro $fcdistro ;;
498     esac 
499 }
500
501 # return arch from debian distro and personality
502 function canonical_arch () {
503     personality=$1; shift
504     fcdistro=$1; shift
505     case $(package_method $fcdistro) in
506         yum)
507             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
508         debootstrap)
509             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
510         *)
511             echo Unknown-arch-3 ;;
512     esac
513 }
514
515 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
516 function almost_empty () { 
517     dir="$1"; shift ; 
518     # non existing is fine
519     [ ! -d $dir ] && return 0; 
520     # need to have at most one file
521     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
522 }
523
524 function setup_lxc() {
525
526     set -x
527     set -e
528     #trap failure ERR INT
529
530     lxc=$1; shift
531     fcdistro=$1; shift
532     pldistro=$1; shift
533     personality=$1; shift
534
535     # create lxc container 
536     copy_configuration
537     if [ $? -ne 0 ]; then
538         echo "failed write configuration file"
539         exit 1
540     fi
541
542     install_fedora
543     if [ $? -ne 0 ]; then
544         echo "failed to install fedora"
545         exit 1
546     fi
547
548     configure_fedora
549     if [ $? -ne 0 ]; then
550         echo "failed to configure fedora for a container"
551         exit 1
552     fi
553
554     type /bin/systemd >/dev/null 2>&1
555     if [ $? -ne 0 ]; then
556         configure_fedora_init
557     else
558         configure_fedora_systemd
559     fi
560
561     # Enable cgroup
562     mkdir $rootfs_path/cgroup
563     
564     # set up resolv.conf
565     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
566     # and /etc/hosts for at least localhost
567     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
568     
569     # ssh access to lxc
570     mkdir $rootfs_path/root/.ssh
571     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
572     
573     # copy libvirt xml template
574     veth_pair="i$(echo $HOSTNAME | cut -d. -f1)" 
575     tmpl_name="$lxc.xml"
576     cat > $config_path/$tmpl_name<<EOF
577 <domain type='lxc'>
578   <name>$lxc</name>
579   <memory>524288</memory>
580   <os>
581     <type>exe</type>
582     <init>/sbin/init</init>
583   </os>
584   <features>
585     <acpi/>
586   </features>
587   <vcpu>1</vcpu>
588   <clock offset='utc'/>
589   <on_poweroff>destroy</on_poweroff>
590   <on_reboot>restart</on_reboot>
591   <on_crash>destroy</on_crash>
592   <devices>
593     <emulator>/usr/libexec/libvirt_lxc</emulator>
594     <filesystem type='mount'>
595       <source dir='$rootfs_path'/>
596       <target dir='/'/>
597     </filesystem>
598     <interface type="bridge">
599       <source bridge="br0"/>
600       <target dev='$veth_pair'/>
601     </interface>
602     <console type='pty' />
603   </devices>
604   <network>
605     <name>host-bridge</name>
606     <forward mode="bridge"/>
607     <bridge name="br0"/>
608   </network>
609 </domain>
610 EOF
611    
612     # define lxc container for libvirt
613     virsh -c lxc:// define $config_path/$tmpl_name
614
615     # rpm --rebuilddb
616     chroot $rootfs_path /bin/rpm --rebuilddb
617
618     configure_yum_in_lxc $lxc $fcdistro $pldistro
619
620     return 0
621 }
622
623 function devel_or_vtest_tools () {
624
625     set -x 
626     set -e 
627     trap failure ERR INT
628
629     lxc=$1; shift
630     fcdistro=$1; shift
631     pldistro=$1; shift
632     personality=$1; shift
633
634     pkg_method=$(package_method $fcdistro)
635
636     # check for .pkgs file based on pldistro
637     if [ -n "$VBUILD_MODE" ] ; then
638         pkgsname=devel.pkgs
639     else
640         pkgsname=vtest.pkgs
641     fi
642     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
643
644     ### install individual packages, then groups
645     # get target arch - use uname -i here (we want either x86_64 or i386)
646    
647     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
648     # on debian systems we get arch through the 'arch' command
649     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
650
651     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
652     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
653
654     case "$pkg_method" in
655         yum)
656             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
657             for group_plus in $groups; do
658                 group=$(echo $group_plus | sed -e "s,+++, ,g")
659                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
660             done
661             # store current rpm list in /init-lxc.rpms in case we need to check the contents
662             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
663             ;;
664         debootstrap)
665             chroot $rootfs_path /usr/bin/apt-get update
666             for package in $packages ; do 
667                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
668             done
669             ### xxx todo install groups with apt..
670             ;;
671         *)
672             echo "unknown pkg_method $pkg_method"
673             ;;
674     esac
675
676     return 0
677 }
678
679 function post_install () {
680     if [ -n "$VBUILD_MODE" ] ; then
681         post_install_vbuild "$@" 
682     else
683         post_install_myplc "$@"
684     fi
685     # setup localtime from the host
686     lxc=$1; shift 
687     cp /etc/localtime $rootfs_path/etc/localtime
688 }
689
690 function post_install_vbuild () {
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     echo $IP is up, waiting for ssh...
792
793     #wait max 5 min for sshd to start 
794     ssh_up=""
795     stop_time=$(($(date +%s) + 300))
796     current_time=$(date +%s)
797     
798     counter=1
799     while [ "$current_time" -lt "$stop_time" ] ; do
800          echo "$counter-th attempt to reach sshd in container $lxc ..."
801          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
802          sleep 10
803          current_time=$(($current_time + 10))
804          counter=$(($counter+1))
805     done
806
807     # Thierry: this is fatal, let's just exit with a failure here
808     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
809
810     return 0
811 }
812
813 function usage () {
814     set +x 
815     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
816     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
817     echo "Description:"
818     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
819     echo "Supported options"
820     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
821     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
822     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
823     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
824     echo "-- lxc-options"
825     echo "  --netdev : interface to be defined inside lxc"
826     echo "  --interface : IP to be defined for the lxc"
827     echo "  --hostname : Hostname to be defined for the lxc"
828     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
829     echo "   myplc.repo does not get created"
830     exit 1
831 }
832
833 ### parse args and 
834 function main () {
835
836     #set -e
837     #trap failure ERR INT
838
839     case "$COMMAND" in
840         $COMMAND_VBUILD)
841             VBUILD_MODE=true ;;
842         $COMMAND_MYPLC)
843             MYPLC_MODE=true;;
844         *)
845             usage ;;
846     esac
847
848     VERBOSE=
849     RESISTANT=""
850     IFNAME=""
851     LXC_OPTIONS=""
852     while getopts "f:d:p:i:" opt ; do
853         case $opt in
854             f) fcdistro=$OPTARG;;
855             d) pldistro=$OPTARG;;
856             p) personality=$OPTARG;;
857             i) IFNAME=$OPTARG;;
858             *) usage ;;
859         esac
860     done
861         
862     shift $(($OPTIND - 1))
863
864     # parse fixed arguments
865     [[ -z "$@" ]] && usage
866     lxc=$1 ; shift
867     if [ -n "$MYPLC_MODE" ] ; then
868         [[ -z "$@" ]] && usage
869         REPO_URL=$1 ; shift
870     fi
871
872     # parse vserver options
873     if [[ -n "$@" ]] ; then
874         if [ "$1" == "--" ] ; then
875             shift
876             LXC_OPTIONS="$@"
877         else
878             usage
879         fi
880     fi
881
882     eval set -- "$LXC_OPTIONS"
883
884     while true
885      do
886         case "$1" in
887              --netdev)      IFNAME=$2; shift 2;;
888              --interface)   IP=$2; shift 2;;
889              --hostname)    HOSTNAME=$2; shift 2;;
890              *)             break ;;
891         esac
892       done
893
894    
895     if [ -n "$VBUILD_MODE" ] ; then
896         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
897         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
898     fi
899
900     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
901     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
902     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
903     
904     release=$(echo $fcdistro | cut -df -f2)
905
906     if [ "$personality" == "linux32" ]; then
907         arch=i386
908         arch2=x86
909     elif [ "$personality" == "linux64" ]; then
910         arch=x86_64
911         arch2=x86_64
912     else
913         echo "Unknown personality: $personality"
914     fi
915
916     # need lxc installed before we can run lxc-ls
917     # need bridge installed
918     prepare_host    
919
920     if [ -n "$VBUILD_MODE" ] ; then
921
922         # Bridge IP affectation
923         x=$(echo $personality | cut -dx -f2)
924         y=$(echo $fcdistro | cut -df -f2)
925         z=$(($x + $y))
926
927         IP="192.168.122.$z"
928         NETMASK="255.255.255.0"
929         GATEWAY="192.168.122.1"
930         
931         lxc_network_type=veth
932         lxc_network_link=virbr0
933         veth_pair="veth$z"
934         echo "the IP address of container $lxc is $IP "
935     else
936         [[ -z "$REPO_URL" ]] && usage
937         [[ -z "$IP" ]] && usage
938        
939         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
940         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
941         [[ -z "$HOSTNAME" ]] && usage
942         lxc_network_type=veth
943         lxc_network_link=br0
944         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
945     fi
946
947     CIDR=$(cidr_notation $NETMASK)
948     
949
950     if [ "$(id -u)" != "0" ]; then
951           echo "This script should be run as 'root'"
952           exit 1
953     fi
954
955     path=/var/lib/lxc
956     rootfs_path=$path/$lxc/rootfs
957     config_path=$path/$lxc
958     cache_base=/var/cache/lxc/fedora/$arch
959     cache=$cache_base/$release
960     root_password=root
961     
962     # check whether the rootfs directory is created to know if the container exists
963     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
964     [ -d $rootfs_path ] && { echo "container $lxc already exists - 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     start_lxc $lxc
973
974     echo $COMMAND Done
975 }
976
977 main "$@"