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