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