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