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