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