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