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