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