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