2 # main autocluster script
4 # Copyright (C) Andrew Tridgell 2008
5 # Copyright (C) Martin Schwenke 2008
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.
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.
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/>.
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. :-)
26 autocluster=$(which "$0")
28 if [ -L "$autocluster" ] ; then
29 autocluster=$(readlink "$autocluster")
31 installdir=$(dirname "$autocluster")
32 ##END-INSTALLDIR-MAGIC##
39 Usage: autocluster [OPTION] ... <COMMAND>
41 -c <file> specify config file (default is "config")
42 -e <expr> execute <expr> and exit
43 -E <expr> execute <expr> and continue
44 -x enable script debugging
45 --dump dump config settings and exit
47 configuration options:
55 base [ create | boot ] ...
57 cluster [ build | destroy | create | update_hosts | boot | configure ] ...
62 create cluster [ CLUSTERNAME ]
65 create node CLUSTERNAME IP_OFFSET
66 (re)create a single cluster node
69 mount a qemu disk on mnt/
72 unmount a qemu disk from mnt/
80 ###############################
83 if [ "$no_sanity" = 1 ] ; then
84 fill_text 0 "WARNING: $*" >&2
86 fill_text 0 "ERROR: $*" >&2
93 echo "######################################################################"
94 printf "# %-66s #\n" "$*"
95 echo "######################################################################"
105 local tmpfile=$(mktemp)
107 cat <<EOF >"$tmpfile"
108 spawn tail -n 10000 -f $file
109 expect -timeout $timeout -re "$msg"
116 if ! grep -E "$msg" "$file" > /dev/null; then
117 echo "Failed to find \"$msg\" in \"$file\""
124 ###############################
126 # Indirectly call a function named by ${1}_${2}
128 local func="$1" ; shift
129 local type="$1" ; shift
131 local f="${func}_${type}"
132 if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
136 if type -t "$f" >/dev/null && ! type -P "$f" >/dev/null ; then
139 die "No function defined for \"${func}\" \"${type}\""
144 # Note that this will work if you pass "call_func f" because the first
145 # element of the node tuple is the node type. Nice... :-)
150 "$@" $(IFS=: ; echo $n)
154 hack_one_node_with ()
156 local filter="$1" ; shift
165 local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
166 nodes="${nodes}${nodes:+ }${item}"
169 # This also gets used for non-filtering iteration.
170 hack_all_nodes_with ()
175 for_each_node hack_one_node_with "$filter"
184 eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
193 for i in ${!hook_var} ; do
198 # Use with care, since this may clear some autocluster defaults.!
203 eval "$hook_var=\"\""
206 ##############################
208 # These hooks are intended to customise the value of $DISK. They have
209 # access to 1 argument ("base", "system", "shared") and the variables
210 # $VIRTBASE, $CLUSTER, $BASENAME (for "base"), $NAME (for "system"),
211 # $SHARED_DISK_NUM (for "shared"). A hook must be deterministic and
212 # should not be stateful, since they can be called multiple times for
216 # common node creation stuff
217 create_node_COMMON ()
222 local template_file="${4:-$NODE_TEMPLATE}"
224 if [ "$SYSTEM_DISK_FORMAT" != "qcow2" -a "$BASE_FORMAT" = "qcow2" ] ; then
225 die "Error: if BASE_FORMAT is \"qcow2\" then SYSTEM_DISK_FORMAT must also be \"qcow2\"."
228 local IPNUM=$(($FIRSTIP + $ip_offset))
231 # Determine base image name. We use $DISK temporarily to allow
232 # the path to be hacked.
233 local DISK="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
234 if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
235 DISK="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
237 run_hooks hack_disk_hooks "base"
238 local base_disk="$DISK"
240 # Determine the system disk image name.
241 DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
242 run_hooks hack_disk_hooks "system"
245 if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
246 di=$(readlink "$DISK")
249 local di_dirname="${di%/*}"
250 mkdir -p "$di_dirname"
252 case "$SYSTEM_DISK_FORMAT" in
254 echo "Creating the disk..."
255 qemu-img create -b "$base_disk" -f qcow2 "$di"
256 create_node_configure_image "$DISK" "$type"
259 echo "Creating the disk..."
260 cp -v --sparse=always "$base_disk" "$di"
261 create_node_configure_image "$DISK" "$type"
264 echo "Creating the disk..."
265 cp -v --reflink=always "$base_disk" "$di"
266 create_node_configure_image "$DISK" "$type"
269 echo "Creating the disk (using mmclone)..."
270 local base_snap="${base_disk}.snap"
271 [ -f "$base_snap" ] || mmclone snap "$base_disk" "$base_snap"
272 mmclone copy "$base_snap" "$di"
273 create_node_configure_image "$DISK" "$type"
276 echo "Skipping disk image creation as requested"
279 die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
282 # Pull the UUID for this node out of the map.
283 UUID=$(awk "\$1 == $ip_offset {print \$2}" $uuid_map)
287 echo "Creating $NAME.xml"
288 substitute_vars $template_file tmp/$NAME.xml
290 # install the XML file
291 $VIRSH undefine $NAME > /dev/null 2>&1 || true
292 $VIRSH define tmp/$NAME.xml
295 create_node_configure_image ()
300 diskimage mount "$disk"
305 # Provides an easy way of removing nodes from $NODE.
306 create_node_null () {
310 hack_network_map_hooks=""
312 # Uses: CLUSTER, NAME, NETWORKS, FIRSTIP, ip_offset
315 network_map="tmp/network_map.$NAME"
317 if [ -n "$CLUSTER" ] ; then
318 local md5=$(echo "$CLUSTER" | md5sum)
319 local nh=$(printf "%02x" $ip_offset)
320 local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
322 local mac_prefix="02:42:42:00:00:"
327 for n in $NETWORKS ; do
328 local ch=$(printf "%02x" $count)
329 local mac="${mac_prefix}${ch}"
332 local ip_bits="$1" ; shift
333 local dev="$1" ; shift
336 local net="${ip_bits%/*}"
337 local netname="acnet_${net//./_}"
339 local ip="${net%.*}.${IPNUM}"
340 local mask="255.255.255.0"
342 # This can be used to override the variables in the echo
343 # statement below. The hook can use any other variables
344 # available in this function.
345 run_hooks hack_network_map_hooks
347 echo "${netname} ${dev} ${ip} ${mask} ${mac} ${opts}"
348 count=$(($count + 1))
352 ##############################
354 hack_nodes_functions=
357 # Expand out any abbreviations in NODES.
366 for i in ${ips//,/ } ; do
367 ns="${ns}${ns:+ }${t}:${i}"
372 for i in $(seq ${ips/-/ }) ; do
373 ns="${ns}${ns:+ }${t}:${i}"
377 ns="${ns}${ns:+ }${n}"
382 # Apply nodes hacks. Some of this is about backward compatibility
383 # but the hacks also fill in the node names and whether they're
384 # part of the CTDB cluster. The order is the order that
385 # configuration modules register their hacks.
386 run_hooks hack_nodes_functions
388 if [ -n "$NUMNODES" ] ; then
389 # Attempt to respect NUMNODES. Reduce the number of CTDB
391 local numnodes=$NUMNODES
395 if [ "$ctdb_node" = 1 ] ; then
396 if [ $numnodes -gt 0 ] ; then
397 numnodes=$(($numnodes - 1))
405 hack_all_nodes_with hack_filter
407 [ $numnodes -gt 0 ] && \
408 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."
411 # Check IP addresses for duplicates.
413 # This function doesn't modify anything...
416 [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
417 die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
418 ip_offsets="${ip_offsets}${ip_offset}:"
420 hack_all_nodes_with get_ip_offset
423 ##############################
425 sanity_check_cluster_name ()
427 [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
428 die "Cluster names should be restricted to the characters A-Za-z0-9. \
429 Some cluster filesystems have problems with other characters."
434 common_nodelist_hacking ()
436 # Rework the NODES list
439 # Build /etc/hosts and hack the names of the ctdb nodes
440 hosts_line_hack_name ()
442 # Ignore nodes without names (e.g. "null")
443 [ "$node_type" != "null" -a -n "$name" ] || return 0
447 local ip_addr="${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
449 if [ "$ctdb_node" = 1 ] ; then
450 num_ctdb_nodes=$(($num_ctdb_nodes + 1))
451 sname="${CLUSTER}n${num_ctdb_nodes}"
452 hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
455 hosts_line="$ip_addr ${name}.${ld} $name"
458 # This allows you to add a function to your configuration file
459 # to modify hostnames (and other aspects of nodes). This
460 # function can access/modify $name (the existing name),
461 # $node_type and $ctdb_node (1, if the node is a member of the
462 # CTDB cluster, 0 otherwise).
463 if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
464 local old_name="$name"
465 $HOSTNAME_HACKING_FUNCTION
466 if [ "$name" != "$old_name" ] ; then
467 hosts_line="$ip_addr ${name}.${ld} $name"
473 hosts_file="tmp/hosts.$CLUSTER"
475 local num_ctdb_nodes=0
476 local ld=$(echo $DOMAIN | tr A-Z a-z)
477 echo "# autocluster $CLUSTER"
478 hack_all_nodes_with hosts_line_hack_name
482 # Build /etc/ctdb/nodes
485 [ "$ctdb_node" = 1 ] || return 0
486 echo "${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
487 num_nodes=$(($num_nodes + 1))
489 nodes_file="tmp/nodes.$CLUSTER"
491 hack_all_nodes_with ctdb_nodes_line >$nodes_file
492 : "${NUMNODES:=${num_nodes}}" # Set $NUMNODES if necessary
495 uuid_map="tmp/uuid_map.$CLUSTER"
498 echo "${ip_offset} $(uuidgen) ${node_type}"
500 hack_all_nodes_with uuid_map_line >$uuid_map
503 create_cluster_hooks=
504 cluster_created_hooks=
508 # Use $1. If not set then use value from configuration file.
509 CLUSTER="${1:-${CLUSTER}}"
510 announce "cluster create \"${CLUSTER}\""
511 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
513 sanity_check_cluster_name
515 mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
517 # Run hooks before doing anything else.
518 run_hooks create_cluster_hooks
520 common_nodelist_hacking
522 for_each_node call_func create_node
524 echo "Cluster $CLUSTER created"
527 run_hooks cluster_created_hooks
530 cluster_created_hosts_message ()
532 echo "You may want to add this to your /etc/hosts file:"
536 register_hook cluster_created_hooks cluster_created_hosts_message
540 announce "cluster destroy \"${CLUSTER}\""
541 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
543 vircmd destroy "$CLUSTER" || true
546 cluster_update_hosts ()
548 announce "cluster update_hosts \"${CLUSTER}\""
549 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
551 [ -n "$hosts_file" ] || hosts_file="tmp/hosts.${CLUSTER}"
552 [ -r "$hosts_file" ] || die "Missing hosts file \"${hosts_file}\""
554 local pat="# autocluster ${CLUSTER}\$|[[:space:]]${CLUSTER}(n|base)[[:digit:]]+"
556 local t="/etc/hosts.${CLUSTER}"
557 grep -E "$pat" /etc/hosts >"$t" || true
558 if diff -B "$t" "$hosts_file" >/dev/null ; then
563 local old=/etc/hosts.old.autocluster
565 local new=/etc/hosts.new
566 grep -Ev "$pat" "$old" |
567 cat -s - "$hosts_file" >"$new"
571 echo "Made these changes to /etc/hosts:"
572 diff -u "$old" /etc/hosts || true
577 [ -n "$CLUSTER_PATTERN" ] || CLUSTER_PATTERN="$CLUSTER"
578 announce "cluster boot \"${CLUSTER_PATTERN}\""
579 [ -n "$CLUSTER_PATTERN" ] || die "\$CLUSTER_PATTERN not set"
581 vircmd start "$CLUSTER_PATTERN"
583 local nodes=$(vircmd dominfo "$CLUSTER_PATTERN" 2>/dev/null | \
584 sed -n -e 's/Name: *//p')
589 waitfor "${KVMLOG}/serial.$i" "login:" 300 || {
590 vircmd destroy "$CLUSTER_PATTERN"
591 die "Failed to create cluster"
595 # Move past the last line of log output
601 announce "cluster configure \"${CLUSTER}\""
602 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
604 local n1="${CLUSTER}n1"
605 local ssh="ssh -o StrictHostKeyChecking=no"
607 case "$CLUSTER_TYPE" in
609 $ssh "$n1" ./scripts/install_packages.sh clusterfs build
610 $ssh "$n1" ./scripts/setup_cluster.sh build
614 $ssh "$n1" ./scripts/install_packages.sh ad_server
615 $ssh "$n1" ./scripts/configure_cluster.sh ad_server
619 [ -n "$CLUSTER_PATTERN" ] || CLUSTER_PATTERN="$CLUSTER"
621 local nodes=$(vircmd dominfo "$CLUSTER_PATTERN" 2>/dev/null | \
622 sed -n -e 's/Name: *//p')
625 $ssh "$i" ./scripts/install_packages.sh clusterfs nas
628 $ssh "$n1" ./scripts/setup_cluster.sh clusterfs nas
636 local single_node_ip_offset="$2"
638 sanity_check_cluster_name
640 mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
642 common_nodelist_hacking
645 set -- $(IFS=: ; echo $n)
646 [ $single_node_ip_offset -eq $2 ] || continue
647 call_func create_node "$@"
649 echo "Requested node created"
651 echo "You may want to update your /etc/hosts file:"
658 ###############################
659 # test the proxy setup
661 export http_proxy=$WEBPROXY
662 wget -O /dev/null $INSTALL_SERVER || \
663 die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
669 kickstart_floppy_create_hooks=
671 guess_install_network ()
673 # Figure out IP address to use during base install. Default to
674 # the IP address of the 1st (private) network. If a gateway is
675 # specified then use the IP address associated with it.
678 local netname dev ip mask mac opts
679 while read netname dev ip mask mac opts; do
684 INSTALL_GW="${o#gw=}"
685 INSTALL_IP="${ip}${FIRSTIP}"
688 [ -n "$INSTALL_IP" ] || INSTALL_IP="$ip"
695 local NAME="$BASENAME"
696 local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
697 run_hooks hack_disk_hooks "base"
701 echo "Testing WEBPROXY $WEBPROXY"
705 if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
706 di=$(readlink "$DISK")
709 local di_dirname="${di%/*}"
710 mkdir -p "$di_dirname"
712 echo "Creating the disk"
713 qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
716 mkdir -p mnt tmp tmp/ISO
722 guess_install_network
724 echo "Creating kickstart file from template"
725 substitute_vars "$KICKSTART" "tmp/ks.cfg"
727 # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
730 (*) ISO="${ISO_DIR}/${ISO}"
733 echo "Creating kickstart floppy"
734 dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
735 mkdosfs -n KICKSTART tmp/floppy.img
736 mount -o loop -t msdos tmp/floppy.img mnt
738 mount -o loop,ro $ISO tmp/ISO
740 echo "Setting up bootloader"
741 cp tmp/ISO/isolinux/isolinux.bin tmp
742 cp tmp/ISO/isolinux/vmlinuz tmp
743 cp tmp/ISO/isolinux/initrd.img tmp
745 run_hooks kickstart_floppy_create_hooks
752 substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
754 rm -f $KVMLOG/serial.$NAME
756 # boot the install CD
757 $VIRSH create tmp/$NAME.xml
759 echo "Waiting for install to start"
762 # wait for the install to finish
763 if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
765 die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
766 You may need to increase the value of CREATE_BASE_TIMEOUT.
767 Alternatively, the install might have completed but KS_DONE_MESSAGE
768 (currently \"${KS_DONE_MESSAGE}\")
769 may not have matched anything at the end of the kickstart output."
777 Install finished, base image $DISK created
780 chcon -t virt_content_t $DISK
782 To ensure that this image does not change
784 Note that the root password has been set to $ROOTPASSWORD
789 ###############################
796 DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
804 diskimage mount $DISK
810 echo "Creating $NAME.xml"
811 substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
813 # boot the base system
814 $VIRSH create tmp/$NAME.xml
817 ######################################################################
819 # Updating a disk image...
825 call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
828 # setup the files from $BASE_TEMPLATES/, substituting any variables
829 # based on the config
830 copy_base_dir_substitute_templates ()
834 local d="$BASE_TEMPLATES/$dir"
835 [ -d "$d" ] || return 0
838 for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
839 f="${f#./}" # remove leading "./" for clarity
840 if [ -d "$d/$f" ]; then
841 # Don't chmod existing directory
842 if diskimage is_directory "/$f" ; then
845 diskimage mkdir_p "/$f"
848 diskimage substitute_vars "$d/$f" "/$f"
850 diskimage chmod_reference "$d/$f" "/$f"
856 setup_base_ssh_keys ()
858 # this is needed as git doesn't store file permissions other
860 # Note that we protect the wildcards from the local shell.
861 diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
862 diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
863 if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
864 echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
865 diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
867 if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
868 echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
869 diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
873 register_hook setup_base_hooks setup_base_ssh_keys
875 setup_base_grub_conf ()
877 echo "Adjusting grub.conf"
878 local o="$EXTRA_KERNEL_OPTIONS" # For readability.
879 local grub_configs="/boot/grub/grub.conf"
880 if ! diskimage is_file "$grub_configs" ; then
881 grub_configs="/etc/default/grub /boot/grub2/grub.cfg"
884 for c in $grub_configs ; do
886 -e "s/console=ttyS0,19200/console=ttyS0,115200/" \
887 -e "s/ console=tty1//" -e "s/ rhgb/ norhgb/" \
888 -e "s/ nodmraid//" -e "s/ nompath//" \
889 -e "s/quiet/noapic divider=10${o:+ }${o}/g"
893 register_hook setup_base_hooks setup_base_grub_conf
900 echo "Copy base files"
901 copy_base_dir_substitute_templates "all"
902 if [ -n "$type" ] ; then
903 copy_base_dir_substitute_templates "$type"
906 run_hooks setup_base_hooks
909 # setup various networking components
912 # This avoids doing anything when we're called from boot_base().
913 if [ -z "$hosts_file" ] ; then
914 echo "Skipping network-related setup"
918 echo "Setting up networks"
919 diskimage append_text_file "$hosts_file" "/etc/hosts"
921 echo "Setting up /etc/ctdb/nodes"
922 diskimage mkdir_p "/etc/ctdb"
923 diskimage put "$nodes_file" "/etc/ctdb/nodes"
925 [ "$WEBPROXY" = "" ] || {
926 diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
929 if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
930 echo "Enabling nfs mount of $NFSSHARE"
931 diskimage mkdir_p "$NFS_MOUNTPOINT"
932 diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
935 diskimage mkdir_p "/etc/yum.repos.d"
936 echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
938 diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
940 echo "Setting up network interfaces: "
941 local netname dev ip mask mac opts
942 while read netname dev ip mask mac opts; do
955 diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
965 # This goes to 70-persistent-net.rules
967 # Generated by autocluster
968 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
971 done <"$network_map" |
972 diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
975 register_hook setup_base_hooks setup_network
978 [ -z "$TIMEZONE" ] && {
979 [ -r /etc/timezone ] && {
980 TIMEZONE=`cat /etc/timezone`
982 [ -r /etc/sysconfig/clock ] && {
983 . /etc/sysconfig/clock
986 TIMEZONE="${TIMEZONE// /_}"
988 [ -n "$TIMEZONE" ] || \
989 die "Unable to determine TIMEZONE - please set in config"
992 # substite a set of variables of the form @@XX@@ for the shell
993 # variables $XX in a file.
995 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
996 # contain a filename whose contents are substituted, with variable
997 # substitution applied to those contents. If filename starts with '|'
998 # it is a command instead - however, quoting is extremely fragile.
1000 infile="${1:-/dev/null}" # if empty then default to /dev/null
1001 outfile="$2" # optional
1004 cat "$infile" >"$tmp_out"
1006 # Handle any indirects by looping until nothing changes.
1007 # However, only handle 10 levels of recursion.
1010 if ! _substitute_vars "$tmp_out" "@@@" ; then
1012 die "Failed to expand template $infile"
1015 # No old version of file means no changes made.
1016 if [ ! -f "${tmp_out}.old" ] ; then
1020 rm -f "${tmp_out}.old"
1022 count=$(($count + 1))
1023 if [ $count -ge 10 ] ; then
1025 die "Recursion too deep in $infile - only 10 levels allowed!"
1029 # Now regular variables.
1030 if ! _substitute_vars "$tmp_out" "@@" ; then
1032 die "Failed to expand template $infile"
1034 rm -f "${tmp_out}.old"
1036 if [ -n "$outfile" ] ; then
1037 mv "$tmp_out" "$outfile"
1045 # Delimiter @@ means to substitute contents of variable.
1046 # Delimiter @@@ means to substitute contents of file named by variable.
1047 # @@@ supports leading '|' in variable value, which means to excute a
1049 _substitute_vars() {(
1051 delimiter="${2:-@@}"
1053 # Get the list of variables used in the template. The grep
1054 # gets rid of any blank lines and lines with extraneous '@'s
1055 # next to template substitutions.
1056 VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
1057 grep '^[A-Z0-9_][A-Z0-9_]*$' |
1062 # variable variables are fun .....
1065 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
1069 if [ "$delimiter" = "@@@" ] ; then
1071 c="${f#|}" # Is is a command, signified by a leading '|'?
1072 if [ "$c" = "$f" ] ; then
1073 # No leading '|', cat file.
1077 die "Could not substitute contents of file $f"
1080 # Leading '|', execute command.
1081 # Quoting problems here - using eval "$c" doesn't help.
1085 die "Could not execute command $c"
1090 # escape some pesky chars
1091 # This first one can be too slow if done using a bash
1092 # variable pattern subsitution.
1093 s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
1096 echo "s#${delimiter}${v}${delimiter}#${s}#g"
1099 # Get the in-place sed to make a backup of the old file.
1100 # Remove the backup if it is the same as the resulting file -
1101 # this acts as a flag to the caller that no changes were made.
1102 sed -i.old -f $tmp "$tmp_out"
1103 if cmp -s "${tmp_out}.old" "$tmp_out" ; then
1104 rm -f "${tmp_out}.old"
1111 which $1 > /dev/null || die "Please install $1 to continue"
1114 # Set a variable if it isn't already set. This allows environment
1115 # variables to override default config settings.
1120 [ "${!v+x}" ] || eval "$v=\"$e\""
1126 for i in "${installdir}/config.d/"*.defconf ; do
1131 # Print the list of config variables defined in config.d/.
1132 get_config_options () {( # sub-shell for local declaration of defconf()
1134 defconf() { options="$options $1" ; }
1139 # Produce a list of long options, suitable for use with getopt, that
1140 # represent the config variables defined in config.d/.
1141 getopt_config_options () {
1142 local x=$(get_config_options | tr 'A-Z_' 'a-z-')
1146 # Unconditionally set the config variable associated with the given
1148 setconf_longopt () {
1152 local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
1153 # unset so defconf will set it
1158 # Dump all of the current config variables.
1161 for o in $(get_config_options) ; do
1162 echo "${o}=\"${!o}\""
1167 # $COLUMNS is set in interactive bash shells. It probably isn't set
1168 # in this shell, so let's set it if it isn't.
1169 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1173 # Print text assuming it starts after other text in $startcol and
1174 # needs to wrap before $COLUMNS - 2. Subsequent lines start at $startcol.
1175 # Long "words" will extend past $COLUMNS - 2.
1180 local width=$(($COLUMNS - 2 - $startcol))
1181 [ $width -lt 0 ] && width=$((78 - $startcol))
1186 if [ $startcol -gt 0 ] ; then
1187 padding=$(printf "\n%${startcol}s" " ")
1193 while [ -n "$text" ] ; do
1196 # If we already have output then arrange padding on the next line.
1197 [ -n "$out" ] && out="${out}${padding}"
1199 # Break the text at $width.
1200 out="${out}${text:0:${width}}"
1201 text="${text:${width}}"
1203 # If we have left over text then the line break may be ugly,
1204 # so let's check and try to break it on a space.
1205 if [ -n "$text" ] ; then
1206 # The 'x's stop us producing a special character like '(',
1207 # ')' or '!'. Yuck - there must be a better way.
1208 if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1209 # We didn't break on a space. Arrange for the
1210 # beginning of the broken "word" to appear on the next
1211 # line but not if it will make us loop infinitely.
1212 if [ "${orig}" != "${out##* }${text}" ] ; then
1213 text="${out##* }${text}"
1216 # Hmmm, doing that would make us loop, so add the
1217 # rest of the word from the remainder of the text
1218 # to this line and let it extend past $COLUMNS - 2.
1219 out="${out}${text%% *}"
1220 if [ "${text# *}" != "$text" ] ; then
1221 # Remember the text after the next space for next time.
1224 # No text after next space.
1229 # We broke on a space. If it will be at the beginning
1230 # of the next line then remove it.
1239 # Display usage text, trying these approaches in order.
1240 # 1. See if it all fits on one line before $COLUMNS - 2.
1241 # 2. See if splitting before the default value and indenting it
1242 # to $startcol means that nothing passes $COLUMNS - 2.
1243 # 3. Treat the message and default value as a string and just us fill_text()
1245 usage_display_text () {
1250 local width=$(($COLUMNS - 2 - $startcol))
1251 [ $width -lt 0 ] && width=$((78 - $startcol))
1253 default="(default \"$default\")"
1255 if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1256 echo "${desc} ${default}"
1258 local padding=$(printf "%${startcol}s" " ")
1260 if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1262 echo "${padding}${default}"
1264 fill_text $startcol "${desc} ${default}"
1269 # Display usage information for long config options.
1270 usage_smart_display () {( # sub-shell for local declaration of defconf()
1274 local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1276 printf " --%-25s " "${longopt}=${3}"
1278 usage_display_text $startcol "$4" "$2"
1285 # Display usage information for long config options.
1286 usage_config_options (){
1287 usage_smart_display load_config
1297 actions="${actions}${actions:+ }$*"
1302 [ -n "$actions" ] || usage
1305 for a in $actions ; do
1310 ######################################################################
1314 ######################################################################
1318 ############################
1319 # parse command line options
1320 long_opts=$(getopt_config_options)
1321 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump -l "$long_opts" -- "$@")
1322 [ $? != 0 ] && usage
1324 use_default_config=true
1326 # We do 2 passes of the options. The first time we just handle usage
1327 # and check whether -c is being used.
1328 eval set -- "$getopt_output"
1331 -c) shift 2 ; use_default_config=false ;;
1334 --) shift ; break ;;
1336 -h|--help) usage ;; # Usage should be shown here for real defaults.
1337 --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1338 *) usage ;; # shouldn't happen, so this is reasonable.
1343 $use_default_config && [ -r "$config" ] && . "$config"
1345 eval set -- "$getopt_output"
1351 # force at least ./local_file to avoid accidental file
1353 . "$(dirname $2)/${b}"
1354 # If $CLUSTER is unset then try to base it on the filename
1355 if [ ! -n "$CLUSTER" ] ; then
1358 CLUSTER="${b%.autocluster}"
1363 -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1364 -E) eval "$2" ; shift 2 ;;
1365 -x) set -x; shift ;;
1366 --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1367 --) shift ; break ;;
1368 -h|--help) usage ;; # Redundant.
1370 # Putting --opt1|opt2|... into a variable and having case
1371 # match against it as a pattern doesn't work. The | is
1372 # part of shell syntax, so we need to do this. Look away
1373 # now to stop your eyes from bleeding! :-)
1374 x=",${long_opts}" # Now each option is surrounded by , and :
1375 if [ "$x" != "${x#*,${1#--}:}" ] ; then
1376 # Our option, $1, surrounded by , and : was in $x, so is legal.
1377 setconf_longopt "$1" "$2"; shift 2
1382 *) usage ;; # shouldn't happen, so this is reasonable.
1386 run_hooks post_config_hooks
1392 echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es;
1395 # check for needed programs
1396 check_command expect
1398 [ $# -lt 1 ] && usage
1408 create|boot) actions_add "base_${t}" ;;
1419 destroy|create|update_hosts|boot|configure)
1420 actions_add "cluster_${t}" ;;
1422 for t in destroy create update_hosts boot configure ; do
1423 actions_add "cluster_${t}"
1437 [ $# != 0 ] && usage
1441 [ $# != 1 ] && usage
1445 [ $# != 2 ] && usage
1446 create_one_node "$1" "$2"
1454 [ $# != 1 ] && usage
1455 diskimage mount "$1"
1458 [ $# != 0 ] && usage