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