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