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