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