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