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