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