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