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