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