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