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