back to libvirt 1.0.3
[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_version is installed
144     virsh -v | grep -e $libvirt_version || { echo "$libvirt_version needs to be installed!!!" ; exit 1 ; }
145 #    host_fcdistro="$(cat /etc/fedora-release | cut -d' ' -f3)"
146 #    if [ ! -f /etc/yum.repos.d/libvirt.repo ] ; then
147 #       touch /etc/yum.repos.d/libvirt.repo
148 #       cat <<EOF > /etc/yum.repos.d/libvirt.repo
149 #[libvirt]
150 #name=libvirt-1.0.2-1
151 #baseurl=http://build.onelab.eu/lxc/2013.02.25--lxc$host_fcdistro/RPMS/
152 #enabled=1
153 #gpgcheck=0
154 #EOF
155 #
156 #       yum --assumeno update
157 #       check_yumgroup_installed "Development Tools"
158 #       check_yum_installed libcap-devel
159 #       check_yum_installed libvirt
160 #       systemctl start libvirtd
161 #    fi
162
163     #################### bride initialization
164     check_yum_installed bridge-utils
165     #Bridge init
166     isInstalled=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
167     if [ "$isInstalled" != "br0" ] ; then
168         bridge_init
169         sleep 5
170     fi
171
172     return 0
173 }
174
175
176
177 function configure_fedora() {
178
179     # disable selinux in fedora
180     mkdir -p $rootfs_path/selinux
181     echo 0 > $rootfs_path/selinux/enforce
182
183    # configure the network 
184
185     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$IFNAME
186 DEVICE=$IFNAME
187 BOOTPROTO=static
188 ONBOOT=yes
189 HOSTNAME=$HOSTNAME
190 IPADDR=$IP
191 NETMASK=$NETMASK
192 GATEWAY=$GATEWAY
193 NM_CONTROLLED=no
194 TYPE=Ethernet
195 MTU=1500
196 EOF
197
198 # set the hostname
199 if [[ "$fcdistro" == "f18" ]] ; then
200     cat <<EOF > ${rootfs_path}/etc/hostname
201 $HOSTNAME
202 EOF
203 else
204     cat <<EOF > ${rootfs_path}/etc/sysconfig/network
205 NETWORKING=yes
206 HOSTNAME=$HOSTNAME
207 EOF
208     # set minimal hosts
209     cat <<EOF > $rootfs_path/etc/hosts
210 127.0.0.1 localhost $HOSTNAME
211 EOF
212 fi
213
214     dev_path="${rootfs_path}/dev"
215     rm -rf $dev_path
216     mkdir -p $dev_path
217     mknod -m 666 ${dev_path}/null c 1 3
218     mknod -m 666 ${dev_path}/zero c 1 5
219     mknod -m 666 ${dev_path}/random c 1 8
220     mknod -m 666 ${dev_path}/urandom c 1 9
221     mkdir -m 755 ${dev_path}/pts
222     mkdir -m 1777 ${dev_path}/shm
223     mknod -m 666 ${dev_path}/tty c 5 0
224     mknod -m 666 ${dev_path}/tty0 c 4 0
225     mknod -m 666 ${dev_path}/tty1 c 4 1
226     mknod -m 666 ${dev_path}/tty2 c 4 2
227     mknod -m 666 ${dev_path}/tty3 c 4 3
228     mknod -m 666 ${dev_path}/tty4 c 4 4
229     mknod -m 600 ${dev_path}/console c 5 1
230     mknod -m 666 ${dev_path}/full c 1 7
231     mknod -m 600 ${dev_path}/initctl p
232     mknod -m 666 ${dev_path}/ptmx c 5 2
233
234     #echo "setting root passwd to $root_password"
235     #echo "root:$root_password" | chroot $rootfs_path chpasswd
236
237     return 0
238 }
239
240
241 function configure_fedora_init() {
242
243     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
244     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
245     chroot ${rootfs_path} /sbin/chkconfig udev-post off
246     chroot ${rootfs_path} /sbin/chkconfig network on
247 }
248
249
250 function configure_fedora_systemd() {
251     unlink ${rootfs_path}/etc/systemd/system/default.target
252     ln -s /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
253     touch ${rootfs_path}/etc/fstab
254     ln -s /dev/null ${rootfs_path}/etc/systemd/system/udev.service
255 # Thierry - Feb 2013
256 # this was intended for f16 initially, in order to enable getty that otherwise would not start
257 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
258 # VM's that refuse to lxc-stop and VM's that run crazy getty's
259 # so, turning getty off for now instead
260 #   #dependency on a device unit fails it specially that we disabled udev
261 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
262     ln -s /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
263     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
264 # can't seem to handle this one with systemctl
265     chroot ${rootfs_path} /sbin/chkconfig network on
266 }
267
268 function download_fedora() {
269 set -x
270     # check the mini fedora was not already downloaded
271     INSTALL_ROOT=$cache/partial
272     echo $INSTALL_ROOT
273     mkdir -p $INSTALL_ROOT
274     if [ $? -ne 0 ]; then
275         echo "Failed to create '$INSTALL_ROOT' directory"
276         return 1
277     fi
278
279     # download a mini fedora into a cache
280     echo "Downloading fedora minimal ..."
281     YUM="yum --installroot $INSTALL_ROOT -y --nogpgcheck --releasever=$release"
282     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
283   
284     
285     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
286     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
287     # with fedora18 the rpms are scattered by first name
288     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
289     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
290     found=""
291     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
292         if curl -f $attempt -o $RELEASE_TARGET ; then
293             echo "Retrieved $attempt"
294             found=true
295             break
296         else
297             echo "Failed attempt $attempt"
298         fi
299     done
300     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
301     
302     mkdir -p $INSTALL_ROOT/var/lib/rpm
303     rpm --root $INSTALL_ROOT  --initdb
304     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm
305     echo "$YUM install $PKG_LIST"
306     $YUM install $PKG_LIST
307
308     if [ $? -ne 0 ]; then
309         echo "Failed to download the rootfs, aborting."
310         return 1
311     fi
312
313     mv "$INSTALL_ROOT" "$cache/rootfs"
314     echo "Download complete."
315
316     return 0
317 }
318
319
320 function copy_fedora() {
321 set -x
322     # make a local copy of the minifedora
323     echo -n "Copying rootfs to $rootfs_path ..."
324     mkdir -p $rootfs_path
325     rsync -a $cache/rootfs/ $rootfs_path/
326     return 0
327 }
328
329
330 function update_fedora() {
331 set -x
332     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
333     $YUM update
334 }
335
336
337 function install_fedora() {
338     set -x
339
340     mkdir -p /var/lock/subsys/
341     (
342         flock -n -x 200
343         if [ $? -ne 0 ]; then
344             echo "Cache repository is busy."
345             return 1
346         fi
347
348         echo "Checking cache download in $cache/rootfs ... "
349         if [ ! -e "$cache/rootfs" ]; then
350             download_fedora
351             if [ $? -ne 0 ]; then
352                 echo "Failed to download 'fedora base'"
353                 return 1
354             fi
355         else
356             echo "Cache found. Updating..."
357             update_fedora
358             if [ $? -ne 0 ]; then
359                 echo "Failed to update 'fedora base', continuing with last known good cache"
360             else
361                 echo "Update finished"
362             fi
363         fi
364
365         echo "Copy $cache/rootfs to $rootfs_path ... "
366         copy_fedora
367         if [ $? -ne 0 ]; then
368             echo "Failed to copy rootfs"
369             return 1
370         fi
371
372         return 0
373
374         ) 200>/var/lock/subsys/lxc
375
376     return $?
377 }
378
379
380 function copy_configuration() {
381
382     mkdir -p $config_path
383     cat <<EOF >> $config_path/config
384 lxc.utsname = $lxc
385 lxc.arch = $arch2
386 lxc.tty = 4
387 lxc.pts = 1024
388 lxc.rootfs = $rootfs_path
389 lxc.mount  = $config_path/fstab
390 #networking
391 lxc.network.type = $lxc_network_type
392 lxc.network.flags = up
393 lxc.network.link = $lxc_network_link
394 lxc.network.name = $IFNAME
395 lxc.network.mtu = 1500
396 lxc.network.ipv4 = $IP/$CIDR
397 lxc.network.veth.pair = $veth_pair
398 #cgroups
399 #lxc.cgroup.devices.deny = a
400 # /dev/null and zero
401 lxc.cgroup.devices.allow = c 1:3 rwm
402 lxc.cgroup.devices.allow = c 1:5 rwm
403 # consoles
404 lxc.cgroup.devices.allow = c 5:1 rwm
405 lxc.cgroup.devices.allow = c 5:0 rwm
406 lxc.cgroup.devices.allow = c 4:0 rwm
407 lxc.cgroup.devices.allow = c 4:1 rwm
408 # /dev/{,u}random
409 lxc.cgroup.devices.allow = c 1:9 rwm
410 lxc.cgroup.devices.allow = c 1:8 rwm
411 lxc.cgroup.devices.allow = c 136:* rwm
412 lxc.cgroup.devices.allow = c 5:2 rwm
413 # rtc
414 lxc.cgroup.devices.allow = c 254:0 rwm
415 lxc.cgroup.devices.allow = b 255:0 rwm
416 EOF
417
418
419
420     cat <<EOF > $config_path/fstab
421 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
422 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
423 sysfs           $rootfs_path/sys          sysfs defaults  0 0
424 EOF
425     if [ $? -ne 0 ]; then
426         echo "Failed to add configuration"
427         return 1
428     fi
429
430     return 0
431 }
432
433
434
435
436 # overwrite lxc's internal yum config
437 function configure_yum_in_lxc () {
438     set -x 
439     set -e 
440     trap failure ERR INT
441
442     lxc=$1; shift
443     fcdistro=$1; shift
444     pldistro=$1; shift
445
446     echo "Initializing yum.repos.d in $lxc"
447     rm -f $rootfs_path/etc/yum.repos.d/*
448
449     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
450 [fedora]
451 name=Fedora $release - \$basearch
452 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/\$basearch/os/
453 enabled=1
454 metadata_expire=7d
455 gpgcheck=1
456 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
457
458 [updates]
459 name=Fedora $release - \$basearch - Updates
460 baseurl=http://mirror.onelab.eu/fedora/updates/$release/\$basearch/
461 enabled=1
462 metadata_expire=7d
463 gpgcheck=1
464 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
465 EOF
466     
467     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
468     # just mention 'none' as the repo url
469     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
470         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
471             echo "WARNING : cannot create myplc repo"
472         else
473             # exclude kernel from fedora repos 
474             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
475             for repo in $rootfs_path/etc/yum.repos.d/* ; do
476                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
477             done
478             # the build repo is not signed at this stage
479             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
480 [myplc]
481 name= MyPLC
482 baseurl=$REPO_URL
483 enabled=1
484 gpgcheck=0
485 EOF
486         fi
487     fi
488 }    
489
490 # return yum or debootstrap
491 function package_method () {
492     fcdistro=$1; shift
493     case $fcdistro in
494         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
495         lenny|etch) echo debootstrap ;;
496         *) echo Unknown distro $fcdistro ;;
497     esac 
498 }
499
500 # return arch from debian distro and personality
501 function canonical_arch () {
502     personality=$1; shift
503     fcdistro=$1; shift
504     case $(package_method $fcdistro) in
505         yum)
506             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
507         debootstrap)
508             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
509         *)
510             echo Unknown-arch-3 ;;
511     esac
512 }
513
514 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
515 function almost_empty () { 
516     dir="$1"; shift ; 
517     # non existing is fine
518     [ ! -d $dir ] && return 0; 
519     # need to have at most one file
520     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
521 }
522
523 function setup_lxc() {
524
525     set -x
526     set -e
527     #trap failure ERR INT
528
529     lxc=$1; shift
530     fcdistro=$1; shift
531     pldistro=$1; shift
532     personality=$1; shift
533
534     # create lxc container 
535     copy_configuration
536     if [ $? -ne 0 ]; then
537         echo "failed write configuration file"
538         exit 1
539     fi
540
541     install_fedora
542     if [ $? -ne 0 ]; then
543         echo "failed to install fedora"
544         exit 1
545     fi
546
547     configure_fedora
548     if [ $? -ne 0 ]; then
549         echo "failed to configure fedora for a container"
550         exit 1
551     fi
552
553     type /bin/systemd >/dev/null 2>&1
554     if [ $? -ne 0 ]; then
555         configure_fedora_init
556     else
557         configure_fedora_systemd
558     fi
559
560     # Enable cgroup
561     mkdir $rootfs_path/cgroup
562     
563     # set up resolv.conf
564     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
565     # and /etc/hosts for at least localhost
566     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
567     
568     # ssh access to lxc
569     mkdir $rootfs_path/root/.ssh
570     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
571     
572     # copy libvirt xml template
573     veth_pair="i$(echo $HOSTNAME | cut -d. -f1)" 
574     tmpl_name="$lxc.xml"
575     cat > $config_path/$tmpl_name<<EOF
576 <domain type='lxc'>
577   <name>$lxc</name>
578   <memory>524288</memory>
579   <os>
580     <type>exe</type>
581     <init>/sbin/init</init>
582   </os>
583   <features>
584     <acpi/>
585   </features>
586   <vcpu>1</vcpu>
587   <clock offset='utc'/>
588   <on_poweroff>destroy</on_poweroff>
589   <on_reboot>restart</on_reboot>
590   <on_crash>destroy</on_crash>
591   <devices>
592     <emulator>/usr/libexec/libvirt_lxc</emulator>
593     <filesystem type='mount'>
594       <source dir='$rootfs_path'/>
595       <target dir='/'/>
596     </filesystem>
597     <interface type="bridge">
598       <source bridge="br0"/>
599       <target dev='$veth_pair'/>
600     </interface>
601     <console type='pty' />
602   </devices>
603   <network>
604     <name>host-bridge</name>
605     <forward mode="bridge"/>
606     <bridge name="br0"/>
607   </network>
608 </domain>
609 EOF
610    
611     # define lxc container for libvirt
612     virsh -c lxc:// define $config_path/$tmpl_name
613
614     # rpm --rebuilddb
615     chroot $rootfs_path /bin/rpm --rebuilddb
616
617     configure_yum_in_lxc $lxc $fcdistro $pldistro
618
619     return 0
620 }
621
622 function devel_or_vtest_tools () {
623
624     set -x 
625     set -e 
626     trap failure ERR INT
627
628     lxc=$1; shift
629     fcdistro=$1; shift
630     pldistro=$1; shift
631     personality=$1; shift
632
633     pkg_method=$(package_method $fcdistro)
634
635     # check for .pkgs file based on pldistro
636     if [ -n "$VBUILD_MODE" ] ; then
637         pkgsname=devel.pkgs
638     else
639         pkgsname=vtest.pkgs
640     fi
641     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
642
643     ### install individual packages, then groups
644     # get target arch - use uname -i here (we want either x86_64 or i386)
645    
646     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
647     # on debian systems we get arch through the 'arch' command
648     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
649
650     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
651     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
652
653     case "$pkg_method" in
654         yum)
655             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
656             for group_plus in $groups; do
657                 group=$(echo $group_plus | sed -e "s,+++, ,g")
658                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
659             done
660             # store current rpm list in /init-lxc.rpms in case we need to check the contents
661             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
662             ;;
663         debootstrap)
664             chroot $rootfs_path /usr/bin/apt-get update
665             for package in $packages ; do 
666                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
667             done
668             ### xxx todo install groups with apt..
669             ;;
670         *)
671             echo "unknown pkg_method $pkg_method"
672             ;;
673     esac
674
675     return 0
676 }
677
678 function post_install () {
679     if [ -n "$VBUILD_MODE" ] ; then
680         post_install_vbuild "$@" 
681     else
682         post_install_myplc "$@"
683     fi
684     # setup localtime from the host
685     lxc=$1; shift 
686     cp /etc/localtime $rootfs_path/etc/localtime
687 }
688
689 function post_install_vbuild () {
690
691     set -x 
692     set -e 
693     trap failure ERR INT
694
695     lxc=$1; shift
696     personality=$1; shift
697
698 ### From myplc-devel-native.spec
699 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
700     cat << EOF | chroot $rootfs_path /bin/bash -x
701     # set up /dev/loop* in lxc
702     for i in \$(seq 0 255) ; do
703         /bin/mknod -m 640 /dev/loop\$i b 7 \$i
704     done
705     
706     # create symlink for /dev/fd
707     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
708
709     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
710     /bin/sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
711     if [ -h "/sbin/new-kernel-pkg" ] ; then
712         filename=\$(/bin/readlink -f /sbin/new-kernel-pkg)
713         if [ "\$filename" == "/sbin/true" ] ; then
714                 /bin/echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
715                 /bin/echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
716                 /bin/echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
717                 exit 1
718         fi
719     fi
720     
721     # customize root's prompt
722     /bin/cat << PROFILE > /root/.profile
723 export PS1="[$lxc] \\w # "
724 PROFILE
725
726     uid=2000
727     gid=2000
728     
729     # add a "build" user to the system
730     builduser=\$(grep "^build:" /etc/passwd | wc -l)
731     if [ \$builduser -eq 0 ] ; then
732         groupadd -o -g \$gid build;
733         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
734     fi
735
736 # Allow build user to build certain RPMs as root
737     if [ -f /etc/sudoers ] ; then
738         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
739         if [ \$buildsudo -eq 0 ] ; then
740             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
741         fi
742         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
743     fi
744 #
745 EOF
746
747 }
748
749 function post_install_myplc  () {
750     set -x 
751     set -e 
752     trap failure ERR INT
753
754     lxc=$1; shift
755     personality=$1; shift
756
757 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
758     cat << EOF | chroot $rootfs_path /bin/bash -x
759
760     # create /etc/sysconfig/network if missing
761     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
762
763     # create symlink for /dev/fd
764     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
765
766     # turn off regular crond, as plc invokes plc_crond
767     /sbin/chkconfig crond off
768
769     # take care of loginuid in /etc/pam.d 
770     /bin/sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
771
772     # customize root's prompt
773     /bin/cat << PROFILE > /root/.profile
774 export PS1="[$lxc] \\w # "
775 PROFILE
776
777 EOF
778 }
779
780 function start_lxc() {
781
782     set -x
783     set -e
784     #trap failure ERR INT
785
786     lxc=$1; shift
787   
788     virsh -c lxc:// start $lxc
789   
790     echo $IP is up, waiting for ssh...
791
792     #wait max 5 min for sshd to start 
793     ssh_up=""
794     stop_time=$(($(date +%s) + 300))
795     current_time=$(date +%s)
796     
797     counter=1
798     while [ "$current_time" -lt "$stop_time" ] ; do
799          echo "$counter-th attempt to reach sshd in container $lxc ..."
800          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
801          sleep 10
802          current_time=$(($current_time + 10))
803          counter=$(($counter+1))
804     done
805
806     # Thierry: this is fatal, let's just exit with a failure here
807     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
808
809     return 0
810 }
811
812 function usage () {
813     set +x 
814     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
815     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
816     echo "Description:"
817     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
818     echo "Supported options"
819     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
820     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
821     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
822     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
823     echo "-- lxc-options"
824     echo "  --netdev : interface to be defined inside lxc"
825     echo "  --interface : IP to be defined for the lxc"
826     echo "  --hostname : Hostname to be defined for the lxc"
827     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
828     echo "   myplc.repo does not get created"
829     exit 1
830 }
831
832 ### parse args and 
833 function main () {
834
835     #set -e
836     #trap failure ERR INT
837
838     case "$COMMAND" in
839         $COMMAND_VBUILD)
840             VBUILD_MODE=true ;;
841         $COMMAND_MYPLC)
842             MYPLC_MODE=true;;
843         *)
844             usage ;;
845     esac
846
847     VERBOSE=
848     RESISTANT=""
849     IFNAME=""
850     LXC_OPTIONS=""
851     while getopts "f:d:p:i:" opt ; do
852         case $opt in
853             f) fcdistro=$OPTARG;;
854             d) pldistro=$OPTARG;;
855             p) personality=$OPTARG;;
856             i) IFNAME=$OPTARG;;
857             *) usage ;;
858         esac
859     done
860         
861     shift $(($OPTIND - 1))
862
863     # parse fixed arguments
864     [[ -z "$@" ]] && usage
865     lxc=$1 ; shift
866     if [ -n "$MYPLC_MODE" ] ; then
867         [[ -z "$@" ]] && usage
868         REPO_URL=$1 ; shift
869     fi
870
871     # parse vserver options
872     if [[ -n "$@" ]] ; then
873         if [ "$1" == "--" ] ; then
874             shift
875             LXC_OPTIONS="$@"
876         else
877             usage
878         fi
879     fi
880
881     eval set -- "$LXC_OPTIONS"
882
883     while true
884      do
885         case "$1" in
886              --netdev)      IFNAME=$2; shift 2;;
887              --interface)   IP=$2; shift 2;;
888              --hostname)    HOSTNAME=$2; shift 2;;
889              *)             break ;;
890         esac
891       done
892
893    
894     if [ -n "$VBUILD_MODE" ] ; then
895         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
896         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
897     fi
898
899     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
900     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
901     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
902     
903     release=$(echo $fcdistro | cut -df -f2)
904
905     if [ "$personality" == "linux32" ]; then
906         arch=i386
907         arch2=x86
908     elif [ "$personality" == "linux64" ]; then
909         arch=x86_64
910         arch2=x86_64
911     else
912         echo "Unknown personality: $personality"
913     fi
914
915     # need lxc installed before we can run lxc-ls
916     # need bridge installed
917     prepare_host    
918
919     if [ -n "$VBUILD_MODE" ] ; then
920
921         # Bridge IP affectation
922         x=$(echo $personality | cut -dx -f2)
923         y=$(echo $fcdistro | cut -df -f2)
924         z=$(($x + $y))
925
926         IP="192.168.122.$z"
927         NETMASK="255.255.255.0"
928         GATEWAY="192.168.122.1"
929         
930         lxc_network_type=veth
931         lxc_network_link=virbr0
932         veth_pair="veth$z"
933         echo "the IP address of container $lxc is $IP "
934     else
935         [[ -z "$REPO_URL" ]] && usage
936         [[ -z "$IP" ]] && usage
937        
938         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
939         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
940         [[ -z "$HOSTNAME" ]] && usage
941         lxc_network_type=veth
942         lxc_network_link=br0
943         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
944     fi
945
946     CIDR=$(cidr_notation $NETMASK)
947     
948
949     if [ "$(id -u)" != "0" ]; then
950           echo "This script should be run as 'root'"
951           exit 1
952     fi
953
954     path=/vservers
955     [ ! -d $path ] && mkdir $path
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 "$@"