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