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