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