Uses Libvirt instead of lxc-tools
[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.2"
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     rpm -qa | grep -e "libvirt*.*1.0.2-1" || { echo "Libvirt 1.0.2-1 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 <<<<<<< HEAD
574     # copy libvirt xml template
575     veth_pair="i$(echo $HOSTNAME | cut -d. -f1)" 
576     tmpl_name="$lxc.xml"
577     cat > $config_path/$tmpl_name<<EOF
578 <domain type='lxc'>
579   <name>$lxc</name>
580   <memory>524288</memory>
581   <os>
582     <type>exe</type>
583     <init>/sbin/init</init>
584   </os>
585   <features>
586     <acpi/>
587   </features>
588   <vcpu>1</vcpu>
589   <clock offset='utc'/>
590   <on_poweroff>destroy</on_poweroff>
591   <on_reboot>restart</on_reboot>
592   <on_crash>destroy</on_crash>
593   <devices>
594     <emulator>/usr/libexec/libvirt_lxc</emulator>
595     <filesystem type='mount'>
596       <source dir='$rootfs_path'/>
597       <target dir='/'/>
598     </filesystem>
599     <interface type="bridge">
600       <source bridge="br0"/>
601       <target dev='$veth_pair'/>
602     </interface>
603     <console type='pty' />
604   </devices>
605   <network>
606     <name>host-bridge</name>
607     <forward mode="bridge"/>
608     <bridge name="br0"/>
609   </network>
610 </domain>
611 EOF
612 =======
613     # start container
614     lxc-start -d -n $lxc
615
616     echo $IP is up, waiting for ssh...
617
618     # wait max 5 min for sshd to start 
619     ssh_up=""
620     stop_time=$(($(date +%s) + 300))
621     current_time=$(date +%s)
622     counter=1
623     while [ "$current_time" -lt "$stop_time" ] ; do
624          echo "$counter-th attempt to reach sshd in container $lxc ..."
625          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
626          sleep 10
627          current_time=$(($current_time + 10))
628          counter=$(($counter+1))
629     done
630
631     # Thierry: this is fatal, let's just exit with a failure here
632     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; }
633 >>>>>>> afa8207b5ee1a3aa29026bbe427be9b4516436fb
634    
635     # define lxc container for libvirt
636     virsh -c lxc:// define $config_path/$tmpl_name
637
638     # rpm --rebuilddb
639     chroot $rootfs_path /bin/rpm --rebuilddb
640
641     configure_yum_in_lxc $lxc $fcdistro $pldistro
642
643     return 0
644 }
645
646 function devel_or_vtest_tools () {
647
648     set -x 
649     set -e 
650     trap failure ERR INT
651
652     lxc=$1; shift
653     fcdistro=$1; shift
654     pldistro=$1; shift
655     personality=$1; shift
656
657     pkg_method=$(package_method $fcdistro)
658
659     # check for .pkgs file based on pldistro
660     if [ -n "$VBUILD_MODE" ] ; then
661         pkgsname=devel.pkgs
662     else
663         pkgsname=vtest.pkgs
664     fi
665     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
666
667     ### install individual packages, then groups
668     # get target arch - use uname -i here (we want either x86_64 or i386)
669    
670     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
671     # on debian systems we get arch through the 'arch' command
672     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
673
674     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
675     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
676
677     case "$pkg_method" in
678         yum)
679             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
680             for group_plus in $groups; do
681                 group=$(echo $group_plus | sed -e "s,+++, ,g")
682                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
683             done
684             # store current rpm list in /init-lxc.rpms in case we need to check the contents
685             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
686             ;;
687         debootstrap)
688             chroot $rootfs_path /usr/bin/apt-get update
689             for package in $packages ; do 
690                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
691             done
692             ### xxx todo install groups with apt..
693             ;;
694         *)
695             echo "unknown pkg_method $pkg_method"
696             ;;
697     esac
698
699     return 0
700 }
701
702 function post_install () {
703     if [ -n "$VBUILD_MODE" ] ; then
704         post_install_vbuild "$@" 
705     else
706         post_install_myplc "$@"
707     fi
708     # setup localtime from the host
709     lxc=$1; shift 
710     cp /etc/localtime $rootfs_path/etc/localtime
711 }
712
713 function post_install_vbuild () {
714
715     set -x 
716     set -e 
717     trap failure ERR INT
718
719     lxc=$1; shift
720     personality=$1; shift
721
722 ### From myplc-devel-native.spec
723 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
724     cat << EOF | chroot $rootfs_path /bin/bash -x
725     # set up /dev/loop* in lxc
726     for i in \$(seq 0 255) ; do
727         /bin/mknod -m 640 /dev/loop\$i b 7 \$i
728     done
729     
730     # create symlink for /dev/fd
731     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
732
733     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
734     /bin/sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
735     if [ -h "/sbin/new-kernel-pkg" ] ; then
736         filename=\$(/bin/readlink -f /sbin/new-kernel-pkg)
737         if [ "\$filename" == "/sbin/true" ] ; then
738                 /bin/echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
739                 /bin/echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
740                 /bin/echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
741                 exit 1
742         fi
743     fi
744     
745     # customize root's prompt
746     /bin/cat << PROFILE > /root/.profile
747 export PS1="[$lxc] \\w # "
748 PROFILE
749
750     uid=2000
751     gid=2000
752     
753     # add a "build" user to the system
754     builduser=\$(grep "^build:" /etc/passwd | wc -l)
755     if [ \$builduser -eq 0 ] ; then
756         groupadd -o -g \$gid build;
757         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
758     fi
759
760 # Allow build user to build certain RPMs as root
761     if [ -f /etc/sudoers ] ; then
762         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
763         if [ \$buildsudo -eq 0 ] ; then
764             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
765         fi
766         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
767     fi
768 #
769 EOF
770
771 }
772
773 function post_install_myplc  () {
774     set -x 
775     set -e 
776     trap failure ERR INT
777
778     lxc=$1; shift
779     personality=$1; shift
780
781 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
782     cat << EOF | chroot $rootfs_path /bin/bash -x
783
784     # create /etc/sysconfig/network if missing
785     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
786
787     # create symlink for /dev/fd
788     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
789
790     # turn off regular crond, as plc invokes plc_crond
791     /sbin/chkconfig crond off
792
793     # take care of loginuid in /etc/pam.d 
794     /bin/sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
795
796     # customize root's prompt
797     /bin/cat << PROFILE > /root/.profile
798 export PS1="[$lxc] \\w # "
799 PROFILE
800
801 EOF
802 }
803
804 function start_lxc() {
805
806     set -x
807     set -e
808     #trap failure ERR INT
809
810     lxc=$1; shift
811   
812     virsh -c lxc:// start $lxc
813   
814     echo $IP is up, waiting for ssh...
815
816     #wait max 5 min for sshd to start 
817     ssh_up=""
818     stop_time=$(($(date +%s) + 300))
819     current_time=$(date +%s)
820     
821     counter=1
822     while [ "$current_time" -lt "$stop_time" ] ; do
823          echo "$counter-th attempt to reach sshd in container $lxc ..."
824          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
825          sleep 10
826          current_time=$(($current_time + 10))
827          counter=$(($counter+1))
828     done
829
830     # Thierry: this is fatal, let's just exit with a failure here
831     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
832
833     return 0
834 }
835
836 function usage () {
837     set +x 
838     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
839     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
840     echo "Description:"
841     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
842     echo "Supported options"
843     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
844     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
845     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
846     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
847     echo "-- lxc-options"
848     echo "  --netdev : interface to be defined inside lxc"
849     echo "  --interface : IP to be defined for the lxc"
850     echo "  --hostname : Hostname to be defined for the lxc"
851     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
852     echo "   myplc.repo does not get created"
853     exit 1
854 }
855
856 ### parse args and 
857 function main () {
858
859     #set -e
860     #trap failure ERR INT
861
862     case "$COMMAND" in
863         $COMMAND_VBUILD)
864             VBUILD_MODE=true ;;
865         $COMMAND_MYPLC)
866             MYPLC_MODE=true;;
867         *)
868             usage ;;
869     esac
870
871     VERBOSE=
872     RESISTANT=""
873     IFNAME=""
874     LXC_OPTIONS=""
875     while getopts "f:d:p:i:" opt ; do
876         case $opt in
877             f) fcdistro=$OPTARG;;
878             d) pldistro=$OPTARG;;
879             p) personality=$OPTARG;;
880             i) IFNAME=$OPTARG;;
881             *) usage ;;
882         esac
883     done
884         
885     shift $(($OPTIND - 1))
886
887     # parse fixed arguments
888     [[ -z "$@" ]] && usage
889     lxc=$1 ; shift
890     if [ -n "$MYPLC_MODE" ] ; then
891         [[ -z "$@" ]] && usage
892         REPO_URL=$1 ; shift
893     fi
894
895     # parse vserver options
896     if [[ -n "$@" ]] ; then
897         if [ "$1" == "--" ] ; then
898             shift
899             LXC_OPTIONS="$@"
900         else
901             usage
902         fi
903     fi
904
905     eval set -- "$LXC_OPTIONS"
906
907     while true
908      do
909         case "$1" in
910              --netdev)      IFNAME=$2; shift 2;;
911              --interface)   IP=$2; shift 2;;
912              --hostname)    HOSTNAME=$2; shift 2;;
913              *)             break ;;
914         esac
915       done
916
917    
918     if [ -n "$VBUILD_MODE" ] ; then
919         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
920         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
921     fi
922
923     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
924     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
925     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
926     
927     release=$(echo $fcdistro | cut -df -f2)
928
929     if [ "$personality" == "linux32" ]; then
930         arch=i386
931         arch2=x86
932     elif [ "$personality" == "linux64" ]; then
933         arch=x86_64
934         arch2=x86_64
935     else
936         echo "Unknown personality: $personality"
937     fi
938
939     # need lxc installed before we can run lxc-ls
940     # need bridge installed
941     prepare_host    
942
943     if [ -n "$VBUILD_MODE" ] ; then
944
945         # Bridge IP affectation
946         x=$(echo $personality | cut -dx -f2)
947         y=$(echo $fcdistro | cut -df -f2)
948         z=$(($x + $y))
949
950         IP="192.168.122.$z"
951         NETMASK="255.255.255.0"
952         GATEWAY="192.168.122.1"
953         
954         lxc_network_type=veth
955         lxc_network_link=virbr0
956         veth_pair="veth$z"
957         echo "the IP address of container $lxc is $IP "
958     else
959         [[ -z "$REPO_URL" ]] && usage
960         [[ -z "$IP" ]] && usage
961        
962         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
963         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
964         [[ -z "$HOSTNAME" ]] && usage
965         lxc_network_type=veth
966         lxc_network_link=br0
967         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
968     fi
969
970     CIDR=$(cidr_notation $NETMASK)
971     
972
973     if [ "$(id -u)" != "0" ]; then
974           echo "This script should be run as 'root'"
975           exit 1
976     fi
977
978     path=/var/lib/lxc
979     rootfs_path=$path/$lxc/rootfs
980     config_path=$path/$lxc
981     cache_base=/var/cache/lxc/fedora/$arch
982     cache=$cache_base/$release
983     root_password=root
984     
985     # check whether the rootfs directory is created to know if the container exists
986     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
987     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
988
989     setup_lxc $lxc $fcdistro $pldistro $personality 
990
991     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
992
993     post_install $lxc $personality
994     
995     start_lxc $lxc
996
997     echo $COMMAND Done
998 }
999
1000 main "$@"