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