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