Handle grub2 configuration hacking in RHEL 7+
[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/ nodmraid//" -e "s/ nompath//"  \
732             -e "s/quiet/noapic divider=10${o:+ }${o}/g"
733     done
734 }
735
736 register_hook setup_base_hooks setup_base_grub_conf
737
738 setup_base()
739 {
740     local type="$1"
741
742     umask 022
743     echo "Copy base files"
744     copy_base_dir_substitute_templates "all"
745     if [ -n "$type" ] ; then
746         copy_base_dir_substitute_templates "$type"
747     fi
748
749     run_hooks setup_base_hooks
750 }
751
752 # setup various networking components
753 setup_network()
754 {
755     # This avoids doing anything when we're called from boot_base().
756     if [ -z "$hosts_file" ] ; then
757         echo "Skipping network-related setup"
758         return
759     fi
760
761     echo "Setting up networks"
762     diskimage append_text_file "$hosts_file" "/etc/hosts"
763
764     echo "Setting up /etc/ctdb/nodes"
765     diskimage mkdir_p "/etc/ctdb"
766     diskimage put "$nodes_file" "/etc/ctdb/nodes"
767
768     [ "$WEBPROXY" = "" ] || {
769         diskimage append_text "export http_proxy=$WEBPROXY" "/etc/bashrc"
770     }
771
772     if [ -n "$NFSSHARE" -a -n "$NFS_MOUNTPOINT" ] ; then
773         echo "Enabling nfs mount of $NFSSHARE"
774         diskimage mkdir_p "$NFS_MOUNTPOINT"
775         diskimage append_text "$NFSSHARE $NFS_MOUNTPOINT nfs nfsvers=3,intr 0 0" "/etc/fstab"
776     fi
777
778     diskimage mkdir_p "/etc/yum.repos.d"
779     echo '@@@YUM_TEMPLATE@@@' | diskimage substitute_vars - "/etc/yum.repos.d/autocluster.repo"
780
781     diskimage rm_rf "/etc/udev/rules.d/70-persistent-net.rules"
782
783     echo "Setting up network interfaces: "
784     local netname dev ip mask mac opts
785     while read netname dev ip mask mac opts; do
786         echo "  $dev"
787         cat <<EOF | \
788             diskimage put - "/etc/sysconfig/network-scripts/ifcfg-${dev}"
789 DEVICE=$dev
790 ONBOOT=yes
791 TYPE=Ethernet
792 IPADDR=$ip
793 NETMASK=$mask
794 HWADDR=$mac
795 EOF
796
797         # This goes to 70-persistent-net.rules
798         cat <<EOF
799 # Generated by autocluster
800 SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${mac}", ATTR{type}=="1", KERNEL=="eth*", NAME="${dev}"
801
802 EOF
803     done <"$network_map" |
804     diskimage put - "/etc/udev/rules.d/70-persistent-net.rules"
805 }
806
807 register_hook setup_base_hooks setup_network
808
809 setup_timezone() {
810     [ -z "$TIMEZONE" ] && {
811         [ -r /etc/timezone ] && {
812             TIMEZONE=`cat /etc/timezone`
813         }
814         [ -r /etc/sysconfig/clock ] && {
815             . /etc/sysconfig/clock
816             TIMEZONE="$ZONE"
817         }
818         TIMEZONE="${TIMEZONE// /_}"
819     }
820     [ -n "$TIMEZONE" ] || \
821         die "Unable to determine TIMEZONE - please set in config"
822 }
823
824 # substite a set of variables of the form @@XX@@ for the shell
825 # variables $XX in a file.
826 #
827 # Indirect variables @@@XX@@@ (3 ats) specify that the variable should
828 # contain a filename whose contents are substituted, with variable
829 # substitution applied to those contents.  If filename starts with '|'
830 # it is a command instead - however, quoting is extremely fragile.
831 substitute_vars() {(
832         infile="${1:-/dev/null}" # if empty then default to /dev/null
833         outfile="$2" # optional
834
835         tmp_out=$(mktemp)
836         cat "$infile" >"$tmp_out"
837
838         # Handle any indirects by looping until nothing changes.
839         # However, only handle 10 levels of recursion.
840         count=0
841         while : ; do
842             if ! _substitute_vars "$tmp_out" "@@@" ; then
843                 rm -f "$tmp_out"
844                 die "Failed to expand template $infile"
845             fi
846
847             # No old version of file means no changes made.
848             if [ ! -f "${tmp_out}.old" ] ; then
849                 break
850             fi
851
852             rm -f "${tmp_out}.old"
853
854             count=$(($count + 1))
855             if [ $count -ge 10 ] ; then
856                 rm -f "$tmp_out"
857                 die "Recursion too deep in $infile - only 10 levels allowed!"
858             fi
859         done
860
861         # Now regular variables.
862         if ! _substitute_vars "$tmp_out" "@@" ; then
863             rm -f "$tmp_out"
864             die "Failed to expand template $infile"
865         fi
866         rm -f "${tmp_out}.old"
867
868         if [ -n "$outfile" ] ; then
869             mv "$tmp_out" "$outfile"
870         else
871             cat "$tmp_out"
872             rm -f "$tmp_out"
873         fi
874 )}
875
876
877 # Delimiter @@ means to substitute contents of variable.
878 # Delimiter @@@ means to substitute contents of file named by variable.
879 # @@@ supports leading '|' in variable value, which means to excute a
880 # command.
881 _substitute_vars() {(
882         tmp_out="$1"
883         delimiter="${2:-@@}"
884
885         # Get the list of variables used in the template.  The grep
886         # gets rid of any blank lines and lines with extraneous '@'s
887         # next to template substitutions.
888         VARS=$(sed -n -e "s#[^@]*${delimiter}\([A-Z0-9_][A-Z0-9_]*\)${delimiter}[^@]*#\1\n#gp" "$tmp_out" |
889             grep '^[A-Z0-9_][A-Z0-9_]*$' |
890             sort -u)
891
892         tmp=$(mktemp)
893         for v in $VARS; do
894             # variable variables are fun .....
895             [ "${!v+x}" ] || {
896                 rm -f $tmp
897                 die "No substitution given for ${delimiter}$v${delimiter} in $infile"
898             }
899             s=${!v}
900
901             if [ "$delimiter" = "@@@" ] ; then
902                 f=${s:-/dev/null}
903                 c="${f#|}" # Is is a command, signified by a leading '|'?
904                 if [ "$c" = "$f" ] ; then
905                     # No leading '|', cat file.
906                     s=$(cat -- "$f")
907                     [ $? -eq 0 ] || {
908                         rm -f $tmp
909                         die "Could not substitute contents of file $f"
910                     }
911                 else
912                     # Leading '|', execute command.
913                     # Quoting problems here - using eval "$c" doesn't help.
914                     s=$($c)
915                     [ $? -eq 0 ] || {
916                         rm -f $tmp
917                         die "Could not execute command $c"
918                     }
919                 fi
920             fi
921
922             # escape some pesky chars
923             # This first one can be too slow if done using a bash
924             # variable pattern subsitution.
925             s=$(echo -n "$s" | tr '\n' '\001' | sed -e 's/\o001/\\n/g')
926             s=${s//#/\\#}
927             s=${s//&/\\&}
928             echo "s#${delimiter}${v}${delimiter}#${s}#g"
929         done > $tmp
930
931         # Get the in-place sed to make a backup of the old file.
932         # Remove the backup if it is the same as the resulting file -
933         # this acts as a flag to the caller that no changes were made.
934         sed -i.old -f $tmp "$tmp_out"
935         if cmp -s "${tmp_out}.old" "$tmp_out" ; then
936             rm -f "${tmp_out}.old"
937         fi
938
939         rm -f $tmp
940 )}
941
942 check_command() {
943     which $1 > /dev/null || die "Please install $1 to continue"
944 }
945
946 # Set a variable if it isn't already set.  This allows environment
947 # variables to override default config settings.
948 defconf() {
949     local v="$1"
950     local e="$2"
951
952     [ "${!v+x}" ] || eval "$v=\"$e\""
953 }
954
955 load_config () {
956     local i
957
958     for i in "${installdir}/config.d/"*.defconf ; do
959         . "$i"
960     done
961 }
962
963 # Print the list of config variables defined in config.d/.
964 get_config_options () {( # sub-shell for local declaration of defconf()
965         local options=
966         defconf() { options="$options $1" ; }
967         load_config
968         echo $options
969 )}
970
971 # Produce a list of long options, suitable for use with getopt, that
972 # represent the config variables defined in config.d/.
973 getopt_config_options () {
974     local x=$(get_config_options | tr 'A-Z_' 'a-z-')
975     echo "${x// /:,}:"
976 }
977
978 # Unconditionally set the config variable associated with the given
979 # long option.
980 setconf_longopt () {
981     local longopt="$1"
982     local e="$2"
983
984     local v=$(echo "${longopt#--}" | tr 'a-z-' 'A-Z_')
985     # unset so defconf will set it
986     eval "unset $v"
987     defconf "$v" "$e"
988 }
989
990 # Dump all of the current config variables.
991 dump_config() {
992     local o
993     for o in $(get_config_options) ; do
994         echo "${o}=\"${!o}\""
995     done
996     exit 0
997 }
998
999 # $COLUMNS is set in interactive bash shells.  It probably isn't set
1000 # in this shell, so let's set it if it isn't.
1001 : ${COLUMNS:=$(stty size 2>/dev/null | sed -e 's@.* @@')}
1002 : ${COLUMNS:=80}
1003 export COLUMNS
1004
1005 # Print text assuming it starts after other text in $startcol and
1006 # needs to wrap before $COLUMNS - 2.  Subsequent lines start at $startcol.
1007 # Long "words" will extend past $COLUMNS - 2.
1008 fill_text() {
1009     local startcol="$1"
1010     local text="$2"
1011
1012     local width=$(($COLUMNS - 2 - $startcol))
1013     [ $width -lt 0 ] && width=$((78 - $startcol))
1014
1015     local out=""
1016
1017     local padding
1018     if [ $startcol -gt 0 ] ; then
1019         padding=$(printf "\n%${startcol}s" " ")
1020     else
1021         padding="
1022 "
1023     fi
1024
1025     while [ -n "$text" ] ; do
1026         local orig="$text"
1027
1028         # If we already have output then arrange padding on the next line.
1029         [ -n "$out" ] && out="${out}${padding}"
1030
1031         # Break the text at $width.
1032         out="${out}${text:0:${width}}"
1033         text="${text:${width}}"
1034
1035         # If we have left over text then the line break may be ugly,
1036         # so let's check and try to break it on a space.
1037         if [ -n "$text" ] ; then
1038             # The 'x's stop us producing a special character like '(',
1039             # ')' or '!'.  Yuck - there must be a better way.
1040             if [ "x${text:0:1}" != "x " -a "x${text: -1:1}" != "x " ] ; then
1041                 # We didn't break on a space.  Arrange for the
1042                 # beginning of the broken "word" to appear on the next
1043                 # line but not if it will make us loop infinitely.
1044                 if [ "${orig}" != "${out##* }${text}" ] ; then
1045                     text="${out##* }${text}"
1046                     out="${out% *}"
1047                 else
1048                     # Hmmm, doing that would make us loop, so add the
1049                     # rest of the word from the remainder of the text
1050                     # to this line and let it extend past $COLUMNS - 2.
1051                     out="${out}${text%% *}"
1052                     if [ "${text# *}" != "$text" ] ; then
1053                         # Remember the text after the next space for next time.
1054                         text="${text# *}"
1055                     else
1056                         # No text after next space.
1057                         text=""
1058                     fi
1059                 fi
1060             else
1061                 # We broke on a space.  If it will be at the beginning
1062                 # of the next line then remove it.
1063                 text="${text# }"
1064             fi
1065         fi
1066     done
1067
1068     echo "$out"
1069 }
1070
1071 # Display usage text, trying these approaches in order.
1072 # 1. See if it all fits on one line before $COLUMNS - 2.
1073 # 2. See if splitting before the default value and indenting it
1074 #    to $startcol means that nothing passes $COLUMNS - 2.
1075 # 3. Treat the message and default value as a string and just us fill_text()
1076 #    to format it. 
1077 usage_display_text () {
1078     local startcol="$1"
1079     local desc="$2"
1080     local default="$3"
1081     
1082     local width=$(($COLUMNS - 2 - $startcol))
1083     [ $width -lt 0 ] && width=$((78 - $startcol))
1084
1085     default="(default \"$default\")"
1086
1087     if [ $((${#desc} + 1 + ${#default})) -le $width ] ; then
1088         echo "${desc} ${default}"
1089     else
1090         local padding=$(printf "%${startcol}s" " ")
1091
1092         if [ ${#desc} -lt $width -a ${#default} -lt $width ] ; then
1093             echo "$desc"
1094             echo "${padding}${default}"
1095         else
1096             fill_text $startcol "${desc} ${default}"
1097         fi
1098     fi
1099 }
1100
1101 # Display usage information for long config options.
1102 usage_smart_display () {( # sub-shell for local declaration of defconf()
1103         local startcol=33
1104
1105         defconf() {
1106             local local longopt=$(echo "$1" | tr 'A-Z_' 'a-z-')
1107
1108             printf "     --%-25s " "${longopt}=${3}"
1109
1110             usage_display_text $startcol "$4" "$2"
1111         }
1112
1113         "$@"
1114 )}
1115
1116
1117 # Display usage information for long config options.
1118 usage_config_options (){
1119     usage_smart_display load_config
1120 }
1121
1122 list_releases () {
1123     local releases=$(cd $installdir/releases && echo *.release)
1124     releases="${releases//.release}"
1125     releases="${releases// /\", \"}"
1126     echo "\"$releases\""
1127 }
1128
1129 ######################################################################
1130
1131 post_config_hooks=
1132
1133 ######################################################################
1134
1135 load_config
1136
1137 ############################
1138 # parse command line options
1139 long_opts=$(getopt_config_options)
1140 getopt_output=$(getopt -n autocluster -o "c:e:E:xh" -l help,dump,with-release: -l "$long_opts" -- "$@")
1141 [ $? != 0 ] && usage
1142
1143 use_default_config=true
1144
1145 # We do 2 passes of the options.  The first time we just handle usage
1146 # and check whether -c is being used.
1147 eval set -- "$getopt_output"
1148 while true ; do
1149     case "$1" in
1150         -c) shift 2 ; use_default_config=false ;;
1151         -e) shift 2 ;;
1152         -E) shift 2 ;;
1153         --) shift ; break ;;
1154         --with-release) shift 2 ;; # Don't set use_default_config=false!!!
1155         --dump|-x) shift ;;
1156         -h|--help) usage ;; # Usage should be shown here for real defaults.
1157         --*) shift 2 ;; # Assume other long opts are valid and take an arg.
1158         *) usage ;; # shouldn't happen, so this is reasonable.
1159     esac
1160 done
1161
1162 config="./config"
1163 $use_default_config && [ -r "$config" ] && . "$config"
1164
1165 eval set -- "$getopt_output"
1166
1167 while true ; do
1168     case "$1" in
1169         # force at least ./local_file to avoid accidental file from $PATH
1170         -c) . "$(dirname $2)/$(basename $2)" ; shift 2 ;;
1171         -e) no_sanity=1 ; run_hooks post_config_hooks ; eval "$2" ; exit ;;
1172         -E) eval "$2" ; shift 2 ;;
1173         -x) set -x; shift ;;
1174         --dump) no_sanity=1 ; run_hooks post_config_hooks ; dump_config ;;
1175         --) shift ; break ;;
1176         -h|--help) usage ;; # Redundant.
1177         --*)
1178             # Putting --opt1|opt2|... into a variable and having case
1179             # match against it as a pattern doesn't work.  The | is
1180             # part of shell syntax, so we need to do this.  Look away
1181             # now to stop your eyes from bleeding! :-)
1182             x=",${long_opts}" # Now each option is surrounded by , and :
1183             if [ "$x" != "${x#*,${1#--}:}" ] ; then
1184                 # Our option, $1, surrounded by , and : was in $x, so is legal.
1185                 setconf_longopt "$1" "$2"; shift 2
1186             else
1187                 usage
1188             fi
1189             ;;
1190         *) usage ;; # shouldn't happen, so this is reasonable.
1191     esac
1192 done
1193
1194 run_hooks post_config_hooks 
1195
1196 # catch errors
1197 set -e
1198 set -E
1199 trap 'es=$?; 
1200       echo ERROR: failed in function \"${FUNCNAME}\" at line ${LINENO} of ${BASH_SOURCE[0]} with code $es; 
1201       exit $es' ERR
1202
1203 # check for needed programs 
1204 check_command expect
1205
1206 [ $# -lt 1 ] && usage
1207
1208 command="$1"
1209 shift
1210
1211 case $command in
1212     create)
1213         type=$1
1214         shift
1215         case $type in
1216             base)
1217                 [ $# != 0 ] && usage
1218                 create_base
1219                 ;;
1220             cluster)
1221                 [ $# != 1 ] && usage
1222                 create_cluster "$1"
1223                 ;;
1224             node)
1225                 [ $# != 2 ] && usage
1226                 create_one_node "$1" "$2"
1227                 ;;
1228             *)
1229                 usage;
1230                 ;;
1231         esac
1232         ;;
1233     mount)
1234         [ $# != 1 ] && usage
1235         diskimage mount "$1"
1236         ;;
1237     unmount|umount)
1238         [ $# != 0 ] && usage
1239         diskimage unmount
1240         ;;
1241     bootbase)
1242         boot_base;
1243         ;;
1244     testproxy)
1245         test_proxy;
1246         ;;
1247     *)
1248         usage;
1249         ;;
1250 esac