myplc from master
[build.git] / vbuild-init-lxc.sh
1 #!/bin/bash
2 # -*-shell-*-
3
4 #shopt -s huponexit
5
6 COMMAND=$(basename $0)
7 DIRNAME=$(dirname $0)
8 BUILD_DIR=$(pwd)
9
10 # pkgs parsing utilities
11 PATH=$(dirname $0):$PATH export PATH
12 . build.common
13
14 DEFAULT_FCDISTRO=f16
15 DEFAULT_PLDISTRO=planetlab
16 DEFAULT_PERSONALITY=linux64
17 DEFAULT_IFNAME=eth0
18
19 COMMAND_VBUILD="vbuild-init-lxc.sh"
20 COMMAND_MYPLC="vtest-init-lxc.sh"
21
22 libvirt_version="1.0.4"
23 function bridge_init () {
24
25     # turn on verbosity
26     set -x
27
28     # constant
29     INTERFACE_BRIDGE=br0
30
31     # Default Value for INTERFACE_LAN
32     INTERFACE_LAN=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
33
34
35     echo "========== $COMMAND: entering start - beg"
36     hostname
37     uname -a
38     ifconfig
39     netstat -rn
40     echo "========== $COMMAND: entering start - end"
41
42     # disable netfilter calls for bridge interface (they cause panick on 2.6.35 anyway)
43     #
44     # another option would be to accept the all forward packages for
45     # bridged interface like: -A FORWARD -m physdev --physdev-is-bridged -j ACCEPT
46     sysctl net.bridge.bridge-nf-call-iptables=0
47     sysctl net.bridge.bridge-nf-call-ip6tables=0
48     sysctl net.bridge.bridge-nf-call-arptables=0
49
50     # take extra arg for ifname, if provided
51     [ -n "$1" ] && { INTERFACE_LAN=$1; shift ; }
52
53     #if we have already configured the same host_box no need to do it again
54     /sbin/ifconfig $INTERFACE_BRIDGE &> /dev/null && {
55         echo "Bridge interface $INTERFACE_BRIDGE already set up - $COMMAND start exiting"
56         return 0
57     }
58     /sbin/ifconfig $INTERFACE_LAN &>/dev/null || {
59         echo "Cannot use interface $INTERFACE_LAN - exiting"
60         exit 1
61     }
62
63     
64     #Getting host IP/masklen
65     address=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $2;}')
66     [ -z "$address" ] && { echo "ERROR: Could not determine IP address for $INTERFACE_LAN" ; exit 1 ; }
67
68     broadcast=$(/sbin/ip addr show $INTERFACE_LAN | grep -v inet6 | grep inet | head --lines=1 | awk '{print $4;}')
69     [ -z "$broadcast" ] && echo "WARNING: Could not determine broadcast address for $INTERFACE_LAN"
70
71     gateway=$(netstat -rn | grep '^0.0.0.0' | awk '{print $2;}')
72     [ -z "$gateway" ] && echo "WARNING: Could not determine gateway IP"
73
74     # creating the bridge
75     echo "Creating bridge INTERFACE_BRIDGE=$INTERFACE_BRIDGE"
76     brctl addbr $INTERFACE_BRIDGE
77     #brctl stp $INTERFACE_BRIDGE yes
78     brctl addif $INTERFACE_BRIDGE $INTERFACE_LAN
79     echo "Activating promiscuous mode INTERFACE_LAN=$INTERFACE_LAN"
80     /sbin/ifconfig $INTERFACE_LAN 0.0.0.0 promisc up
81     sleep 2
82     echo "Setting bridge address=$address broadcast=$broadcast"
83     # static
84     #/sbin/ifconfig $INTERFACE_BRIDGE $address broadcast $broadcast up
85     dhclient $INTERFACE_BRIDGE
86     sleep 1
87
88     #Reconfigure the routing table
89     echo "Configuring gateway=$gateway"
90     route add default gw $gateway
91
92     echo "========== $COMMAND: exiting start - beg"
93     ifconfig
94     netstat -rn
95     echo "========== $COMMAND: exiting start - end"
96
97
98 return 0
99
100 }
101
102
103 function failure () {
104     echo "$COMMAND : Bailing out"
105     exit 1
106 }
107
108 function cidr_notation () {
109
110 netmask=$1; shift
111 cidr=0
112 for i in $(seq 1 4) ; do
113     part=$(echo $netmask | cut -d. -f $i)
114     case $part in
115         "255") cidr=$((cidr + 8));;
116         "254") cidr=$((cidr + 7));;
117         "252") cidr=$((cidr + 6));;
118         "248") cidr=$((cidr + 5));;
119         "240") cidr=$((cidr + 4));;
120         "224") cidr=$((cidr + 3));;
121         "192") cidr=$((cidr + 2));;
122         "128") cidr=$((cidr + 1));;
123         "0") cidr=$((cidr + 0));;
124      esac
125 done
126 echo $cidr
127
128 }
129
130 function check_yum_installed () {
131     package=$1; shift
132     rpm -q $package >& /dev/null || yum -y install $package
133 }
134
135 function check_yumgroup_installed () {
136     group="$1"; shift
137     yum grouplist "$group" | grep -q Installed || { yum -y groupinstall "$group" ; }
138 }
139
140 function prepare_host() {
141    
142     host_fcdistro="$(cat /etc/fedora-release | cut -d' ' -f3)"    
143     ## check if libvirt_version is installed
144     virsh -v | grep -e $libvirt_version || { echo "$libvirt_version needs to be installed!!!" ; exit 1 ; }
145 #    host_fcdistro="$(cat /etc/fedora-release | cut -d' ' -f3)"
146 #    if [ ! -f /etc/yum.repos.d/libvirt.repo ] ; then
147 #       touch /etc/yum.repos.d/libvirt.repo
148 #       cat <<EOF > /etc/yum.repos.d/libvirt.repo
149 #[libvirt]
150 #name=libvirt-1.0.2-1
151 #baseurl=http://build.onelab.eu/lxc/2013.02.25--lxc$host_fcdistro/RPMS/
152 #enabled=1
153 #gpgcheck=0
154 #EOF
155 #
156 #       yum --assumeno update
157 #       check_yumgroup_installed "Development Tools"
158 #       check_yum_installed libcap-devel
159 #       check_yum_installed libvirt
160 #       systemctl start libvirtd
161 #    fi
162
163     #################### bride initialization
164     check_yum_installed bridge-utils
165     #Bridge init
166     isInstalled=$(netstat -rn | grep '^0.0.0.0' | awk '{print $8;}')
167     if [ "$isInstalled" != "br0" ] ; then
168         bridge_init
169         sleep 5
170     fi
171
172     return 0
173 }
174
175
176
177 function configure_fedora() {
178
179     # disable selinux in fedora
180     mkdir -p $rootfs_path/selinux
181     echo 0 > $rootfs_path/selinux/enforce
182
183    # configure the network 
184
185     cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-$IFNAME
186 DEVICE=$IFNAME
187 BOOTPROTO=static
188 ONBOOT=yes
189 HOSTNAME=$HOSTNAME
190 IPADDR=$IP
191 NETMASK=$NETMASK
192 GATEWAY=$GATEWAY
193 NM_CONTROLLED=no
194 TYPE=Ethernet
195 MTU=1500
196 EOF
197
198     # set the hostname
199     case "$fcdistro" in 
200         f18|f2?)
201             cat <<EOF > ${rootfs_path}/etc/hostname
202 $HOSTNAME
203 EOF
204             echo ;;
205         *)
206             cat <<EOF > ${rootfs_path}/etc/sysconfig/network
207 NETWORKING=yes
208 HOSTNAME=$HOSTNAME
209 EOF
210             # set minimal hosts
211             cat <<EOF > $rootfs_path/etc/hosts
212 127.0.0.1 localhost $HOSTNAME
213 EOF
214             echo ;;
215     esac
216
217     dev_path="${rootfs_path}/dev"
218     rm -rf $dev_path
219     mkdir -p $dev_path
220     mknod -m 666 ${dev_path}/null c 1 3
221     mknod -m 666 ${dev_path}/zero c 1 5
222     mknod -m 666 ${dev_path}/random c 1 8
223     mknod -m 666 ${dev_path}/urandom c 1 9
224     mkdir -m 755 ${dev_path}/pts
225     mkdir -m 1777 ${dev_path}/shm
226     mknod -m 666 ${dev_path}/tty c 5 0
227     mknod -m 666 ${dev_path}/tty0 c 4 0
228     mknod -m 666 ${dev_path}/tty1 c 4 1
229     mknod -m 666 ${dev_path}/tty2 c 4 2
230     mknod -m 666 ${dev_path}/tty3 c 4 3
231     mknod -m 666 ${dev_path}/tty4 c 4 4
232     mknod -m 600 ${dev_path}/console c 5 1
233     mknod -m 666 ${dev_path}/full c 1 7
234     mknod -m 600 ${dev_path}/initctl p
235     mknod -m 666 ${dev_path}/ptmx c 5 2
236
237     #echo "setting root passwd to $root_password"
238     #echo "root:$root_password" | chroot $rootfs_path chpasswd
239
240     return 0
241 }
242
243
244 function configure_fedora_init() {
245
246     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.sysinit
247     sed -i 's|.sbin.start_udev||' ${rootfs_path}/etc/rc.d/rc.sysinit
248     # don't mount devpts, for pete's sake
249     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.sysinit
250     sed -i 's/^.*dev.pts.*$/#\0/' ${rootfs_path}/etc/rc.d/rc.sysinit
251     chroot ${rootfs_path} /sbin/chkconfig udev-post off
252     chroot ${rootfs_path} /sbin/chkconfig network on
253 }
254
255 # this code of course is for guests that do run on systemd
256 function configure_fedora_systemd() {
257     # so ignore if we can't find /etc/systemd at all 
258     [ -d ${rootfs_path}/etc/systemd ] || return 0
259     # otherwise let's proceed
260     ln -sf /lib/systemd/system/multi-user.target ${rootfs_path}/etc/systemd/system/default.target
261     touch ${rootfs_path}/etc/fstab
262     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/udev.service
263 # Thierry - Feb 2013
264 # this was intended for f16 initially, in order to enable getty that otherwise would not start
265 # having a getty running is helpful only if ssh won't start though, and we see a correlation between
266 # VM's that refuse to lxc-stop and VM's that run crazy getty's
267 # so, turning getty off for now instead
268 #   #dependency on a device unit fails it specially that we disabled udev
269 #    sed -i 's/After=dev-%i.device/After=/' ${rootfs_path}/lib/systemd/system/getty\@.service
270     ln -sf /dev/null ${rootfs_path}/etc/systemd/system/"getty@.service"
271     rm -f ${rootfs_path}/etc/systemd/system/getty.target.wants/*service || :
272 # can't seem to handle this one with systemctl
273     chroot ${rootfs_path} /sbin/chkconfig network on
274 }
275
276 function download_fedora() {
277 set -x
278     # check the mini fedora was not already downloaded
279     INSTALL_ROOT=$cache/partial
280     echo $INSTALL_ROOT
281
282     # download a mini fedora into a cache
283     echo "Downloading fedora minimal ..."
284
285     mkdir -p $INSTALL_ROOT
286     if [ $? -ne 0 ]; then
287         echo "Failed to create '$INSTALL_ROOT' directory"
288         return 1
289     fi
290
291     mkdir -p $INSTALL_ROOT/etc/yum.repos.d   
292     mkdir -p $INSTALL_ROOT/dev
293     mknod -m 0444 $INSTALL_ROOT/dev/random c 1 8
294     mknod -m 0444 $INSTALL_ROOT/dev/urandom c 1 9
295
296     # copy yum config and repo files
297     cp /etc/yum.conf $INSTALL_ROOT/etc/
298     cp /etc/yum.repos.d/fedora* $INSTALL_ROOT/etc/yum.repos.d/
299
300     # append fedora repo files with desired $release and $basearch
301     for f in $INSTALL_ROOT/etc/yum.repos.d/*
302     do
303       sed -i "s/\$basearch/$arch/g; s/\$releasever/$release/g;" $f
304     done 
305
306     MIRROR_URL=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os
307     RELEASE_URL1="$MIRROR_URL/Packages/fedora-release-$release-1.noarch.rpm"
308     # with fedora18 the rpms are scattered by first name
309     RELEASE_URL2="$MIRROR_URL/Packages/f/fedora-release-$release-1.noarch.rpm"
310     RELEASE_TARGET=$INSTALL_ROOT/fedora-release-$release.noarch.rpm
311     found=""
312     for attempt in $RELEASE_URL1 $RELEASE_URL2; do
313         if curl -f $attempt -o $RELEASE_TARGET ; then
314             echo "Retrieved $attempt"
315             found=true
316             break
317         else
318             echo "Failed attempt $attempt"
319         fi
320     done
321     [ -n "$found" ] || { echo "Could not retrieve fedora-release rpm - exiting" ; exit 1; }
322     
323     mkdir -p $INSTALL_ROOT/var/lib/rpm
324     rpm --root $INSTALL_ROOT  --initdb
325     # when installing f12 this apparently is already present, so ignore result
326     rpm --root $INSTALL_ROOT -ivh $INSTALL_ROOT/fedora-release-$release.noarch.rpm || :
327     # however f12 root images won't get created on a f18 host
328     # (the issue here is the same as the one we ran into when dealing with a vs-box)
329     # in a nutshell, in f12 the glibc-common and filesystem rpms have an apparent conflict
330     # >>> file /usr/lib/locale from install of glibc-common-2.11.2-3.x86_64 conflicts 
331     #          with file from package filesystem-2.4.30-2.fc12.x86_64
332     # in fact this was - of course - allowed by f12's rpm but later on a fix was made 
333     #   http://rpm.org/gitweb?p=rpm.git;a=commitdiff;h=cf1095648194104a81a58abead05974a5bfa3b9a
334     # So ideally if we want to be able to build f12 images from f18 we need an rpm that has
335     # this patch undone, like we have in place on our f14 boxes (our f14 boxes need a f18-like rpm)
336
337     YUM="yum --installroot=$INSTALL_ROOT --nogpgcheck -y"
338     PKG_LIST="yum initscripts passwd rsyslog vim-minimal dhclient chkconfig rootfiles policycoreutils openssh-server openssh-clients"
339     echo "$YUM install $PKG_LIST"
340     $YUM install $PKG_LIST
341
342     if [ $? -ne 0 ]; then
343         echo "Failed to download the rootfs, aborting."
344         return 1
345     fi
346
347     mv "$INSTALL_ROOT" "$cache/rootfs"
348     echo "Download complete."
349
350     return 0
351 }
352
353
354 function copy_fedora() {
355 set -x
356     # make a local copy of the minifedora
357     echo -n "Copying rootfs to $rootfs_path ..."
358     mkdir -p $rootfs_path
359     rsync -a $cache/rootfs/ $rootfs_path/
360     return 0
361 }
362
363
364 function update_fedora() {
365 set -x
366     YUM="yum --installroot $cache/rootfs -y --nogpgcheck"
367     $YUM update
368 }
369
370
371 function install_fedora() {
372     set -x
373
374     mkdir -p /var/lock/subsys/
375     (
376         flock -n -x 200
377         if [ $? -ne 0 ]; then
378             echo "Cache repository is busy."
379             return 1
380         fi
381
382         echo "Checking cache download in $cache/rootfs ... "
383         if [ ! -e "$cache/rootfs" ]; then
384             download_fedora
385             if [ $? -ne 0 ]; then
386                 echo "Failed to download 'fedora base'"
387                 return 1
388             fi
389         else
390             echo "Cache found. Updating..."
391             update_fedora
392             if [ $? -ne 0 ]; then
393                 echo "Failed to update 'fedora base', continuing with last known good cache"
394             else
395                 echo "Update finished"
396             fi
397         fi
398
399         echo "Copy $cache/rootfs to $rootfs_path ... "
400         copy_fedora
401         if [ $? -ne 0 ]; then
402             echo "Failed to copy rootfs"
403             return 1
404         fi
405
406         return 0
407
408         ) 200>/var/lock/subsys/lxc
409
410     return $?
411 }
412
413
414 function copy_configuration() {
415
416     mkdir -p $config_path
417     cat <<EOF >> $config_path/config
418 lxc.utsname = $lxc
419 lxc.arch = $arch2
420 lxc.tty = 4
421 lxc.pts = 1024
422 lxc.rootfs = $rootfs_path
423 lxc.mount  = $config_path/fstab
424 #networking
425 lxc.network.type = $lxc_network_type
426 lxc.network.flags = up
427 lxc.network.link = $lxc_network_link
428 lxc.network.name = $IFNAME
429 lxc.network.mtu = 1500
430 lxc.network.ipv4 = $IP/$CIDR
431 lxc.network.veth.pair = $veth_pair
432 #cgroups
433 #lxc.cgroup.devices.deny = a
434 # /dev/null and zero
435 lxc.cgroup.devices.allow = c 1:3 rwm
436 lxc.cgroup.devices.allow = c 1:5 rwm
437 # consoles
438 lxc.cgroup.devices.allow = c 5:1 rwm
439 lxc.cgroup.devices.allow = c 5:0 rwm
440 lxc.cgroup.devices.allow = c 4:0 rwm
441 lxc.cgroup.devices.allow = c 4:1 rwm
442 # /dev/{,u}random
443 lxc.cgroup.devices.allow = c 1:9 rwm
444 lxc.cgroup.devices.allow = c 1:8 rwm
445 lxc.cgroup.devices.allow = c 136:* rwm
446 lxc.cgroup.devices.allow = c 5:2 rwm
447 # rtc
448 lxc.cgroup.devices.allow = c 254:0 rwm
449 lxc.cgroup.devices.allow = b 255:0 rwm
450 EOF
451
452
453
454     cat <<EOF > $config_path/fstab
455 proc            $rootfs_path/proc         proc    nodev,noexec,nosuid 0 0
456 devpts          $rootfs_path/dev/pts      devpts defaults 0 0
457 sysfs           $rootfs_path/sys          sysfs defaults  0 0
458 EOF
459     if [ $? -ne 0 ]; then
460         echo "Failed to add configuration"
461         return 1
462     fi
463
464     return 0
465 }
466
467
468
469
470 # overwrite lxc's internal yum config
471 function configure_yum_in_lxc () {
472     set -x 
473     set -e 
474     trap failure ERR INT
475
476     lxc=$1; shift
477     fcdistro=$1; shift
478     pldistro=$1; shift
479
480     echo "Initializing yum.repos.d in $lxc"
481     rm -f $rootfs_path/etc/yum.repos.d/*
482
483     cat > $rootfs_path/etc/yum.repos.d/building.repo <<EOF
484 [fedora]
485 name=Fedora $release - $arch
486 baseurl=http://mirror.onelab.eu/fedora/releases/$release/Everything/$arch/os/
487 enabled=1
488 metadata_expire=7d
489 gpgcheck=1
490 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
491
492 [updates]
493 name=Fedora $release - $arch - Updates
494 baseurl=http://mirror.onelab.eu/fedora/updates/$release/$arch/
495 enabled=1
496 metadata_expire=7d
497 gpgcheck=1
498 gpgkey=http://mirror.onelab.eu/keys/RPM-GPG-KEY-fedora-$release-primary
499 EOF
500     
501     # for using vtest-init-lxc.sh as a general-purpose lxc creation wrapper
502     # just mention 'none' as the repo url
503     if [ -n "$MYPLC_MODE" -a "$REPO_URL" != "none" ] ; then
504         if [ ! -d $rootfs_path/etc/yum.repos.d ] ; then
505             echo "WARNING : cannot create myplc repo"
506         else
507             # exclude kernel from fedora repos 
508             yumexclude=$(pl_plcyumexclude $fcdistro $pldistro $DIRNAME)
509             for repo in $rootfs_path/etc/yum.repos.d/* ; do
510                 [ -f $repo ] && yumconf_exclude $repo "exclude=$yumexclude" 
511             done
512             # the build repo is not signed at this stage
513             cat > $rootfs_path/etc/yum.repos.d/myplc.repo <<EOF
514 [myplc]
515 name= MyPLC
516 baseurl=$REPO_URL
517 enabled=1
518 gpgcheck=0
519 EOF
520         fi
521     fi
522 }    
523
524 # return yum or debootstrap
525 function package_method () {
526     fcdistro=$1; shift
527     case $fcdistro in
528         f[0-9]*|centos[0-9]*|sl[0-9]*) echo yum ;;
529         lenny|etch) echo debootstrap ;;
530         *) echo Unknown distro $fcdistro ;;
531     esac 
532 }
533
534 # return arch from debian distro and personality
535 function canonical_arch () {
536     personality=$1; shift
537     fcdistro=$1; shift
538     case $(package_method $fcdistro) in
539         yum)
540             case $personality in *32) echo i386 ;; *64) echo x86_64 ;; *) echo Unknown-arch-1 ;; esac ;;
541         debootstrap)
542             case $personality in *32) echo i386 ;; *64) echo amd64 ;; *) echo Unknown-arch-2 ;; esac ;;
543         *)
544             echo Unknown-arch-3 ;;
545     esac
546 }
547
548 # the new test framework creates /timestamp in /vservers/<name> *before* populating it
549 function almost_empty () { 
550     dir="$1"; shift ; 
551     # non existing is fine
552     [ ! -d $dir ] && return 0; 
553     # need to have at most one file
554     count=$(cd $dir; ls | wc -l); [ $count -le 1 ]; 
555 }
556
557 function setup_lxc() {
558
559     set -x
560     set -e
561     #trap failure ERR INT
562
563     lxc=$1; shift
564     fcdistro=$1; shift
565     pldistro=$1; shift
566     personality=$1; shift
567
568     # create lxc container 
569     copy_configuration
570     if [ $? -ne 0 ]; then
571         echo "failed write configuration file"
572         exit 1
573     fi
574
575     install_fedora
576     if [ $? -ne 0 ]; then
577         echo "failed to install fedora"
578         exit 1
579     fi
580
581     configure_fedora
582     if [ $? -ne 0 ]; then
583         echo "failed to configure fedora for a container"
584         exit 1
585     fi
586
587     if [ "$(echo $fcdistro | cut -d"f" -f2)" -le "14" ]; then
588         configure_fedora_init
589     else
590         configure_fedora_systemd
591     fi
592
593     # Enable cgroup
594     mkdir $rootfs_path/cgroup
595     
596     # set up resolv.conf
597     cp /etc/resolv.conf $rootfs_path/etc/resolv.conf
598     # and /etc/hosts for at least localhost
599     [ -f $rootfs_path/etc/hosts ] || echo "127.0.0.1 localhost localhost.localdomain" > $rootfs_path/etc/hosts
600     
601     # ssh access to lxc
602     mkdir $rootfs_path/root/.ssh
603     cat /root/.ssh/id_rsa.pub >> $rootfs_path/root/.ssh/authorized_keys
604     
605     # copy libvirt xml template
606     veth_pair="i$(echo $HOSTNAME | cut -d. -f1)" 
607     tmpl_name="$lxc.xml"
608     cat > $config_path/$tmpl_name<<EOF
609 <domain type='lxc'>
610   <name>$lxc</name>
611   <memory>524288</memory>
612   <os>
613     <type arch='$arch2'>exe</type>
614     <init>/sbin/init</init>
615   </os>
616   <features>
617     <acpi/>
618   </features>
619   <vcpu>1</vcpu>
620   <clock offset='utc'/>
621   <on_poweroff>destroy</on_poweroff>
622   <on_reboot>restart</on_reboot>
623   <on_crash>destroy</on_crash>
624   <devices>
625     <emulator>/usr/libexec/libvirt_lxc</emulator>
626     <filesystem type='mount'>
627       <source dir='$rootfs_path'/>
628       <target dir='/'/>
629     </filesystem>
630     <interface type="bridge">
631       <source bridge="br0"/>
632       <target dev='$veth_pair'/>
633     </interface>
634     <console type='pty' />
635   </devices>
636   <network>
637     <name>host-bridge</name>
638     <forward mode="bridge"/>
639     <bridge name="br0"/>
640   </network>
641 </domain>
642 EOF
643    
644     # define lxc container for libvirt
645     virsh -c lxc:// define $config_path/$tmpl_name
646
647     # rpm --rebuilddb
648     chroot $rootfs_path /bin/rpm --rebuilddb
649
650     configure_yum_in_lxc $lxc $fcdistro $pldistro
651
652     return 0
653 }
654
655 function devel_or_vtest_tools () {
656
657     set -x 
658     set -e 
659     trap failure ERR INT
660
661     lxc=$1; shift
662     fcdistro=$1; shift
663     pldistro=$1; shift
664     personality=$1; shift
665
666     pkg_method=$(package_method $fcdistro)
667
668     # check for .pkgs file based on pldistro
669     if [ -n "$VBUILD_MODE" ] ; then
670         pkgsname=devel.pkgs
671     else
672         pkgsname=vtest.pkgs
673     fi
674     pkgsfile=$(pl_locateDistroFile $DIRNAME $pldistro $pkgsname)
675
676     ### install individual packages, then groups
677     # get target arch - use uname -i here (we want either x86_64 or i386)
678    
679     lxc_arch=$(chroot $rootfs_path /bin/uname -i)
680     # on debian systems we get arch through the 'arch' command
681     [ "$lxc_arch" = "unknown" ] && lxc_arch=$(chroot $rootfs_path /bin/arch)
682
683     packages=$(pl_getPackages -a $lxc_arch $fcdistro $pldistro $pkgsfile)
684     groups=$(pl_getGroups -a $lxc_arch $fcdistro $pldistro $pkgsfile)
685
686     case "$pkg_method" in
687         yum)
688             [ -n "$packages" ] && chroot $rootfs_path /usr/bin/yum -y install $packages
689             for group_plus in $groups; do
690                 group=$(echo $group_plus | sed -e "s,+++, ,g")
691                 chroot $rootfs_path /usr/bin/yum -y groupinstall "$group"
692             done
693             # store current rpm list in /init-lxc.rpms in case we need to check the contents
694             chroot $rootfs_path /bin/rpm -aq > $rootfs_path/init-lxc.rpms
695             ;;
696         debootstrap)
697             chroot $rootfs_path /usr/bin/apt-get update
698             for package in $packages ; do 
699                 chroot $rootfs_path  /usr/bin/apt-get install -y $package 
700             done
701             ### xxx todo install groups with apt..
702             ;;
703         *)
704             echo "unknown pkg_method $pkg_method"
705             ;;
706     esac
707
708     return 0
709 }
710
711 function post_install () {
712     if [ -n "$VBUILD_MODE" ] ; then
713         post_install_vbuild "$@" 
714     else
715         post_install_myplc "$@"
716     fi
717     # setup localtime from the host
718     lxc=$1; shift 
719     cp /etc/localtime $rootfs_path/etc/localtime
720 }
721
722 function post_install_vbuild () {
723
724     set -x 
725     set -e 
726     trap failure ERR INT
727
728     lxc=$1; shift
729     personality=$1; shift
730
731 ### From myplc-devel-native.spec
732 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
733     cat << EOF | chroot $rootfs_path /bin/bash -x
734     # set up /dev/loop* in lxc
735     for i in \$(seq 0 255) ; do
736         /bin/mknod -m 640 /dev/loop\$i b 7 \$i
737     done
738     
739     # create symlink for /dev/fd
740     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
741
742     # modify /etc/rpm/macros to not use /sbin/new-kernel-pkg
743     /bin/sed -i 's,/sbin/new-kernel-pkg:,,' /etc/rpm/macros
744     if [ -h "/sbin/new-kernel-pkg" ] ; then
745         filename=\$(/bin/readlink -f /sbin/new-kernel-pkg)
746         if [ "\$filename" == "/sbin/true" ] ; then
747                 /bin/echo "WARNING: /sbin/new-kernel-pkg symlinked to /sbin/true"
748                 /bin/echo "\tmost likely /etc/rpm/macros has /sbin/new-kernel-pkg declared in _netsharedpath."
749                 /bin/echo "\tPlease remove /sbin/new-kernel-pkg from _netsharedpath and reintall mkinitrd."
750                 exit 1
751         fi
752     fi
753     
754     # customize root's prompt
755     /bin/cat << PROFILE > /root/.profile
756 export PS1="[$lxc] \\w # "
757 PROFILE
758
759     uid=2000
760     gid=2000
761     
762     # add a "build" user to the system
763     builduser=\$(grep "^build:" /etc/passwd | wc -l)
764     if [ \$builduser -eq 0 ] ; then
765         groupadd -o -g \$gid build;
766         useradd -o -c 'Automated Build' -u \$uid -g \$gid -n -M -s /bin/bash build;
767     fi
768
769 # Allow build user to build certain RPMs as root
770     if [ -f /etc/sudoers ] ; then
771         buildsudo=\$(grep "^build.*ALL=(ALL).*NOPASSWD:.*ALL"  /etc/sudoers | wc -l)
772         if [ \$buildsudo -eq 0 ] ; then
773             echo "build   ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
774         fi
775         sed -i 's,^Defaults.*requiretty,#Defaults requiretty,' /etc/sudoers
776     fi
777 #
778 EOF
779
780 }
781
782 function post_install_myplc  () {
783     set -x 
784     set -e 
785     trap failure ERR INT
786
787     lxc=$1; shift
788     personality=$1; shift
789
790 # be careful to backslash $ in this, otherwise it's the root context that's going to do the evaluation
791     cat << EOF | chroot $rootfs_path /bin/bash -x
792
793     # create /etc/sysconfig/network if missing
794     [ -f /etc/sysconfig/network ] || /bin/echo NETWORKING=yes > /etc/sysconfig/network
795
796     # create symlink for /dev/fd
797     [ ! -e "/dev/fd" ] && /bin/ln -s /proc/self/fd /dev/fd
798
799     # turn off regular crond, as plc invokes plc_crond
800     /sbin/chkconfig crond off
801
802     # take care of loginuid in /etc/pam.d 
803     /bin/sed -i "s,#*\(.*loginuid.*\),#\1," /etc/pam.d/*
804
805     # customize root's prompt
806     /bin/cat << PROFILE > /root/.profile
807 export PS1="[$lxc] \\w # "
808 PROFILE
809
810 EOF
811 }
812
813 function start_lxc() {
814
815     set -x
816     set -e
817     #trap failure ERR INT
818
819     lxc=$1; shift
820   
821     virsh -c lxc:// start $lxc
822   
823     echo $IP is up, waiting for ssh...
824
825     #wait max 5 min for sshd to start 
826     ssh_up=""
827     stop_time=$(($(date +%s) + 300))
828     current_time=$(date +%s)
829     
830     counter=1
831     while [ "$current_time" -lt "$stop_time" ] ; do
832          echo "$counter-th attempt to reach sshd in container $lxc ..."
833          ssh -o "StrictHostKeyChecking no" $IP 'uname -i' && { ssh_up=true; echo "SSHD in container $lxc is UP"; break ; } || :
834          sleep 10
835          current_time=$(($current_time + 10))
836          counter=$(($counter+1))
837     done
838
839     # Thierry: this is fatal, let's just exit with a failure here
840     [ -z $ssh_up ] && { echo "SSHD in container $lxc is not running" ; exit 1 ; } 
841
842     return 0
843 }
844
845 function usage () {
846     set +x 
847     echo "Usage: $COMMAND_VBUILD [options] lxc-name"
848     echo "Usage: $COMMAND_MYPLC [options] lxc-name repo-url [ -- lxc-options ]"
849     echo "Description:"
850     echo "   This command creates a fresh lxc instance, for building, or running, myplc"
851     echo "Supported options"
852     echo " -f fcdistro - for creating the root filesystem - defaults to $DEFAULT_FCDISTRO"
853     echo " -d pldistro - defaults to $DEFAULT_PLDISTRO"
854     echo " -p personality - defaults to $DEFAULT_PERSONALITY"
855     echo " -i ifname: determines ip and netmask attached to ifname, and passes it to the lxc"
856     echo "-- lxc-options"
857     echo "  --netdev : interface to be defined inside lxc"
858     echo "  --interface : IP to be defined for the lxc"
859     echo "  --hostname : Hostname to be defined for the lxc"
860     echo "With $COMMAND_MYPLC you can give 'none' as the URL, in which case"
861     echo "   myplc.repo does not get created"
862     exit 1
863 }
864
865 ### parse args and 
866 function main () {
867
868     #set -e
869     #trap failure ERR INT
870
871     case "$COMMAND" in
872         $COMMAND_VBUILD)
873             VBUILD_MODE=true ;;
874         $COMMAND_MYPLC)
875             MYPLC_MODE=true;;
876         *)
877             usage ;;
878     esac
879
880     VERBOSE=
881     RESISTANT=""
882     IFNAME=""
883     LXC_OPTIONS=""
884     while getopts "f:d:p:i:" opt ; do
885         case $opt in
886             f) fcdistro=$OPTARG;;
887             d) pldistro=$OPTARG;;
888             p) personality=$OPTARG;;
889             i) IFNAME=$OPTARG;;
890             *) usage ;;
891         esac
892     done
893         
894     shift $(($OPTIND - 1))
895
896     # parse fixed arguments
897     [[ -z "$@" ]] && usage
898     lxc=$1 ; shift
899     if [ -n "$MYPLC_MODE" ] ; then
900         [[ -z "$@" ]] && usage
901         REPO_URL=$1 ; shift
902     fi
903
904     # parse vserver options
905     if [[ -n "$@" ]] ; then
906         if [ "$1" == "--" ] ; then
907             shift
908             LXC_OPTIONS="$@"
909         else
910             usage
911         fi
912     fi
913
914     eval set -- "$LXC_OPTIONS"
915
916     while true
917      do
918         case "$1" in
919              --netdev)      IFNAME=$2; shift 2;;
920              --interface)   IP=$2; shift 2;;
921              --hostname)    HOSTNAME=$2; shift 2;;
922              *)             break ;;
923         esac
924       done
925
926    
927     if [ -n "$VBUILD_MODE" ] ; then
928         [ -z "$IFNAME" ] && IFNAME=$DEFAULT_IFNAME
929         [ -z "$HOSTNAME" ] && HOSTNAME=$lxc
930     fi
931
932     [ -z "$fcdistro" ] && fcdistro=$DEFAULT_FCDISTRO
933     [ -z "$pldistro" ] && pldistro=$DEFAULT_PLDISTRO
934     [ -z "$personality" ] && personality=$DEFAULT_PERSONALITY
935     
936     release=$(echo $fcdistro | cut -df -f2)
937
938     if [ "$personality" == "linux32" ]; then
939         arch=i386
940         arch2=i686
941     elif [ "$personality" == "linux64" ]; then
942         arch=x86_64
943         arch2=x86_64
944     else
945         echo "Unknown personality: $personality"
946     fi
947
948     # need lxc installed before we can run lxc-ls
949     # need bridge installed
950     prepare_host    
951
952     if [ -n "$VBUILD_MODE" ] ; then
953
954         # Bridge IP affectation
955         x=$(echo $personality | cut -dx -f2)
956         y=$(echo $fcdistro | cut -df -f2)
957         z=$(($x + $y))
958
959         IP="192.168.122.$z"
960         NETMASK="255.255.255.0"
961         GATEWAY="192.168.122.1"
962         
963         lxc_network_type=veth
964         lxc_network_link=virbr0
965         veth_pair="veth$z"
966         echo "the IP address of container $lxc is $IP "
967     else
968         [[ -z "$REPO_URL" ]] && usage
969         [[ -z "$IP" ]] && usage
970        
971         NETMASK=$(ifconfig br0 | grep 'inet ' | awk '{print $4}' | sed -e 's/.*://')
972         GATEWAY=$(route -n | grep 'UG' | awk '{print $2}')
973         [[ -z "$HOSTNAME" ]] && usage
974         lxc_network_type=veth
975         lxc_network_link=br0
976         veth_pair="i$(echo $HOSTNAME | cut -d. -f1)"
977     fi
978
979     CIDR=$(cidr_notation $NETMASK)
980     
981
982     if [ "$(id -u)" != "0" ]; then
983           echo "This script should be run as 'root'"
984           exit 1
985     fi
986
987     path=/vservers
988     [ ! -d $path ] && mkdir $path
989     rootfs_path=$path/$lxc/rootfs
990     config_path=$path/$lxc
991     cache_base=/var/cache/lxc/fedora/$arch
992     cache=$cache_base/$release
993     root_password=root
994     
995     # check whether the rootfs directory is created to know if the container exists
996     # bacause /var/lib/lxc/$lxc is already created while putting $lxc.timestamp
997     [ -d $rootfs_path ] && { echo "container $lxc already exists - exiting" ; exit 1 ; }
998
999     setup_lxc $lxc $fcdistro $pldistro $personality 
1000
1001     devel_or_vtest_tools $lxc $fcdistro $pldistro $personality
1002
1003     post_install $lxc $personality
1004     
1005     start_lxc $lxc
1006
1007     echo $COMMAND Done
1008 }
1009
1010 main "$@"