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