18e7a0679939f16aed35334a8601c462e10d904a
[tridge/autocluster.git] / autocluster
1 #!/bin/bash
2 # main autocluster script
3 #
4 # Copyright (C) Andrew Tridgell  2008
5 # Copyright (C) Martin Schwenke  2008
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #   
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #   
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, see <http://www.gnu.org/licenses/>.
19
20 ##BEGIN-INSTALLDIR-MAGIC##
21 # There are better ways of doing this but not if you still want to be
22 # able to run straight out of a git tree.  :-)
23 if [ -f "$0" ]; then
24     installdir="`dirname \"$0\"`"
25 else
26     autocluster=`which $0`
27     installdir="`dirname \"$autocluster\"`"
28 fi
29 ##END-INSTALLDIR-MAGIC##
30
31 ####################
32 # show program usage
33 usage ()
34 {
35     cat <<EOF
36 Usage: autocluster [OPTION] ... <COMMAND>
37   options:
38      -c <file>                   specify config file (default is "config")
39 EOF
40
41     releases=$(list_releases)
42
43     usage_smart_display \
44         defconf "WITH_RELEASE" "" \
45         "<string>" "specify preset options for a release using a version string.  Possible values are: ${releases}."
46
47 cat <<EOF
48      -e <expr>                   execute <expr> and exit (advanced debugging)
49      -x                          enable script debugging
50      --dump                      dump config settings and exit
51
52   configuration options:
53 EOF
54
55     usage_config_options
56
57     cat <<EOF
58
59   commands:
60      create base
61            create a base image
62
63      create cluster CLUSTERNAME
64            create a full cluster
65
66      create node CLUSTERNAME IP_OFFSET
67            (re)create a single cluster node
68
69      mount DISK
70            mount a qemu disk on mnt/
71
72      unmount
73            unmount a qemu disk from mnt/
74
75      bootbase
76            boot the base image
77
78      testproxy
79            test your proxy setup
80 EOF
81     exit 1
82 }
83
84 ###############################
85
86 die () {
87     fill_text 0 "ERROR: $*" >&2
88     exit 1
89 }
90
91 ###############################
92
93 # Indirectly call a function named by ${1}_${2}
94 call_func () {
95     local func="$1" ; shift
96     local type="$1" ; shift
97
98     local f="${func}_${type}"
99     if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
100         "$f" "$@"
101     else
102         f="${func}_DEFAULT"
103         if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null  ; then
104             "$f" "$type" "$@"
105         else
106             die "No function defined for \"${func}\" \"${type}\""
107         fi
108     fi
109 }
110
111 # Note that this will work if you pass "call_func f" because the first
112 # element of the node tuple is the node type.  Nice...  :-)
113 for_each_node ()
114 {
115     local n
116     for n in $NODES ; do
117         "$@" $(IFS=: ; echo $n)
118     done
119 }
120
121 hack_one_node_with ()
122 {
123     local filter="$1" ; shift
124
125     local node_type="$1"
126     local ip_offset="$2"
127     local name="$3"
128     local ctdb_node="$4"
129
130     $filter
131
132     local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
133     nodes="${nodes}${nodes:+ }${item}"
134 }
135
136 # This also gets used for non-filtering iteration.
137 hack_all_nodes_with ()
138 {
139     local filter="$1"
140
141     local nodes=""
142     for_each_node hack_one_node_with "$filter"
143     NODES="$nodes"
144 }
145
146 register_hook ()
147 {
148     local hook_var="$1"
149     local new_hook="$2"
150
151     eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
152 }
153
154 run_hooks ()
155 {
156     local hook_var="$1"
157
158     local i
159     for i in ${!hook_var} ; do
160         $i
161     done
162 }
163
164 # Use with care, since this may clear some autocluster defaults.!
165 clear_hooks ()
166 {
167     local hook_var="$1"
168
169     eval "$hook_var=\"\""
170 }
171
172 ##############################
173
174 # common node creation stuff
175 create_node_COMMON ()
176 {
177     local NAME="$1"
178     local ip_offset="$2"
179     local type="$3"
180     local template_file="${4:-$NODE_TEMPLATE}"
181
182     if [ "$SYSTEM_DISK_FORMAT" = "raw" -a "$BASE_FORMAT" != "raw" ] ; then
183         die "Error: if SYSTEM_DISK_FORMAT is \"raw\" then BASE_FORMAT must also be \"raw\"."
184     fi
185
186     IPNUM=$(($FIRSTIP + $ip_offset))
187     DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
188     local base_disk="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
189
190     if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
191         base_disk="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
192     fi
193
194     mkdir -p $VIRTBASE/$CLUSTER tmp
195
196     rm -f "$DISK"
197     case "$SYSTEM_DISK_FORMAT" in
198         qcow2)
199             echo "Creating the disk..."
200             qemu-img create -b "$base_disk" -f qcow2 "$DISK"
201             create_node_configure_image "$DISK" "$type"
202             ;;
203         raw)
204             echo "Creating the disk..."
205             cp -v --sparse=always "$base_disk" "$DISK"
206             create_node_configure_image "$DISK" "$type"
207             ;;
208         none)
209             echo "Skipping disk image creation as requested"
210             ;;
211         *)
212             die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
213     esac
214
215     set_macaddrs $CLUSTER $ip_offset
216
217     # Pull the UUID for this node out of the map.
218     UUID=$(awk "\$1 == $ip_offset {print \$2}" $uuid_map)
219     
220     echo "Creating $NAME.xml"
221     substitute_vars $template_file tmp/$NAME.xml
222     
223     # install the XML file
224     $VIRSH undefine $NAME > /dev/null 2>&1 || true
225     $VIRSH define tmp/$NAME.xml
226 }
227
228 create_node_configure_image ()
229 {
230     local disk="$1"
231     local type="$2"
232
233     mount_disk "$disk"
234     setup_base "$type"
235     unmount_disk
236 }
237
238 # Provides an easy way of removing nodes from $NODE.
239 create_node_null () {
240     :
241 }
242
243 ##############################
244
245 hack_nodes_functions=
246
247 expand_nodes () {
248     # Expand out any abbreviations in NODES.
249     local ns=""
250     local n
251     for n in $NODES ; do
252         local t="${n%:*}"
253         local ips="${n#*:}"
254         case "$ips" in
255             *,*)
256                 local i
257                 for i in ${ips//,/ } ; do
258                     ns="${ns}${ns:+ }${t}:${i}"
259                 done
260                 ;;
261             *-*)
262                 local i
263                 for i in $(seq ${ips/-/ }) ; do
264                     ns="${ns}${ns:+ }${t}:${i}"
265                 done
266                 ;;
267             *)
268                 ns="${ns}${ns:+ }${n}"
269         esac
270     done
271     NODES="$ns"
272
273     # Apply nodes hacks.  Some of this is about backward compatibility
274     # but the hacks also fill in the node names and whether they're
275     # part of the CTDB cluster.  The order is the order that
276     # configuration modules register their hacks.
277     run_hooks hack_nodes_functions
278
279     if [ -n "$NUMNODES" ] ; then
280         # Attempt to respect NUMNODES.  Reduce the number of CTDB
281         # nodes to NUMNODES.
282         local numnodes=$NUMNODES
283
284         hack_filter ()
285         {
286             if [ "$ctdb_node" = 1 ] ; then
287                 if [ $numnodes -gt 0 ] ; then
288                     numnodes=$(($numnodes - 1))
289                 else
290                     node_type="null"
291                     ctdb_node=0
292                 fi
293             fi
294         }
295
296         hack_all_nodes_with hack_filter
297                         
298         [ $numnodes -gt 0 ] && \
299             die "Can't not use NUMNODES to increase the number of nodes over that specified by NODES.  You need to set NODES instead - please read the documentation."
300     fi
301     
302     # Check IP addresses for duplicates.
303     local ip_offsets=":"
304     # This function doesn't modify anything...
305     get_ip_offset ()
306     {
307         [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
308             die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
309         ip_offsets="${ip_offsets}${ip_offset}:"
310     }
311     hack_all_nodes_with get_ip_offset
312 }
313
314 ##############################
315
316 sanity_check_cluster_name ()
317 {
318     [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
319         die "Cluster names should be restricted to the characters A-Za-z0-9.  \
320 Some cluster filesystems have problems with other characters."
321 }
322
323 hosts_file=
324
325 common_nodelist_hacking ()
326 {
327     # Rework the NODES list
328     expand_nodes
329
330     # Build /etc/hosts and hack the names of the ctdb nodes
331     hosts_line_hack_name ()
332     {
333         # Ignore nodes without names (e.g. "null")
334         [ "$node_type" != "null" -a -n "$name" ] || return 0
335
336         local sname=""
337         local hosts_line
338         local ip_addr="$IPBASE.0.$(($FIRSTIP + $ip_offset))"
339         
340         if [ "$ctdb_node" = 1 ] ; then
341             num_ctdb_nodes=$(($num_ctdb_nodes + 1))
342             sname="${CLUSTER}n${num_ctdb_nodes}"
343             hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
344             name="$sname"
345         else
346             hosts_line="$ip_addr ${name}.${ld} $name"
347         fi
348
349         # This allows you to add a function to your configuration file
350         # to modify hostnames (and other aspects of nodes).  This
351         # function can access/modify $name (the existing name),
352         # $node_type and $ctdb_node (1, if the node is a member of the
353         # CTDB cluster, 0 otherwise).
354         if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
355             local old_name="$name"
356             $HOSTNAME_HACKING_FUNCTION
357             if [ "$name" != "$old_name" ] ; then
358                 hosts_line="$ip_addr ${name}.${ld} $name"
359             fi
360         fi
361
362         echo "$hosts_line"
363     }
364     hosts_file="tmp/hosts.$CLUSTER"
365     {
366         local num_ctdb_nodes=0
367         local ld=$(echo $DOMAIN | tr A-Z a-z)
368         echo "# autocluster $CLUSTER"
369         hack_all_nodes_with hosts_line_hack_name
370         echo
371     } >$hosts_file
372
373     # Build /etc/ctdb/nodes
374     ctdb_nodes_line ()
375     {
376         [ "$ctdb_node" = 1 ] || return 0
377         echo "$IPBASE.0.$(($FIRSTIP + $ip_offset))"
378         num_nodes=$(($num_nodes + 1))
379     }
380     nodes_file="tmp/nodes.$CLUSTER"
381     local num_nodes=0
382     hack_all_nodes_with ctdb_nodes_line >$nodes_file
383     : "${NUMNODES:=${num_nodes}}"  # Set $NUMNODES if necessary
384
385     # Build UUID map
386     uuid_map="tmp/uuid_map.$CLUSTER"
387     uuid_map_line ()
388     {
389         echo "${ip_offset} $(uuidgen) ${node_type}"
390     }
391     hack_all_nodes_with uuid_map_line >$uuid_map
392 }
393
394 create_cluster_hooks=
395 cluster_created_hooks=
396
397 create_cluster ()
398 {
399     CLUSTER="$1"
400
401     sanity_check_cluster_name
402
403     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
404
405     # Run hooks before doing anything else.
406     run_hooks create_cluster_hooks
407
408     common_nodelist_hacking
409
410     for_each_node call_func create_node
411
412     echo "Cluster $CLUSTER created"
413     echo "You may want to add this to your /etc/hosts file:"
414     cat $hosts_file
415
416     run_hooks cluster_created_hooks
417 }
418
419 create_one_node ()
420 {
421     CLUSTER="$1"
422     local single_node_ip_offset="$2"
423
424     sanity_check_cluster_name
425
426     mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
427
428     common_nodelist_hacking
429
430     for n in $NODES ; do
431         set -- $(IFS=: ; echo $n)
432         [ $single_node_ip_offset -eq $2 ] || continue
433         call_func create_node "$@"
434         
435         echo "Requested node created"
436         echo "You may want to update your /etc/hosts file:"
437         cat $hosts_file
438         
439         break
440     done
441 }
442
443 ###############################
444 # test the proxy setup
445 test_proxy() {
446     export http_proxy=$WEBPROXY
447     wget -O /dev/null $INSTALL_SERVER || \
448         die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
449     echo "Proxy OK"
450 }
451
452 ###################
453
454 kickstart_floppy_create_hooks=
455
456 # create base image
457 create_base() {
458
459     NAME="$BASENAME"
460     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
461
462     mkdir -p $KVMLOG
463
464     echo "Testing WEBPROXY $WEBPROXY"
465     test_proxy
466
467     echo "Creating the disk"
468     qemu-img create -f $BASE_FORMAT "$DISK" $DISKSIZE
469
470     rm -rf tmp
471     mkdir -p mnt tmp tmp/ISO
472
473     setup_timezone
474
475     echo "Creating kickstart file from template"
476     substitute_vars "$KICKSTART" "tmp/ks.cfg"
477
478     if [ $INSTALLKEY = "--skip" ]; then
479         cat <<EOF
480 --------------------------------------------------------------------------------------
481 WARNING: You have not entered an install key. Some RHEL packages will not be installed.
482
483 Please enter a valid RHEL install key in your config file like this:
484
485   INSTALLKEY="1234-5678-0123-4567"
486
487 The install will continue without an install key in 5 seconds
488 --------------------------------------------------------------------------------------
489 EOF
490         sleep 5
491     fi
492
493     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
494     case "$ISO" in
495         (/*) : ;;
496         (*) ISO="${ISO_DIR}/${ISO}"
497     esac
498     
499     echo "Creating kickstart floppy"
500     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
501     mkdosfs tmp/floppy.img
502     mount -o loop -t msdos tmp/floppy.img mnt
503     cp tmp/ks.cfg mnt
504     mount -o loop,ro $ISO tmp/ISO
505     
506     echo "Setting up bootloader"
507     cp tmp/ISO/isolinux/isolinux.bin tmp
508     cp tmp/ISO/isolinux/vmlinuz tmp
509     cp tmp/ISO/isolinux/initrd.img tmp
510
511     run_hooks kickstart_floppy_create_hooks
512
513     umount tmp/ISO
514     umount mnt
515
516     UUID=`uuidgen`
517
518     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
519
520     rm -f $KVMLOG/serial.$NAME
521
522     # boot the install CD
523     $VIRSH create tmp/$NAME.xml
524
525     echo "Waiting for install to start"
526     sleep 2
527     
528     # wait for the install to finish
529     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
530         $VIRSH destroy $NAME
531         die "Failed to create base image $DISK"
532     fi
533     
534     $VIRSH destroy $NAME
535
536     ls -l $DISK
537     cat <<EOF
538
539 Install finished, base image $DISK created
540
541 You may wish to run
542    chattr +i $DISK
543 To ensure that this image does not change
544
545 Note that the root password has been set to $ROOTPASSWORD
546
547 EOF
548 }
549
550 ###############################
551 # boot the base disk
552 boot_base() {
553     CLUSTER="$1"
554
555     NAME="$BASENAME"
556     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
557
558     rm -rf tmp
559     mkdir -p tmp
560
561     IPNUM=$FIRSTIP
562     CLUSTER="base"
563
564     mount_disk $DISK
565     setup_base
566     unmount_disk
567
568     UUID=`uuidgen`
569     
570     echo "Creating $NAME.xml"
571     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
572     
573     # boot the base system
574     $VIRSH create tmp/$NAME.xml
575 }
576
577 ######################################################################
578
579 # various functions...
580
581 # Set some MAC address variables based on a hash of the cluster name
582 # plus the node number and each adapter number.
583 set_macaddrs () {
584     local cname="$1"
585     local ip_offset="$2"
586
587     local md5=$(echo $cname | md5sum)
588     local nh=$(printf "%02x" $ip_offset)
589     local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
590
591     MAC1="${mac_prefix}01"
592     MAC2="${mac_prefix}02"
593     MAC3="${mac_prefix}03"
594     MAC4="${mac_prefix}04"
595     MAC5="${mac_prefix}05"
596     MAC6="${mac_prefix}06"
597 }
598
599 # mount a qemu image via nbd
600 connect_nbd() {    
601     echo "Connecting nbd to $1"
602     mkdir -p mnt
603     modprobe nbd
604     killall -9 -q $QEMU_NBD || true
605     $QEMU_NBD -p 1300 $1 &
606     sleep 1
607     [ -r $NBD_DEVICE ] || {
608         mknod $NBD_DEVICE b 43 0
609     }
610     umount mnt 2> /dev/null || true
611     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
612     killall -9 -q nbd-client || true
613     nbd-client localhost 1300 $NBD_DEVICE > /dev/null 2>&1 || true &
614     sleep 1
615 }
616
617 # disconnect nbd
618 disconnect_nbd() {
619     echo "Disconnecting nbd"
620     sync; sync
621     nbd-client -d $NBD_DEVICE > /dev/null 2>&1 || true
622     killall -9 -q nbd-client || true
623     killall -q $QEMU_NBD || true
624 }
625
626 setup_image ()
627 {
628     local disk="$1"
629
630     case "$SYSTEM_DISK_FORMAT" in
631         qcow2)
632             connect_nbd "$disk"
633             device=$NBD_DEVICE
634             extra_mount_options=""
635             ;;
636         raw)
637             device="$disk"
638             extra_mount_options=",loop"
639             ;;
640         *)
641             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
642     esac
643 }
644
645 cleanup_image ()
646 {
647     case "$SYSTEM_DISK_FORMAT" in
648         qcow2)
649             disconnect_nbd
650             ;;
651         raw)
652             :
653             ;;
654         *)
655             die "Error: unknown SYSTEM_DISK_FORMAT=${SYSTEM_DISK_FORMAT}."
656     esac
657 }
658
659 # mount a qemu image via nbd
660 mount_disk()
661 {
662     local disk="$1"
663
664     local device extra_mount_options
665
666     setup_image "$disk"
667
668     echo "Mounting disk ${disk}..."
669     local m o
670     for m in $SYSTEM_DISK_MOUNTS ; do
671         local mount_ok=0
672         o="${m#*:}" # Offset is after colon
673         m="${m%:*}" # Mountpoint is before colon
674         echo " mount ${m} from offset ${o}"
675         local i
676         for i in $(seq 1 5); do
677             mount -o offset=${o}${extra_mount_options} $device "mnt${m}" && {
678                 mount_ok=1
679                 break
680             }
681             umount mnt 2>/dev/null || true
682             sleep 1
683         done
684         [ $mount_ok = 1 ] || die "Failed to mount $disk"
685     done
686
687     [ -d mnt/root ] || {
688         echo "Mounted directory does not look like a root filesystem"
689         ls -latr mnt
690         exit 1
691     }
692 }
693
694 # unmount a qemu image
695 unmount_disk() {
696     echo "Unmounting disk"
697     sync; sync;
698
699     # umounts are done in reverse.  Be lazy and construct a reverse
700     # list, since the shell will handle any strange whitespace for
701     # us...  ;-)
702     local umounts=""
703     local m
704     for m in $SYSTEM_DISK_MOUNTS ; do
705         umounts="${m%:*}${umounts:+ }${umounts}"
706     done
707     for m in $umounts ; do
708         echo " umount ${m}"
709         umount "mnt${m}" || umount "mnt${m}" || true
710     done
711     cleanup_image
712 }
713
714 # setup the files from $BASE_TEMPLATES/, substituting any variables
715 # based on the config
716 copy_base_dir_substitute_templates ()
717 {
718     local dir="$1"
719
720     local d="$BASE_TEMPLATES/$dir"
721     [ -d "$d" ] || return 0
722
723     local f
724     for f in $(cd "$d" && find . \! -name '*~') ; do
725         if [ -d "$d/$f" ]; then
726             mkdir -p mnt/"$f"
727         else 
728             substitute_vars "$d/$f" "mnt/$f"
729         fi
730         chmod --reference="$d/$f" "mnt/$f"
731     done
732 }
733
734 setup_base_hooks=
735
736 setup_base_ssh_keys ()
737 {
738     # this is needed as git doesn't store file permissions other
739     # than execute
740     chmod 600 mnt/etc/ssh/*key mnt/root/.ssh/*
741     chmod 700 mnt/etc/ssh mnt/root/.ssh mnt/root
742     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
743        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
744        cat "$HOME/.ssh/id_rsa.pub" >> mnt/root/.ssh/authorized_keys
745     fi
746     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
747        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
748        cat "$HOME/.ssh/id_dsa.pub" >> mnt/root/.ssh/authorized_keys
749     fi
750 }
751
752 register_hook setup_base_hooks setup_base_ssh_keys
753
754 setup_base_grub_conf ()
755 {
756     echo "Adjusting grub.conf"
757     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
758     sed -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
759         -e "s/ nodmraid//" -e "s/ nompath//"  \
760         -e "s/quiet/noapic divider=10${o:+ }${o}/g" mnt/boot/grub/grub.conf -i.org
761 }
762
763 register_hook setup_base_hooks setup_base_grub_conf
764
765 setup_base()
766 {
767     local type="$1"
768
769     umask 022
770     echo "Copy base files"
771     copy_base_dir_substitute_templates "all"
772     if [ -n "$type" ] ; then
773         copy_base_dir_substitute_templates "$type"
774     fi
775
776     run_hooks setup_base_hooks
777 }
778
779 # setup various networking components
780 setup_network()
781 {
782     # This avoids doing anything when we're called from boot_base().
783     if [ -z "$hosts_file" ] ; then
784         echo "Skipping network-related setup"
785         return
786     fi
787
788     echo "Setting up networks"
789     cat $hosts_file >>mnt/etc/hosts
790
791     echo "Setting up /etc/ctdb/nodes"
792     mkdir -p mnt/etc/ctdb
793     cp $nodes_file mnt/etc/ctdb/nodes
794
795     [ "$WEBPROXY" = "" ] || {
796         echo "export http_proxy=$WEBPROXY" >> mnt/etc/bashrc
797     }
798
799     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
800         echo "Enabling nfs mount of $NFSSHARE"
801         mkdir -p "mnt$NFS_MOUNTPOINT"
802         echo "$NFSSHARE $NFS_MOUNTPOINT nfs intr" >> mnt/etc/fstab
803     fi
804
805     mkdir -p mnt/etc/yum.repos.d
806     echo '@@@YUM_TEMPLATE@@@' | substitute_vars - > mnt/etc/yum.repos.d/autocluster.repo
807 }
808
809 register_hook setup_base_hooks setup_network
810
811 setup_timezone() {
812     [ -z "$TIMEZONE" ] && {
813         [ -r /etc/timezone ] && {
814             TIMEZONE=`cat /etc/timezone`
815         }
816         [ -r /etc/sysconfig/clock ] && {
817             . /etc/sysconfig/clock
818             TIMEZONE="$ZONE"
819         }
820         TIMEZONE="${TIMEZONE// /_}"
821     }
822     [ -n "$TIMEZONE" ] || \
823         die "Unable to determine TIMEZONE - please set in config"
824 }
825
826 # substite a set of variables of the form @@XX@@ for the shell
827 # variables $XX in a file.
828 #
829 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
830 # contain a filename whose contents are substituted, with variable
831 # substitution applied to those contents.  If filename starts with '|'
832 # it is a command instead - however, quoting is extremely fragile.
833 substitute_vars() {(
834         infile="${1:-/dev/null}" # if empty then default to /dev/null
835         outfile="$2" # optional
836
837         instring=$(cat $infile)
838
839         # Handle any indirects by looping until nothing changes.
840         # However, only handle 10 levels of recursion.
841         count=0
842         while : ; do
843             outstring=$(_substitute_vars "$instring" "@@@")
844             [ $? -eq 0 ] || die "Failed to expand template $infile"
845
846             [ "$instring" = "$outstring" ] && break
847
848             count=$(($count + 1))
849             [ $count -lt 10 ] || \
850                 die "Recursion too deep in $infile - only 10 levels allowed!"
851
852             instring="$outstring"
853         done
854
855         # Now regular variables.
856         outstring=$(_substitute_vars "$instring" "@@")
857         [ $? -eq 0 ] || die "Failed to expand template $infile"
858
859         if [ -n "$outfile" ] ; then
860             echo "$outstring" > "$outfile"
861         else
862             echo "$outstring"
863         fi
864 )}
865
866
867 # Delimiter @@ means to substitute contents of variable.
868 # Delimiter @@@ means to substitute contents of file named by variable.
869 # @@@ supports leading '|' in variable value, which means to excute a
870 # command.
871 _substitute_vars() {(
872         instring="$1"
873         delimiter="${2:-@@}"
874
875         # get the list of variables used in the template
876         VARS=`echo "$instring" |
877               tr -cs "A-Z0-9_$delimiter" '\012' | 
878               sort -u |
879               sed -n -e "s#^${delimiter}\(.*\)${delimiter}\\$#\1#p"`
880
881         tmp=$(mktemp)
882         for v in $VARS; do
883             # variable variables are fun .....
884             [ "${!v+x}" ] || {
885                 rm -f $tmp
886                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
887             }
888             s=${!v}
889
890             if [ "$delimiter" = "@@@" ] ; then
891                 f=${s:-/dev/null}
892                 c="${f#|}" # Is is a command, signified by a leading '|'?
893                 if [ "$c" = "$f" ] ; then
894                     # No leading '|', cat file.
895                     s=$(cat -- "$f")
896                     [ $? -eq 0 ] || {
897                         rm -f $tmp
898                         die "Could not substitute contents of file $f"
899                     }
900                 else
901                     # Leading '|', execute command.
902                     # Quoting problems here - using eval "$c" doesn't help.
903                     s=$($c)
904                     [ $? -eq 0 ] || {
905                         rm -f $tmp
906                         die "Could not execute command $c"
907                     }
908                 fi
909             fi
910
911             # escape some pesky chars
912             s=${s//
913 /\\n}
914             s=${s//#/\\#}
915             s=${s//&/\\&}
916             echo "s#${delimiter}${v}${delimiter}#${s}#g"
917         done > $tmp
918
919         echo "$instring" | sed -f $tmp
920
921         rm -f $tmp
922 )}
923
924 check_command() {
925     which $1 > /dev/null || die "Please install $1 to continue"
926 }
927
928 # Set a variable if it isn't already set.  This allows environment
929 # variables to override default config settings.
930 defconf() {
931     local v="$1"
932     local e="$2"
933
934     [ "${!v+x}" ] || eval "$v=\"$e\""
935 }
936
937 load_config () {
938     local i
939
940     for i in "${installdir}/config.d/"*.defconf ; do
941         . "$i"
942     done
943 }
944
945 # Print the list of config variables defined in config.d/.
946 get_config_options () {( # sub-shell for local declaration of defconf()
947         local options=
948         defconf() { options="$options $1" ; }
949         load_config
950         echo $options
951 )}
952
953 # Produce a list of long options, suitable for use with getopt, that
954 # represent the config variables defined in config.d/.
955 getopt_config_options () {
956     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
957     echo "${x// /:,}:"
958 }
959
960 # Unconditionally set the config variable associated with the given
961 # long option.
962 setconf_longopt () {
963     local longopt="$1"
964     local e="$2"
965
966     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
967     # unset so defconf will set it
968     eval "unset $v"
969     defconf "$v" "$e"
970 }
971
972 # Dump all of the current config variables.
973 dump_config() {
974     local o
975     for o in $(get_config_options) ; do
976         echo "${o}=\"${!o}\""
977     done
978     exit 0
979 }
980
981 # $COLUMNS is set in interactive bash shells.  It probably isn't set
982 # in this shell, so let's set it if it isn't.
983 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
984 : ${COLUMNS:=80}
985 export COLUMNS
986
987 # Print text assuming it starts after other text in $startcol and
988 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
989 # Long "words" will extend past $COLUMNS - 2.
990 fill_text() {
991     local startcol="$1"
992     local text="$2"
993
994     local width=$(($COLUMNS - 2 - $startcol))
995     [ $width -lt 0 ] && width=$((78 - $startcol))
996
997     local out=""
998
999     local padding
1000     if [ $startcol -gt 0 ] ; then
1001         padding=$(printf "\n%${startcol}s" " ")
1002     else
1003         padding="
1004 "
1005     fi
1006
1007     while [ -n "$text" ] ; do
1008         local orig="$text"
1009
1010         # If we already have output then arrange padding on the next line.
1011         [ -n "$out" ] && out="${out}${padding}"
1012
1013         # Break the text at $width.
1014         out="${out}${text:0:${width}}"
1015         text="${text:${width}}"
1016
1017         # If we have left over text then the line break may be ugly,
1018         # so let's check and try to break it on a space.
1019         if [ -n "$text" ] ; then
1020             # The 'x's stop us producing a special character like '(',
1021             # ')' or '!'.  Yuck - there must be a better way.
1022             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1023                 # We didn't break on a space.  Arrange for the
1024                 # beginning of the broken "word" to appear on the next
1025                 # line but not if it will make us loop infinitely.
1026                 if [ "${orig}" != "${out##* }${text}" ] ; then
1027                     text="${out##* }${text}"
1028                     out="${out% *}"
1029                 else
1030                     # Hmmm, doing that would make us loop, so add the
1031                     # rest of the word from the remainder of the text
1032                     # to this line and let it extend past $COLUMNS - 2.
1033                     out="${out}${text%% *}"
1034                     if [ "${text# *}" != "$text" ] ; then
1035                         # Remember the text after the next space for next time.
1036                         text="${text# *}"
1037                     else
1038                         # No text after next space.
1039                         text=""
1040                     fi
1041                 fi
1042             else
1043                 # We broke on a space.  If it will be at the beginning
1044                 # of the next line then remove it.
1045                 text="${text# }"
1046             fi
1047         fi
1048     done
1049
1050     echo "$out"
1051 }
1052
1053 # Display usage text, trying these approaches in order.
1054 # 1. See if it all fits on one line before $COLUMNS - 2.
1055 # 2. See if splitting before the default value and indenting it
1056 #    to $startcol means that nothing passes $COLUMNS - 2.
1057 # 3. Treat the message and default value as a string and just us fill_text()
1058 #    to format it. 
1059 usage_display_text () {
1060     local startcol="$1"
1061     local desc="$2"
1062     local default="$3"
1063     
1064     local width=$(($COLUMNS - 2 - $startcol))
1065     [ $width -lt 0 ] && width=$((78 - $startcol))
1066
1067     default="(default \"$default\")"
1068
1069     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1070         echo "${desc} ${default}"
1071     else
1072         local padding=$(printf "%${startcol}s" " ")
1073
1074         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1075             echo "$desc"
1076             echo "${padding}${default}"
1077         else
1078             fill_text $startcol "${desc} ${default}"
1079         fi
1080     fi
1081 }
1082
1083 # Display usage information for long config options.
1084 usage_smart_display () {( # sub-shell for local declaration of defconf()
1085         local startcol=33
1086
1087         defconf() {
1088             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1089
1090             printf "     --%-25s " "${longopt}=${3}"
1091
1092             usage_display_text $startcol "$4" "$2"
1093         }
1094
1095         "$@"
1096 )}
1097
1098
1099 # Display usage information for long config options.
1100 usage_config_options (){
1101     usage_smart_display load_config
1102 }
1103
1104 list_releases () {
1105     local releases=$(cd $installdir/releases && echo *.release)
1106     releases="${releases//.release}"
1107     releases="${releases// /\", \"}"
1108     echo "\"$releases\""
1109 }
1110
1111 with_release () {
1112     local release="$1"
1113     shift # subsequent args are passed to release file
1114
1115     # This simply loads an extra config file from $installdir/releases
1116     f="${installdir}/releases/${release}.release"
1117     if [ -r "$f" ] ; then
1118         . "$f"
1119     else
1120         f="${installdir}/releases/${release%%-*}.release"
1121         if [ -r "$f" ] ; then
1122             . "$f" "${release#*-}"
1123         else
1124             echo "Unknown release \"${release}\" specified to --with-release"
1125             printf "%-25s" "Supported releases are: "
1126             fill_text 25 "$(list_releases)"
1127             exit 1
1128         fi
1129     fi
1130
1131 }
1132
1133 has_public_addresses_DEFAULT ()
1134 {
1135     false
1136 }
1137
1138 # Build public address configuration.
1139 # * 1st public IP:  unless specified, last octet is $FIRSTIP + $PUBLIC_IP_OFFSET
1140 # * Excluded nodes: unless specified via comma-separated list of IP offsets,
1141 #                   nodes are excluded via their node types
1142 # * Number of public addresses per interface is either specified or $NUMNODES.
1143 make_public_addresses () {
1144     local firstip="${1:-$(($FIRSTIP + $PUBLIC_IP_OFFSET))}"
1145     local excluded_nodes="$2" 
1146     local num_addrs="${3:-${NUMNODES}}"
1147
1148     # For delimiting matches.
1149     excluded_nodes="${excluded_nodes:+,}${excluded_nodes}${excluded_nodes:+,}"
1150     # Avoid spaces
1151     excluded_nodes="${excluded_nodes// /}"
1152
1153     make_public_addresses_for_node ()
1154     {
1155         [ "$ctdb_node" = 1 ] || return 0
1156
1157         echo "[/etc/ctdb/public_addresses:${name}.${DOMAIN}]"
1158
1159         if [ -n "$excluded_nodes" -a \
1160             "${excluded_nodes/,${ip_offset},}" = "$excluded_nodes" ] ||
1161             ([ -z "$excluded_nodes" ] &&
1162                 call_func has_public_addresses "$node_type") ; then
1163
1164             local e i
1165             for e in "1" "2" ; do
1166                 for i in $(seq $firstip $(($firstip + $num_addrs - 1))) ; do
1167                     if [ $i -gt 254 ] ; then
1168                         die "make_public_addresses: octet > 254 - consider setting PUBLIC_IP_OFFSET"
1169                     fi
1170                     printf "\t${IPBASE}.${e}.${i}/24 eth${e}\n"
1171                 done
1172             done            
1173         fi
1174         echo 
1175     }
1176     hack_all_nodes_with make_public_addresses_for_node
1177 }
1178
1179 ######################################################################
1180
1181 load_config
1182
1183 ############################
1184 # parse command line options
1185 long_opts=$(getopt_config_options)
1186 getopt_output=$(getopt -n autocluster -o "c:e:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1187 [ $? != 0 ] && usage
1188
1189 use_default_config=true
1190
1191 # We do 2 passes of the options.  The first time we just handle usage
1192 # and check whether -c is being used.
1193 eval set -- "$getopt_output"
1194 while true ; do
1195     case "$1" in
1196         -c) shift 2 ; use_default_config=false ;;
1197         -e) shift 2 ;;
1198         --) shift ; break ;;
1199         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1200         --dump|-x) shift ;;
1201         -h|--help) usage ;; # Usage should be shown here for real defaults.
1202         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1203         *) usage ;; # shouldn't happen, so this is reasonable.
1204     esac
1205 done
1206
1207 config="./config"
1208 $use_default_config && [ -r "$config" ] && . "$config"
1209
1210 eval set -- "$getopt_output"
1211
1212 while true ; do
1213     case "$1" in
1214         # force at least ./local_file to avoid accidental file from $PATH
1215         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1216         -e) eval "$2" ; exit ;;
1217         --with-release)
1218             with_release "$2"
1219             shift 2
1220             ;;
1221         -x) set -x; shift ;;
1222         --dump) dump_config ;;
1223         --) shift ; break ;;
1224         -h|--help) usage ;; # Redundant.
1225         --*)
1226             # Putting --opt1|opt2|... into a variable and having case
1227             # match against it as a pattern doesn't work.  The | is
1228             # part of shell syntax, so we need to do this.  Look away
1229             # now to stop your eyes from bleeding! :-)
1230             x=",${long_opts}" # Now each option is surrounded by , and :
1231             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1232                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1233                 setconf_longopt "$1" "$2"; shift 2
1234             else
1235                 usage
1236             fi
1237             ;;
1238         *) usage ;; # shouldn't happen, so this is reasonable.
1239     esac
1240 done
1241
1242 # catch errors
1243 set -e
1244 set -E
1245 trap 'es=$?; 
1246       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1247       exit $es' ERR
1248
1249 # check for needed programs 
1250 check_command expect
1251 if [ "$SYSTEM_DISK_FORMAT" != "raw" ] ; then
1252     check_command $QEMU_NBD
1253     check_command nbd-client
1254 fi
1255
1256 [ $# -lt 1 ] && usage
1257
1258 command="$1"
1259 shift
1260
1261 case $command in
1262     create)
1263         type=$1
1264         shift
1265         case $type in
1266             base)
1267                 [ $# != 0 ] && usage
1268                 create_base
1269                 ;;
1270             cluster)
1271                 [ $# != 1 ] && usage
1272                 create_cluster "$1"
1273                 ;;
1274             node)
1275                 [ $# != 2 ] && usage
1276                 create_one_node "$1" "$2"
1277                 ;;
1278             *)
1279                 usage;
1280                 ;;
1281         esac
1282         ;;
1283     mount)
1284         [ $# != 1 ] && usage
1285         mount_disk "$1"
1286         ;;
1287     unmount)
1288         [ $# != 0 ] && usage
1289         unmount_disk
1290         ;;
1291     bootbase)
1292         boot_base;
1293         ;;
1294     testproxy)
1295         test_proxy;
1296         ;;
1297     *)
1298         usage;
1299         ;;
1300 esac