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