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