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