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