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