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