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