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 | setup ] ...
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 node_is_ctdb_node_DEFAULT ()
159 hack_one_node_with ()
161 local filter="$1" ; shift
170 local item="${node_type}:${ip_offset}${name:+:}${name}${ctdb_node:+:}${ctdb_node}"
171 nodes="${nodes}${nodes:+ }${item}"
174 # This also gets used for non-filtering iteration.
175 hack_all_nodes_with ()
180 for_each_node hack_one_node_with "$filter"
189 eval "$hook_var=\"${!hook_var}${!hook_var:+ }${new_hook}\""
198 for i in ${!hook_var} ; do
203 # Use with care, since this may clear some autocluster defaults.!
208 eval "$hook_var=\"\""
211 ##############################
213 # These hooks are intended to customise the value of $DISK. They have
214 # access to 1 argument ("base", "system", "shared") and the variables
215 # $VIRTBASE, $CLUSTER, $BASENAME (for "base"), $NAME (for "system"),
216 # $SHARED_DISK_NUM (for "shared"). A hook must be deterministic and
217 # should not be stateful, since they can be called multiple times for
221 create_node_DEFAULT ()
228 echo "Creating node \"$name\" (of type \"${type}\")"
230 create_node_COMMON "$name" "$ip_offset" "$type"
233 # common node creation stuff
234 create_node_COMMON ()
239 local template_file="${4:-$NODE_TEMPLATE}"
241 if [ "$SYSTEM_DISK_FORMAT" != "qcow2" -a "$BASE_FORMAT" = "qcow2" ] ; then
242 die "Error: if BASE_FORMAT is \"qcow2\" then SYSTEM_DISK_FORMAT must also be \"qcow2\"."
245 local IPNUM=$(($FIRSTIP + $ip_offset))
248 # Determine base image name. We use $DISK temporarily to allow
249 # the path to be hacked.
250 local DISK="${VIRTBASE}/${BASENAME}.${BASE_FORMAT}"
251 if [ "$BASE_PER_NODE_TYPE" = "yes" ] ; then
252 DISK="${VIRTBASE}/${BASENAME}-${type}.${BASE_FORMAT}"
254 run_hooks hack_disk_hooks "base"
255 local base_disk="$DISK"
257 # Determine the system disk image name.
258 DISK="${VIRTBASE}/${CLUSTER}/${NAME}.${SYSTEM_DISK_FORMAT}"
259 run_hooks hack_disk_hooks "system"
262 if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
263 di=$(readlink "$DISK")
266 local di_dirname="${di%/*}"
267 mkdir -p "$di_dirname"
269 case "$SYSTEM_DISK_FORMAT" in
271 echo "Creating the disk..."
272 qemu-img create -b "$base_disk" -f qcow2 "$di"
273 create_node_configure_image "$DISK" "$type"
276 echo "Creating the disk..."
277 cp -v --sparse=always "$base_disk" "$di"
278 create_node_configure_image "$DISK" "$type"
281 echo "Creating the disk..."
282 cp -v --reflink=always "$base_disk" "$di"
283 create_node_configure_image "$DISK" "$type"
286 echo "Creating the disk (using mmclone)..."
287 local base_snap="${base_disk}.snap"
288 [ -f "$base_snap" ] || mmclone snap "$base_disk" "$base_snap"
289 mmclone copy "$base_snap" "$di"
290 create_node_configure_image "$DISK" "$type"
293 echo "Skipping disk image creation as requested"
296 die "Error: unknown SYSTEM_DISK_FORMAT=\"${SYSTEM_DISK_FORMAT}\"."
299 # Pull the UUID for this node out of the map.
300 UUID=$(awk "\$1 == $ip_offset {print \$2}" $uuid_map)
304 echo "Creating $NAME.xml"
305 substitute_vars $template_file tmp/$NAME.xml
307 # install the XML file
308 $VIRSH undefine $NAME > /dev/null 2>&1 || true
309 $VIRSH define tmp/$NAME.xml
312 create_node_configure_image ()
317 diskimage mount "$disk"
322 hack_network_map_hooks=""
324 # Uses: CLUSTER, NAME, NETWORKS, FIRSTIP, ip_offset
327 network_map="tmp/network_map.$NAME"
329 if [ -n "$CLUSTER" ] ; then
330 local md5=$(echo "$CLUSTER" | md5sum)
331 local nh=$(printf "%02x" $ip_offset)
332 local mac_prefix="02:${md5:0:2}:${md5:2:2}:00:${nh}:"
334 local mac_prefix="02:42:42:00:00:"
339 for n in $NETWORKS ; do
340 local ch=$(printf "%02x" $count)
341 local mac="${mac_prefix}${ch}"
344 local ip_bits="$1" ; shift
345 local dev="$1" ; shift
348 local net="${ip_bits%/*}"
349 local netname="acnet_${net//./_}"
351 local ip="${net%.*}.${IPNUM}"
352 local mask="255.255.255.0"
354 # This can be used to override the variables in the echo
355 # statement below. The hook can use any other variables
356 # available in this function.
357 run_hooks hack_network_map_hooks
359 echo "${netname} ${dev} ${ip} ${mask} ${mac} ${opts}"
360 count=$(($count + 1))
364 ##############################
368 # Expand out any abbreviations in NODES.
377 for i in ${ips//,/ } ; do
378 ns="${ns}${ns:+ }${t}:${i}"
383 for i in $(seq ${ips/-/ }) ; do
384 ns="${ns}${ns:+ }${t}:${i}"
388 ns="${ns}${ns:+ }${n}"
393 # Check IP addresses for duplicates.
395 # This function doesn't modify anything...
398 [ "${ip_offsets/${ip_offset}}" != "$ip_offsets" ] && \
399 die "Duplicate IP offset in NODES - ${node_type}:${ip_offset}"
400 ip_offsets="${ip_offsets}${ip_offset}:"
402 hack_all_nodes_with get_ip_offset
404 # Determine node names and whether they're in the CTDB cluster
405 declare -A node_count
406 _get_name_ctdb_node ()
408 local count=$((${node_count[$node_type]:-0} + 1))
409 node_count[$node_type]=$count
411 fmt=$(call_func node_name_format "$node_type") || \
412 die "Node type \"${node_type}\" not defined!!!"
413 # printf behaves weirdly if given too many args for format, so
414 # "head" handles the case where there is no %d or similar for
416 name=$(printf "${fmt}" "$CLUSTER" $count | head -n 1)
417 ctdb_node=$(call_func node_is_ctdb_node "$node_type")
419 hack_all_nodes_with _get_name_ctdb_node
422 ##############################
424 sanity_check_cluster_name ()
426 [ -z "${CLUSTER//[A-Za-z0-9]}" ] || \
427 die "Cluster names should be restricted to the characters A-Za-z0-9. \
428 Some cluster filesystems have problems with other characters."
433 cluster_nodelist_hacking ()
435 # Rework the NODES list
438 # Build /etc/hosts and hack the names of the ctdb nodes
439 hosts_line_hack_name ()
443 local ip_addr="${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
445 # Primary name for CTDB nodes is <CLUSTER>n<num>
446 if [ "$ctdb_node" = 1 ] ; then
447 num_ctdb_nodes=$(($num_ctdb_nodes + 1))
448 sname="${CLUSTER}n${num_ctdb_nodes}"
449 hosts_line="$ip_addr ${sname}.${ld} ${name}.${ld} $name $sname"
452 hosts_line="$ip_addr ${name}.${ld} $name"
455 # This allows you to add a function to your configuration file
456 # to modify hostnames (and other aspects of nodes). This
457 # function can access/modify $name (the existing name),
458 # $node_type and $ctdb_node (1, if the node is a member of the
459 # CTDB cluster, 0 otherwise).
460 if [ -n "$HOSTNAME_HACKING_FUNCTION" ] ; then
461 local old_name="$name"
462 $HOSTNAME_HACKING_FUNCTION
463 if [ "$name" != "$old_name" ] ; then
464 hosts_line="$ip_addr ${name}.${ld} $name"
470 hosts_file="tmp/hosts.$CLUSTER"
472 local num_ctdb_nodes=0
473 local ld=$(echo $DOMAIN | tr A-Z a-z)
474 echo "# autocluster $CLUSTER"
475 hack_all_nodes_with hosts_line_hack_name
479 # Build /etc/ctdb/nodes
482 [ "$ctdb_node" = 1 ] || return 0
483 echo "${NETWORK_PRIVATE_PREFIX}.$(($FIRSTIP + $ip_offset))"
484 num_nodes=$(($num_nodes + 1))
486 nodes_file="tmp/nodes.$CLUSTER"
488 hack_all_nodes_with ctdb_nodes_line >$nodes_file
491 uuid_map="tmp/uuid_map.$CLUSTER"
494 echo "${ip_offset} $(uuidgen) ${node_type}"
496 hack_all_nodes_with uuid_map_line >$uuid_map
499 create_cluster_hooks=
500 cluster_created_hooks=
504 # Use $1. If not set then use value from configuration file.
505 CLUSTER="${1:-${CLUSTER}}"
506 announce "cluster create \"${CLUSTER}\""
507 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
509 sanity_check_cluster_name
511 mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
513 # Run hooks before doing anything else.
514 run_hooks create_cluster_hooks
516 for_each_node call_func create_node
518 echo "Cluster $CLUSTER created"
521 run_hooks cluster_created_hooks
524 cluster_created_hosts_message ()
526 echo "You may want to add this to your /etc/hosts file:"
530 register_hook cluster_created_hooks cluster_created_hosts_message
534 announce "cluster destroy \"${CLUSTER}\""
535 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
537 vircmd destroy "$CLUSTER" || true
540 cluster_update_hosts ()
542 announce "cluster update_hosts \"${CLUSTER}\""
543 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
545 [ -n "$hosts_file" ] || hosts_file="tmp/hosts.${CLUSTER}"
546 [ -r "$hosts_file" ] || die "Missing hosts file \"${hosts_file}\""
548 local pat="# autocluster ${CLUSTER}\$|[[:space:]]${CLUSTER}(n|base)[[:digit:]]+"
550 local t="/etc/hosts.${CLUSTER}"
551 grep -E "$pat" /etc/hosts >"$t" || true
552 if diff -B "$t" "$hosts_file" >/dev/null ; then
557 local old=/etc/hosts.old.autocluster
559 local new=/etc/hosts.new
560 grep -Ev "$pat" "$old" |
561 cat -s - "$hosts_file" >"$new"
565 echo "Made these changes to /etc/hosts:"
566 diff -u "$old" /etc/hosts || true
571 [ -n "$CLUSTER_PATTERN" ] || CLUSTER_PATTERN="$CLUSTER"
572 announce "cluster boot \"${CLUSTER_PATTERN}\""
573 [ -n "$CLUSTER_PATTERN" ] || die "\$CLUSTER_PATTERN not set"
575 vircmd start "$CLUSTER_PATTERN"
577 local nodes=$(vircmd dominfo "$CLUSTER_PATTERN" 2>/dev/null | \
578 sed -n -e 's/Name: *//p')
583 waitfor "${KVMLOG}/serial.$i" "login:" 300 || {
584 vircmd destroy "$CLUSTER_PATTERN"
585 die "Failed to create cluster"
589 # Move past the last line of log output
593 cluster_setup_tasks_DEFAULT ()
597 # By default nodes have no tasks
599 install_packages) echo "" ;;
600 setup_clusterfs) echo "" ;;
601 setup_node) echo "" ;;
602 setup_cluster) echo "" ;;
608 announce "cluster setup \"${CLUSTER}\""
609 [ -n "$CLUSTER" ] || die "\$CLUSTER not set"
611 local ssh="ssh -o StrictHostKeyChecking=no"
612 local setup_clusterfs_done=false
613 local setup_cluster_done=false
615 _cluster_setup_do_stage ()
623 local tasks=$(call_func cluster_setup_tasks "$type" "$stage")
625 if [ -n "$tasks" ] ; then
626 # These tasks are only done on 1 node
629 if $setup_clusterfs_done ; then
632 setup_clusterfs_done=true
636 if $setup_cluster_done ; then
639 setup_cluster_done=true
644 $ssh "$name" ./scripts/cluster_setup.sh "$stage" $tasks
649 local stages="install_packages setup_clusterfs setup_node setup_cluster"
651 for stage in $stages ; do
652 for_each_node _cluster_setup_do_stage "$stage"
659 local single_node_ip_offset="$2"
661 sanity_check_cluster_name
663 mkdir -p $VIRTBASE/$CLUSTER $KVMLOG tmp
666 set -- $(IFS=: ; echo $n)
667 [ $single_node_ip_offset -eq $2 ] || continue
668 call_func create_node "$@"
670 echo "Requested node created"
672 echo "You may want to update your /etc/hosts file:"
679 ###############################
680 # test the proxy setup
682 export http_proxy=$WEBPROXY
683 wget -O /dev/null $INSTALL_SERVER || \
684 die "Your WEBPROXY setting \"$WEBPROXY\" is not working"
690 kickstart_floppy_create_hooks=
692 guess_install_network ()
694 # Figure out IP address to use during base install. Default to
695 # the IP address of the 1st (private) network. If a gateway is
696 # specified then use the IP address associated with it.
699 local netname dev ip mask mac opts
700 while read netname dev ip mask mac opts; do
705 INSTALL_GW="${o#gw=}"
706 INSTALL_IP="${ip}${FIRSTIP}"
709 [ -n "$INSTALL_IP" ] || INSTALL_IP="$ip"
716 local NAME="$BASENAME"
717 local DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
718 run_hooks hack_disk_hooks "base"
722 echo "Testing WEBPROXY $WEBPROXY"
726 if [ "$DISK_FOLLOW_SYMLINKS" = "yes" -a -L "$DISK" ] ; then
727 di=$(readlink "$DISK")
730 local di_dirname="${di%/*}"
731 mkdir -p "$di_dirname"
733 echo "Creating the disk"
734 qemu-img create -f $BASE_FORMAT "$di" $DISKSIZE
737 mkdir -p mnt tmp tmp/ISO
743 guess_install_network
745 echo "Creating kickstart file from template"
746 substitute_vars "$KICKSTART" "tmp/ks.cfg"
748 # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
751 (*) ISO="${ISO_DIR}/${ISO}"
754 echo "Creating kickstart floppy"
755 dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
756 mkdosfs -n KICKSTART tmp/floppy.img
757 mount -o loop -t msdos tmp/floppy.img mnt
759 mount -o loop,ro $ISO tmp/ISO
761 echo "Setting up bootloader"
762 cp tmp/ISO/isolinux/isolinux.bin tmp
763 cp tmp/ISO/isolinux/vmlinuz tmp
764 cp tmp/ISO/isolinux/initrd.img tmp
766 run_hooks kickstart_floppy_create_hooks
773 substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
775 rm -f $KVMLOG/serial.$NAME
777 # boot the install CD
778 $VIRSH create tmp/$NAME.xml
780 echo "Waiting for install to start"
783 # wait for the install to finish
784 if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
786 die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
787 You may need to increase the value of CREATE_BASE_TIMEOUT.
788 Alternatively, the install might have completed but KS_DONE_MESSAGE
789 (currently \"${KS_DONE_MESSAGE}\")
790 may not have matched anything at the end of the kickstart output."
798 Install finished, base image $DISK created
801 chcon -t virt_content_t $DISK
803 To ensure that this image does not change
805 Note that the root password has been set to $ROOTPASSWORD
810 ###############################
817 DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
825 diskimage mount $DISK
831 echo "Creating $NAME.xml"
832 substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
834 # boot the base system
835 $VIRSH create tmp/$NAME.xml
838 ######################################################################
840 # Updating a disk image...
846 call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
849 # setup the files from $BASE_TEMPLATES/, substituting any variables
850 # based on the config
851 copy_base_dir_substitute_templates ()
855 local d="$BASE_TEMPLATES/$dir"
856 [ -d "$d" ] || return 0
859 for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
860 f="${f#./}" # remove leading "./" for clarity
861 if [ -d "$d/$f" ]; then
862 # Don't chmod existing directory
863 if diskimage is_directory "/$f" ; then
866 diskimage mkdir_p "/$f"
869 diskimage substitute_vars "$d/$f" "/$f"
871 diskimage chmod_reference "$d/$f" "/$f"
877 setup_base_ssh_keys ()
879 # this is needed as git doesn't store file permissions other
881 # Note that we protect the wildcards from the local shell.
882 diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
883 diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
884 if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
885 echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
886 diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
888 if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
889 echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
890 diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
894 register_hook setup_base_hooks setup_base_ssh_keys
896 setup_base_grub_conf ()
898 echo "Adjusting grub.conf"
899 local o="$EXTRA_KERNEL_OPTIONS" # For readability.
900 local grub_configs="/boot/grub/grub.conf"
901 if ! diskimage is_file "$grub_configs" ; then
902 grub_configs="/etc/default/grub /boot/grub2/grub.cfg"
905 for c in $grub_configs ; do
907 -e "s/console=ttyS0,19200/console=ttyS0,115200/" \
908 -e "s/ console=tty1//" -e "s/ rhgb/ norhgb/" \
909 -e "s/ nodmraid//" -e "s/ nompath//" \
910 -e "s/quiet/noapic divider=10${o:+ }${o}/g"
914 register_hook setup_base_hooks setup_base_grub_conf
921 echo "Copy base files"
922 copy_base_dir_substitute_templates "all"
923 if [ -n "$type" ] ; then
924 copy_base_dir_substitute_templates "$type"
927 run_hooks setup_base_hooks
930 # setup various networking components
933 # This avoids doing anything when we're called from boot_base().
934 if [ -z "$hosts_file" ] ; then
935 echo "Skipping network-related setup"
939 echo "Setting up networks"
940 diskimage append_text_file "$hosts_file" "/etc/hosts"
942 echo "Setting up /etc/ctdb/nodes"
943 diskimage mkdir_p "/etc/ctdb"
944 diskimage put "$nodes_file" "/etc/ctdb/nodes"
946 [ "$WEBPROXY" = "" ] || {
947 diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
950 if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
951 echo "Enabling nfs mount of $NFSSHARE"
952 diskimage mkdir_p "$NFS_MOUNTPOINT"
953 diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
956 diskimage mkdir_p "/etc/yum.repos.d"
957 echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
959 diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
961 echo "Setting up network interfaces: "
962 local netname dev ip mask mac opts
963 while read netname dev ip mask mac opts; do
976 diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
986 # This goes to 70-persistent-net.rules
988 # Generated by autocluster
989 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
992 done <"$network_map" |
993 diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
996 register_hook setup_base_hooks setup_network
999 [ -z "$TIMEZONE" ] && {
1000 [ -r /etc/timezone ] && {
1001 TIMEZONE=`cat /etc/timezone`
1003 [ -r /etc/sysconfig/clock ] && {
1004 . /etc/sysconfig/clock
1007 TIMEZONE="${TIMEZONE// /_}"
1009 [ -n "$TIMEZONE" ] || \
1010 die "Unable to determine TIMEZONE - please set in config"
1013 # substite a set of variables of the form @@XX@@ for the shell
1014 # variables $XX in a file.
1016 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
1017 # contain a filename whose contents are substituted, with variable
1018 # substitution applied to those contents. If filename starts with '|'
1019 # it is a command instead - however, quoting is extremely fragile.
1020 substitute_vars() {(
1021 infile="${1:-/dev/null}" # if empty then default to /dev/null
1022 outfile="$2" # optional
1025 cat "$infile" >"$tmp_out"
1027 # Handle any indirects by looping until nothing changes.
1028 # However, only handle 10 levels of recursion.
1031 if ! _substitute_vars "$tmp_out" "@@@" ; then
1033 die "Failed to expand template $infile"
1036 # No old version of file means no changes made.
1037 if [ ! -f "${tmp_out}.old" ] ; then
1041 rm -f "${tmp_out}.old"
1043 count=$(($count + 1))
1044 if [ $count -ge 10 ] ; then
1046 die "Recursion too deep in $infile - only 10 levels allowed!"
1050 # Now regular variables.
1051 if ! _substitute_vars "$tmp_out" "@@" ; then
1053 die "Failed to expand template $infile"
1055 rm -f "${tmp_out}.old"
1057 if [ -n "$outfile" ] ; then
1058 mv "$tmp_out" "$outfile"
1066 # Delimiter @@ means to substitute contents of variable.
1067 # Delimiter @@@ means to substitute contents of file named by variable.
1068 # @@@ supports leading '|' in variable value, which means to excute a
1070 _substitute_vars() {(
1072 delimiter="${2:-@@}"
1074 # Get the list of variables used in the template. The grep
1075 # gets rid of any blank lines and lines with extraneous '@'s
1076 # next to template substitutions.
1077 VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
1078 grep '^[A-Z0-9_][A-Z0-9_]*$' |
1083 # variable variables are fun .....
1086 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
1090 if [ "$delimiter" = "@@@" ] ; then
1092 c="${f#|}" # Is is a command, signified by a leading '|'?
1093 if [ "$c" = "$f" ] ; then
1094 # No leading '|', cat file.
1098 die "Could not substitute contents of file $f"
1101 # Leading '|', execute command.
1102 # Quoting problems here - using eval "$c" doesn't help.
1106 die "Could not execute command $c"
1111 # escape some pesky chars
1112 # This first one can be too slow if done using a bash
1113 # variable pattern subsitution.
1114 s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
1117 echo "s#${delimiter}${v}${delimiter}#${s}#g"
1120 # Get the in-place sed to make a backup of the old file.
1121 # Remove the backup if it is the same as the resulting file -
1122 # this acts as a flag to the caller that no changes were made.
1123 sed -i.old -f $tmp "$tmp_out"
1124 if cmp -s "${tmp_out}.old" "$tmp_out" ; then
1125 rm -f "${tmp_out}.old"
1132 which $1 > /dev/null || die "Please install $1 to continue"
1135 # Set a variable if it isn't already set. This allows environment
1136 # variables to override default config settings.
1141 [ "${!v+x}" ] || eval "$v=\"$e\""
1147 for i in "${installdir}/config.d/"*.defconf ; do
1152 # Print the list of config variables defined in config.d/.
1153 get_config_options () {( # sub-shell for local declaration of defconf()
1155 defconf() { options="$options $1" ; }
1160 # Produce a list of long options, suitable for use with getopt, that
1161 # represent the config variables defined in config.d/.
1162 getopt_config_options () {
1163 local x=$(get_config_options | tr 'A-Z_' 'a-z-')
1167 # Unconditionally set the config variable associated with the given
1169 setconf_longopt () {
1173 local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
1174 # unset so defconf will set it
1179 # Dump all of the current config variables.
1182 for o in $(get_config_options) ; do
1183 echo "${o}=\"${!o}\""
1188 # $COLUMNS is set in interactive bash shells. It probably isn't set
1189 # in this shell, so let's set it if it isn't.
1190 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1194 # Print text assuming it starts after other text in $startcol and
1195 # needs to wrap before $COLUMNS - 2. Subsequent lines start at $startcol.
1196 # Long "words" will extend past $COLUMNS - 2.
1201 local width=$(($COLUMNS - 2 - $startcol))
1202 [ $width -lt 0 ] && width=$((78 - $startcol))
1207 if [ $startcol -gt 0 ] ; then
1208 padding=$(printf "\n%${startcol}s" " ")
1214 while [ -n "$text" ] ; do
1217 # If we already have output then arrange padding on the next line.
1218 [ -n "$out" ] && out="${out}${padding}"
1220 # Break the text at $width.
1221 out="${out}${text:0:${width}}"
1222 text="${text:${width}}"
1224 # If we have left over text then the line break may be ugly,
1225 # so let's check and try to break it on a space.
1226 if [ -n "$text" ] ; then
1227 # The 'x's stop us producing a special character like '(',
1228 # ')' or '!'. Yuck - there must be a better way.
1229 if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1230 # We didn't break on a space. Arrange for the
1231 # beginning of the broken "word" to appear on the next
1232 # line but not if it will make us loop infinitely.
1233 if [ "${orig}" != "${out##* }${text}" ] ; then
1234 text="${out##* }${text}"
1237 # Hmmm, doing that would make us loop, so add the
1238 # rest of the word from the remainder of the text
1239 # to this line and let it extend past $COLUMNS - 2.
1240 out="${out}${text%% *}"
1241 if [ "${text# *}" != "$text" ] ; then
1242 # Remember the text after the next space for next time.
1245 # No text after next space.
1250 # We broke on a space. If it will be at the beginning
1251 # of the next line then remove it.
1260 # Display usage text, trying these approaches in order.
1261 # 1. See if it all fits on one line before $COLUMNS - 2.
1262 # 2. See if splitting before the default value and indenting it
1263 # to $startcol means that nothing passes $COLUMNS - 2.
1264 # 3. Treat the message and default value as a string and just us fill_text()
1266 usage_display_text () {
1271 local width=$(($COLUMNS - 2 - $startcol))
1272 [ $width -lt 0 ] && width=$((78 - $startcol))
1274 default="(default \"$default\")"
1276 if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1277 echo "${desc} ${default}"
1279 local padding=$(printf "%${startcol}s" " ")
1281 if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1283 echo "${padding}${default}"
1285 fill_text $startcol "${desc} ${default}"
1290 # Display usage information for long config options.
1291 usage_smart_display () {( # sub-shell for local declaration of defconf()
1295 local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1297 printf " --%-25s " "${longopt}=${3}"
1299 usage_display_text $startcol "$4" "$2"
1306 # Display usage information for long config options.
1307 usage_config_options (){
1308 usage_smart_display load_config
1318 actions="${actions}${actions:+ }$*"
1323 [ -n "$actions" ] || usage
1326 for a in $actions ; do
1331 ######################################################################
1335 ######################################################################
1339 ############################
1340 # parse command line options
1341 long_opts=$(getopt_config_options)
1342 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump -l "$long_opts" -- "$@")
1343 [ $? != 0 ] && usage
1345 use_default_config=true
1347 # We do 2 passes of the options. The first time we just handle usage
1348 # and check whether -c is being used.
1349 eval set -- "$getopt_output"
1352 -c) shift 2 ; use_default_config=false ;;
1355 --) shift ; break ;;
1357 -h|--help) usage ;; # Usage should be shown here for real defaults.
1358 --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1359 *) usage ;; # shouldn't happen, so this is reasonable.
1364 $use_default_config && [ -r "$config" ] && . "$config"
1366 eval set -- "$getopt_output"
1372 # force at least ./local_file to avoid accidental file
1374 . "$(dirname $2)/${b}"
1375 # If $CLUSTER is unset then try to base it on the filename
1376 if [ ! -n "$CLUSTER" ] ; then
1379 CLUSTER="${b%.autocluster}"
1384 -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1385 -E) eval "$2" ; shift 2 ;;
1386 -x) set -x; shift ;;
1387 --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1388 --) shift ; break ;;
1389 -h|--help) usage ;; # Redundant.
1391 # Putting --opt1|opt2|... into a variable and having case
1392 # match against it as a pattern doesn't work. The | is
1393 # part of shell syntax, so we need to do this. Look away
1394 # now to stop your eyes from bleeding! :-)
1395 x=",${long_opts}" # Now each option is surrounded by , and :
1396 if [ "$x" != "${x#*,${1#--}:}" ] ; then
1397 # Our option, $1, surrounded by , and : was in $x, so is legal.
1398 setconf_longopt "$1" "$2"; shift 2
1403 *) usage ;; # shouldn't happen, so this is reasonable.
1407 run_hooks post_config_hooks
1413 echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es;
1416 # check for needed programs
1417 check_command expect
1419 [ $# -lt 1 ] && usage
1429 create|boot) actions_add "base_${t}" ;;
1440 destroy|create|update_hosts|boot|setup)
1441 actions_add "cluster_${t}" ;;
1443 for t in destroy create update_hosts boot setup ; do
1444 actions_add "cluster_${t}"
1450 cluster_nodelist_hacking
1459 [ $# != 0 ] && usage
1463 [ $# != 1 ] && usage
1467 [ $# != 2 ] && usage
1468 create_one_node "$1" "$2"
1476 [ $# != 1 ] && usage
1477 diskimage mount "$1"
1480 [ $# != 0 ] && usage