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