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