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