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