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