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