RHEL 7 needs different boot options to support kickstart
[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     if [ $INSTALLKEY = "--skip" ]; then
573         cat <<EOF
574 --------------------------------------------------------------------------------------
575 WARNING: You have not entered an install key. Some RHEL packages will not be installed.
576
577 Please enter a valid RHEL install key in your config file like this:
578
579   INSTALLKEY="1234-5678-0123-4567"
580
581 The install will continue without an install key in 5 seconds
582 --------------------------------------------------------------------------------------
583 EOF
584         sleep 5
585     fi
586
587     # $ISO gets $ISO_DIR prepended if it doesn't start with a leading '/'.
588     case "$ISO" in
589         (/*) : ;;
590         (*) ISO="${ISO_DIR}/${ISO}"
591     esac
592     
593     echo "Creating kickstart floppy"
594     dd if=/dev/zero of=tmp/floppy.img bs=1024 count=1440
595     mkdosfs -n KICKSTART tmp/floppy.img
596     mount -o loop -t msdos tmp/floppy.img mnt
597     cp tmp/ks.cfg mnt
598     mount -o loop,ro $ISO tmp/ISO
599     
600     echo "Setting up bootloader"
601     cp tmp/ISO/isolinux/isolinux.bin tmp
602     cp tmp/ISO/isolinux/vmlinuz tmp
603     cp tmp/ISO/isolinux/initrd.img tmp
604
605     run_hooks kickstart_floppy_create_hooks
606
607     umount tmp/ISO
608     umount mnt
609
610     UUID=`uuidgen`
611
612     substitute_vars $INSTALL_TEMPLATE tmp/$NAME.xml
613
614     rm -f $KVMLOG/serial.$NAME
615
616     # boot the install CD
617     $VIRSH create tmp/$NAME.xml
618
619     echo "Waiting for install to start"
620     sleep 2
621     
622     # wait for the install to finish
623     if ! waitfor $KVMLOG/serial.$NAME "$KS_DONE_MESSAGE" $CREATE_BASE_TIMEOUT ; then
624         $VIRSH destroy $NAME
625         die "Failed to create base image ${DISK} after waiting for ${CREATE_BASE_TIMEOUT} seconds.
626 You may need to increase the value of CREATE_BASE_TIMEOUT.
627 Alternatively, the install might have completed but KS_DONE_MESSAGE
628 (currently \"${KS_DONE_MESSAGE}\")
629 may not have matched anything at the end of the kickstart output."
630     fi
631     
632     $VIRSH destroy $NAME
633
634     ls -l $DISK
635     cat <<EOF
636
637 Install finished, base image $DISK created
638
639 You may wish to run
640    chattr +i $DISK
641 To ensure that this image does not change
642
643 Note that the root password has been set to $ROOTPASSWORD
644
645 EOF
646 }
647
648 ###############################
649 # boot the base disk
650 boot_base() {
651     rm -rf tmp
652     mkdir -p tmp
653
654     NAME="$BASENAME"
655     DISK="${VIRTBASE}/${NAME}.${BASE_FORMAT}"
656
657     IPNUM=$FIRSTIP
658
659     make_network_map
660
661     CLUSTER="base"
662
663     diskimage mount $DISK
664     setup_base
665     diskimage unmount
666
667     UUID=`uuidgen`
668     
669     echo "Creating $NAME.xml"
670     substitute_vars $BOOT_TEMPLATE tmp/$NAME.xml
671     
672     # boot the base system
673     $VIRSH create tmp/$NAME.xml
674 }
675
676 ######################################################################
677
678 # Updating a disk image...
679
680 diskimage ()
681 {
682     local func="$1"
683     shift
684     call_func diskimage_"$func" "$SYSTEM_DISK_ACCESS_METHOD" "$@"
685 }
686
687 # setup the files from $BASE_TEMPLATES/, substituting any variables
688 # based on the config
689 copy_base_dir_substitute_templates ()
690 {
691     local dir="$1"
692
693     local d="$BASE_TEMPLATES/$dir"
694     [ -d "$d" ] || return 0
695
696     local f
697     for f in $(cd "$d" && find . \! -name '*~' \( -type d -name .svn -prune -o -print \) ) ; do
698         f="${f#./}" # remove leading "./" for clarity
699         if [ -d "$d/$f" ]; then
700             # Don't chmod existing directory
701             if diskimage is_directory "/$f" ; then
702                 continue
703             fi
704             diskimage mkdir_p "/$f"
705         else
706             echo " Install: $f"
707             diskimage substitute_vars "$d/$f" "/$f"
708         fi
709         diskimage chmod_reference "$d/$f" "/$f"
710     done
711 }
712
713 setup_base_hooks=
714
715 setup_base_ssh_keys ()
716 {
717     # this is needed as git doesn't store file permissions other
718     # than execute
719     # Note that we protect the wildcards from the local shell.
720     diskimage chmod 600 "/etc/ssh/*key" "/root/.ssh/*"
721     diskimage chmod 700 "/etc/ssh" "/root/.ssh" "/root"
722     if [ -r "$HOME/.ssh/id_rsa.pub" ]; then
723        echo "Adding $HOME/.ssh/id_rsa.pub to ssh authorized_keys"
724        diskimage append_text_file "$HOME/.ssh/id_rsa.pub" "/root/.ssh/authorized_keys"
725     fi
726     if [ -r "$HOME/.ssh/id_dsa.pub" ]; then
727        echo "Adding $HOME/.ssh/id_dsa.pub to ssh authorized_keys"
728        diskimage append_text_file "$HOME/.ssh/id_dsa.pub" "/root/.ssh/authorized_keys"
729     fi
730 }
731
732 register_hook setup_base_hooks setup_base_ssh_keys
733
734 setup_base_grub_conf ()
735 {
736     echo "Adjusting grub.conf"
737     local o="$EXTRA_KERNEL_OPTIONS" # For readability.
738     diskimage sed "/boot/grub/grub.conf" \
739         -e "s/console=ttyS0,19200/console=ttyS0,115200/"  \
740         -e "s/ nodmraid//" -e "s/ nompath//"  \
741         -e "s/quiet/noapic divider=10${o:+ }${o}/g"
742 }
743
744 register_hook setup_base_hooks setup_base_grub_conf
745
746 setup_base()
747 {
748     local type="$1"
749
750     umask 022
751     echo "Copy base files"
752     copy_base_dir_substitute_templates "all"
753     if [ -n "$type" ] ; then
754         copy_base_dir_substitute_templates "$type"
755     fi
756
757     run_hooks setup_base_hooks
758 }
759
760 # setup various networking components
761 setup_network()
762 {
763     # This avoids doing anything when we're called from boot_base().
764     if [ -z "$hosts_file" ] ; then
765         echo "Skipping network-related setup"
766         return
767     fi
768
769     echo "Setting up networks"
770     diskimage append_text_file "$hosts_file" "/etc/hosts"
771
772     echo "Setting up /etc/ctdb/nodes"
773     diskimage mkdir_p "/etc/ctdb"
774     diskimage put "$nodes_file" "/etc/ctdb/nodes"
775
776     [ "$WEBPROXY" = "" ] || {
777         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
778     }
779
780     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
781         echo "Enabling nfs mount of $NFSSHARE"
782         diskimage mkdir_p "$NFS_MOUNTPOINT"
783         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
784     fi
785
786     diskimage mkdir_p "/etc/yum.repos.d"
787     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
788
789     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
790
791     echo "Setting up network interfaces: "
792     local netname dev ip mask mac opts
793     while read netname dev ip mask mac opts; do
794         echo "  $dev"
795         cat <<EOF | \
796             diskimage substitute_vars \
797             - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
798 DEVICE=$dev
799 ONBOOT=yes
800 TYPE=Ethernet
801 IPADDR=$ip
802 NETMASK=$mask
803 HWADDR=$mac
804 EOF
805     done <"$network_map"
806 }
807
808 register_hook setup_base_hooks setup_network
809
810 setup_timezone() {
811     [ -z "$TIMEZONE" ] && {
812         [ -r /etc/timezone ] && {
813             TIMEZONE=`cat /etc/timezone`
814         }
815         [ -r /etc/sysconfig/clock ] && {
816             . /etc/sysconfig/clock
817             TIMEZONE="$ZONE"
818         }
819         TIMEZONE="${TIMEZONE// /_}"
820     }
821     [ -n "$TIMEZONE" ] || \
822         die "Unable to determine TIMEZONE - please set in config"
823 }
824
825 # substite a set of variables of the form @@XX@@ for the shell
826 # variables $XX in a file.
827 #
828 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
829 # contain a filename whose contents are substituted, with variable
830 # substitution applied to those contents.  If filename starts with '|'
831 # it is a command instead - however, quoting is extremely fragile.
832 substitute_vars() {(
833         infile="${1:-/dev/null}" # if empty then default to /dev/null
834         outfile="$2" # optional
835
836         tmp_out=$(mktemp)
837         cat "$infile" >"$tmp_out"
838
839         # Handle any indirects by looping until nothing changes.
840         # However, only handle 10 levels of recursion.
841         count=0
842         while : ; do
843             if ! _substitute_vars "$tmp_out" "@@@" ; then
844                 rm -f "$tmp_out"
845                 die "Failed to expand template $infile"
846             fi
847
848             # No old version of file means no changes made.
849             if [ ! -f "${tmp_out}.old" ] ; then
850                 break
851             fi
852
853             rm -f "${tmp_out}.old"
854
855             count=$(($count + 1))
856             if [ $count -ge 10 ] ; then
857                 rm -f "$tmp_out"
858                 die "Recursion too deep in $infile - only 10 levels allowed!"
859             fi
860         done
861
862         # Now regular variables.
863         if ! _substitute_vars "$tmp_out" "@@" ; then
864             rm -f "$tmp_out"
865             die "Failed to expand template $infile"
866         fi
867         rm -f "${tmp_out}.old"
868
869         if [ -n "$outfile" ] ; then
870             mv "$tmp_out" "$outfile"
871         else
872             cat "$tmp_out"
873             rm -f "$tmp_out"
874         fi
875 )}
876
877
878 # Delimiter @@ means to substitute contents of variable.
879 # Delimiter @@@ means to substitute contents of file named by variable.
880 # @@@ supports leading '|' in variable value, which means to excute a
881 # command.
882 _substitute_vars() {(
883         tmp_out="$1"
884         delimiter="${2:-@@}"
885
886         # Get the list of variables used in the template.  The grep
887         # gets rid of any blank lines and lines with extraneous '@'s
888         # next to template substitutions.
889         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
890             grep '^[A-Z0-9_][A-Z0-9_]*$' |
891             sort -u)
892
893         tmp=$(mktemp)
894         for v in $VARS; do
895             # variable variables are fun .....
896             [ "${!v+x}" ] || {
897                 rm -f $tmp
898                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
899             }
900             s=${!v}
901
902             if [ "$delimiter" = "@@@" ] ; then
903                 f=${s:-/dev/null}
904                 c="${f#|}" # Is is a command, signified by a leading '|'?
905                 if [ "$c" = "$f" ] ; then
906                     # No leading '|', cat file.
907                     s=$(cat -- "$f")
908                     [ $? -eq 0 ] || {
909                         rm -f $tmp
910                         die "Could not substitute contents of file $f"
911                     }
912                 else
913                     # Leading '|', execute command.
914                     # Quoting problems here - using eval "$c" doesn't help.
915                     s=$($c)
916                     [ $? -eq 0 ] || {
917                         rm -f $tmp
918                         die "Could not execute command $c"
919                     }
920                 fi
921             fi
922
923             # escape some pesky chars
924             # This first one can be too slow if done using a bash
925             # variable pattern subsitution.
926             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
927             s=${s//#/\\#}
928             s=${s//&/\\&}
929             echo "s#${delimiter}${v}${delimiter}#${s}#g"
930         done > $tmp
931
932         # Get the in-place sed to make a backup of the old file.
933         # Remove the backup if it is the same as the resulting file -
934         # this acts as a flag to the caller that no changes were made.
935         sed -i.old -f $tmp "$tmp_out"
936         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
937             rm -f "${tmp_out}.old"
938         fi
939
940         rm -f $tmp
941 )}
942
943 check_command() {
944     which $1 > /dev/null || die "Please install $1 to continue"
945 }
946
947 # Set a variable if it isn't already set.  This allows environment
948 # variables to override default config settings.
949 defconf() {
950     local v="$1"
951     local e="$2"
952
953     [ "${!v+x}" ] || eval "$v=\"$e\""
954 }
955
956 load_config () {
957     local i
958
959     for i in "${installdir}/config.d/"*.defconf ; do
960         . "$i"
961     done
962 }
963
964 # Print the list of config variables defined in config.d/.
965 get_config_options () {( # sub-shell for local declaration of defconf()
966         local options=
967         defconf() { options="$options $1" ; }
968         load_config
969         echo $options
970 )}
971
972 # Produce a list of long options, suitable for use with getopt, that
973 # represent the config variables defined in config.d/.
974 getopt_config_options () {
975     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
976     echo "${x// /:,}:"
977 }
978
979 # Unconditionally set the config variable associated with the given
980 # long option.
981 setconf_longopt () {
982     local longopt="$1"
983     local e="$2"
984
985     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
986     # unset so defconf will set it
987     eval "unset $v"
988     defconf "$v" "$e"
989 }
990
991 # Dump all of the current config variables.
992 dump_config() {
993     local o
994     for o in $(get_config_options) ; do
995         echo "${o}=\"${!o}\""
996     done
997     exit 0
998 }
999
1000 # $COLUMNS is set in interactive bash shells.  It probably isn't set
1001 # in this shell, so let's set it if it isn't.
1002 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1003 : ${COLUMNS:=80}
1004 export COLUMNS
1005
1006 # Print text assuming it starts after other text in $startcol and
1007 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1008 # Long "words" will extend past $COLUMNS - 2.
1009 fill_text() {
1010     local startcol="$1"
1011     local text="$2"
1012
1013     local width=$(($COLUMNS - 2 - $startcol))
1014     [ $width -lt 0 ] && width=$((78 - $startcol))
1015
1016     local out=""
1017
1018     local padding
1019     if [ $startcol -gt 0 ] ; then
1020         padding=$(printf "\n%${startcol}s" " ")
1021     else
1022         padding="
1023 "
1024     fi
1025
1026     while [ -n "$text" ] ; do
1027         local orig="$text"
1028
1029         # If we already have output then arrange padding on the next line.
1030         [ -n "$out" ] && out="${out}${padding}"
1031
1032         # Break the text at $width.
1033         out="${out}${text:0:${width}}"
1034         text="${text:${width}}"
1035
1036         # If we have left over text then the line break may be ugly,
1037         # so let's check and try to break it on a space.
1038         if [ -n "$text" ] ; then
1039             # The 'x's stop us producing a special character like '(',
1040             # ')' or '!'.  Yuck - there must be a better way.
1041             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1042                 # We didn't break on a space.  Arrange for the
1043                 # beginning of the broken "word" to appear on the next
1044                 # line but not if it will make us loop infinitely.
1045                 if [ "${orig}" != "${out##* }${text}" ] ; then
1046                     text="${out##* }${text}"
1047                     out="${out% *}"
1048                 else
1049                     # Hmmm, doing that would make us loop, so add the
1050                     # rest of the word from the remainder of the text
1051                     # to this line and let it extend past $COLUMNS - 2.
1052                     out="${out}${text%% *}"
1053                     if [ "${text# *}" != "$text" ] ; then
1054                         # Remember the text after the next space for next time.
1055                         text="${text# *}"
1056                     else
1057                         # No text after next space.
1058                         text=""
1059                     fi
1060                 fi
1061             else
1062                 # We broke on a space.  If it will be at the beginning
1063                 # of the next line then remove it.
1064                 text="${text# }"
1065             fi
1066         fi
1067     done
1068
1069     echo "$out"
1070 }
1071
1072 # Display usage text, trying these approaches in order.
1073 # 1. See if it all fits on one line before $COLUMNS - 2.
1074 # 2. See if splitting before the default value and indenting it
1075 #    to $startcol means that nothing passes $COLUMNS - 2.
1076 # 3. Treat the message and default value as a string and just us fill_text()
1077 #    to format it. 
1078 usage_display_text () {
1079     local startcol="$1"
1080     local desc="$2"
1081     local default="$3"
1082     
1083     local width=$(($COLUMNS - 2 - $startcol))
1084     [ $width -lt 0 ] && width=$((78 - $startcol))
1085
1086     default="(default \"$default\")"
1087
1088     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1089         echo "${desc} ${default}"
1090     else
1091         local padding=$(printf "%${startcol}s" " ")
1092
1093         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1094             echo "$desc"
1095             echo "${padding}${default}"
1096         else
1097             fill_text $startcol "${desc} ${default}"
1098         fi
1099     fi
1100 }
1101
1102 # Display usage information for long config options.
1103 usage_smart_display () {( # sub-shell for local declaration of defconf()
1104         local startcol=33
1105
1106         defconf() {
1107             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1108
1109             printf "     --%-25s " "${longopt}=${3}"
1110
1111             usage_display_text $startcol "$4" "$2"
1112         }
1113
1114         "$@"
1115 )}
1116
1117
1118 # Display usage information for long config options.
1119 usage_config_options (){
1120     usage_smart_display load_config
1121 }
1122
1123 list_releases () {
1124     local releases=$(cd $installdir/releases && echo *.release)
1125     releases="${releases//.release}"
1126     releases="${releases// /\", \"}"
1127     echo "\"$releases\""
1128 }
1129
1130 ######################################################################
1131
1132 post_config_hooks=
1133
1134 ######################################################################
1135
1136 load_config
1137
1138 ############################
1139 # parse command line options
1140 long_opts=$(getopt_config_options)
1141 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1142 [ $? != 0 ] && usage
1143
1144 use_default_config=true
1145
1146 # We do 2 passes of the options.  The first time we just handle usage
1147 # and check whether -c is being used.
1148 eval set -- "$getopt_output"
1149 while true ; do
1150     case "$1" in
1151         -c) shift 2 ; use_default_config=false ;;
1152         -e) shift 2 ;;
1153         -E) shift 2 ;;
1154         --) shift ; break ;;
1155         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1156         --dump|-x) shift ;;
1157         -h|--help) usage ;; # Usage should be shown here for real defaults.
1158         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1159         *) usage ;; # shouldn't happen, so this is reasonable.
1160     esac
1161 done
1162
1163 config="./config"
1164 $use_default_config && [ -r "$config" ] && . "$config"
1165
1166 eval set -- "$getopt_output"
1167
1168 while true ; do
1169     case "$1" in
1170         # force at least ./local_file to avoid accidental file from $PATH
1171         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1172         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1173         -E) eval "$2" ; shift 2 ;;
1174         -x) set -x; shift ;;
1175         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1176         --) shift ; break ;;
1177         -h|--help) usage ;; # Redundant.
1178         --*)
1179             # Putting --opt1|opt2|... into a variable and having case
1180             # match against it as a pattern doesn't work.  The | is
1181             # part of shell syntax, so we need to do this.  Look away
1182             # now to stop your eyes from bleeding! :-)
1183             x=",${long_opts}" # Now each option is surrounded by , and :
1184             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1185                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1186                 setconf_longopt "$1" "$2"; shift 2
1187             else
1188                 usage
1189             fi
1190             ;;
1191         *) usage ;; # shouldn't happen, so this is reasonable.
1192     esac
1193 done
1194
1195 run_hooks post_config_hooks 
1196
1197 # catch errors
1198 set -e
1199 set -E
1200 trap 'es=$?; 
1201       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1202       exit $es' ERR
1203
1204 # check for needed programs 
1205 check_command expect
1206
1207 [ $# -lt 1 ] && usage
1208
1209 command="$1"
1210 shift
1211
1212 case $command in
1213     create)
1214         type=$1
1215         shift
1216         case $type in
1217             base)
1218                 [ $# != 0 ] && usage
1219                 create_base
1220                 ;;
1221             cluster)
1222                 [ $# != 1 ] && usage
1223                 create_cluster "$1"
1224                 ;;
1225             node)
1226                 [ $# != 2 ] && usage
1227                 create_one_node "$1" "$2"
1228                 ;;
1229             *)
1230                 usage;
1231                 ;;
1232         esac
1233         ;;
1234     mount)
1235         [ $# != 1 ] && usage
1236         diskimage mount "$1"
1237         ;;
1238     unmount|umount)
1239         [ $# != 0 ] && usage
1240         diskimage unmount
1241         ;;
1242     bootbase)
1243         boot_base;
1244         ;;
1245     testproxy)
1246         test_proxy;
1247         ;;
1248     *)
1249         usage;
1250         ;;
1251 esac