-
Notifications
You must be signed in to change notification settings - Fork 3
/
startup.sh
2249 lines (1891 loc) · 98.6 KB
/
startup.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# ------------------------------------------------------------------------
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Description: Google Cloud Platform - SAP Deployment Functions
#
# Version: 2.0.2023021506521676472763
# Build Hash: cac5701db924b1e8b7edb29781b8a989573cc7e4
#
# ------------------------------------------------------------------------
## Check to see if a custom script path was provided by the template
if [[ "${1}" ]]; then
readonly DEPLOY_URL="${1}"
else
readonly DEPLOY_URL="https://storage.googleapis.com/cloudsapdeploy/deploymentmanager/202302150652/dm-templates"
fi
##########################################################################
## Start constants
##########################################################################
TEMPLATE_NAME="SAP_HANA_HA_PRIMARY"
##########################################################################
## Start includes
##########################################################################
set +e
main::set_boot_parameters() {
main::errhandle_log_info 'Checking boot paramaters'
## disable selinux
if [[ -e /etc/sysconfig/selinux ]]; then
main::errhandle_log_info "--- Disabling SELinux"
sed -ie 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux
fi
if [[ -e /etc/selinux/config ]]; then
main::errhandle_log_info "--- Disabling SELinux"
sed -ie 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
fi
## work around for LVM boot where LVM volues are not started on certain SLES/RHEL versions
if [[ -e /etc/sysconfig/lvm ]]; then
sed -ie 's/LVM_ACTIVATED_ON_DISCOVERED="disable"/LVM_ACTIVATED_ON_DISCOVERED="enable"/g' /etc/sysconfig/lvm
fi
## Configure cstates and huge pages
if ! grep -q cstate /etc/default/grub ; then
main::errhandle_log_info "--- Update grub"
cmdline=$(grep GRUB_CMDLINE_LINUX_DEFAULT /etc/default/grub | head -1 | sed 's/GRUB_CMDLINE_LINUX_DEFAULT=//g' | sed 's/\"//g')
cp /etc/default/grub /etc/default/grub.bak
grep -v GRUBLINE_LINUX_DEFAULT /etc/default/grub.bak >/etc/default/grub
if [[ $LINUX_DISTRO == "RHEL" ]] && [[ $LINUX_MAJOR_VERSION -ge 8 ]] && [[ $LINUX_MINOR_VERSION -ge 4 ]]; then
# Enable tsx explicitly - SAP note 2777782
echo "GRUB_CMDLINE_LINUX_DEFAULT=\"${cmdline} transparent_hugepage=never intel_idle.max_cstate=1 processor.max_cstate=1 intel_iommu=off tsx=on\"" >>/etc/default/grub
else
echo "GRUB_CMDLINE_LINUX_DEFAULT=\"${cmdline} transparent_hugepage=never intel_idle.max_cstate=1 processor.max_cstate=1 intel_iommu=off\"" >>/etc/default/grub
echo "GRUB_ENABLE_LINUX_LABEL=true" >>/etc/default/grub
echo "GRUB_DEVICE=\"LABEL=ROOT\"" >>/etc/default/grub
fi
grub2-mkconfig -o /boot/grub2/grub.cfg
echo "${HOSTNAME}" >/etc/hostname
main::errhandle_log_info '--- Parameters updated. Rebooting'
reboot
exit 0
fi
}
main::errhandle_log_info() {
local log_entry=${1}
echo "INFO - ${log_entry}"
if [[ -n "${GCLOUD}" ]]; then
timeout 10 ${GCLOUD} --quiet logging write "${HOSTNAME}" "${HOSTNAME} Deployment \"${log_entry}\"" --severity=INFO
fi
}
main::errhandle_log_warning() {
local log_entry=${1}
if [[ -z "${deployment_warnings}" ]]; then
deployment_warnings=1
else
deployment_warnings=$((deployment_warnings +1))
fi
echo "WARNING - ${log_entry}"
if [[ -n "${GCLOUD}" ]]; then
${GCLOUD} --quiet logging write "${HOSTNAME}" "${HOSTNAME} Deployment \"${log_entry}\"" --severity=WARNING
fi
}
main::errhandle_log_error() {
local log_entry=${1}
echo "ERROR - Deployment Exited - ${log_entry}"
if [[ -n "${GCLOUD}" ]]; then
${GCLOUD} --quiet logging write "${HOSTNAME}" "${HOSTNAME} Deployment \"${log_entry}\"" --severity=ERROR
${GCLOUD} --quiet logging write "${HOSTNAME}" "${HOSTNAME} Deployment \"ERROR - Deployment Exited\"" --severity=ERROR
fi
main::complete error
}
main::get_os_version() {
if grep SLES /etc/os-release; then
readonly LINUX_DISTRO="SLES"
elif grep -q "Red Hat" /etc/os-release; then
readonly LINUX_DISTRO="RHEL"
else
main::errhandle_log_warning "Unsupported Linux distribution. Only SLES and RHEL are supported."
fi
readonly LINUX_VERSION=$(grep VERSION_ID /etc/os-release | awk -F '\"' '{ print $2 }')
readonly LINUX_MAJOR_VERSION=$(echo $LINUX_VERSION | awk -F '.' '{ print $1 }')
readonly LINUX_MINOR_VERSION=$(echo $LINUX_VERSION | awk -F '.' '{ print $2 }')
}
main::config_ssh() {
ssh-keygen -m PEM -q -N "" < /dev/zero
sed -ie 's/PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config
service sshd restart
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
/usr/sbin/rcgoogle-accounts-daemon restart || /usr/sbin/rcgoogle-guest-agent restart
}
main::install_ssh_key(){
local host=${1}
local host_zone
host_zone=$(${GCLOUD} compute instances list --filter="name=('${host}')" --format "value(zone)")
main::errhandle_log_info "Installing ${HOSTNAME} SSH key on ${host}"
local count=0
local max_count=10
while ! ${GCLOUD} --quiet compute instances add-metadata "${host}" --metadata "ssh-keys=root:$(cat ~/.ssh/id_rsa.pub)" --zone "${host_zone}"; do
count=$((count +1))
if [ ${count} -gt ${max_count} ]; then
main::errhandle_log_error "Failed to install ${HOSTNAME} SSH key on ${host}, aborting installation."
else
main::errhandle_log_info "Failed to install ${HOSTNAME} SSH key on ${host}, trying again in 5 seconds."
sleep 5s
fi
done
}
main::install_packages() {
main::errhandle_log_info 'Installing required operating system packages'
## SuSE work around to avoid a startup race condition
if [[ ${LINUX_DISTRO} = "SLES" ]]; then
local count=0
## check if SuSE repos are registered
while [[ $(find /etc/zypp/repos.d/ -maxdepth 1 | wc -l) -lt 2 ]]; do
main::errhandle_log_info "--- SuSE repositories are not registered. Waiting 60 seconds before trying again"
sleep 60s
count=$((count +1))
if [ ${count} -gt 30 ]; then
main::errhandle_log_error "SuSE repositories didn't register within an acceptable time. If you are using BYOS, ensure you login to the system and apply the SuSE license within 30 minutes after deployment. If you are using a VM without external IP make sure you set up a NAT gateway to provide internet access."
fi
done
sleep 10s
## check if zypper is still running
while pgrep zypper; do
errhandle_log_info "--- zypper is still running. Waiting 10 seconds before attempting to continue"
sleep 10s
done
fi
## packages to install
local sles_packages="libssh2-1 libopenssl0_9_8 libopenssl1_0_0 tuned krb5-32bit unrar SAPHanaSR SAPHanaSR-doc pacemaker numactl csh python-pip python-pyasn1-modules ndctl python-oauth2client python-oauth2client-gce python-httplib2 python3-httplib2 python3-google-api-python-client python-requests python-google-api-python-client libgcc_s1 libstdc++6 libatomic1 sapconf saptune nvme-cli"
local rhel_packages="unar.x86_64 tuned-profiles-sap-hana tuned-profiles-sap-hana-2.7.1-3.el7_3.3 resource-agents-sap-hana.x86_64 compat-sap-c++-6 numactl-libs.x86_64 libtool-ltdl.x86_64 nfs-utils.x86_64 pacemaker pcs lvm2.x86_64 compat-sap-c++-5.x86_64 csh autofs ndctl compat-sap-c++-9 compat-sap-c++-10 libatomic unzip libsss_autofs python2-pip langpacks-en langpacks-de glibc-all-langpacks libnsl libssh2 wget lsof jq"
## install packages
if [[ ${LINUX_DISTRO} = "SLES" ]]; then
for package in ${sles_packages}; do # Bash only splits unquoted.
local count=0;
local max_count=3;
while ! sudo ZYPP_LOCK_TIMEOUT=60 zypper in -y "${package}"; do
count=$((count +1))
sleep 3
if [[ ${count} -gt ${max_count} ]]; then
main::errhandle_log_warning "Failed to install ${package}, continuing installation."
break
fi
done
done
# making sure we refresh the bash env
. /etc/bash.bashrc
# boto.cfg has spaces in 15sp2, getting rid of them (b/172181835)
if [[ $(tail -n 1 /etc/boto.cfg) == " ca_certificates_file = system" ]]; then
sed -i 's/^[ \t]*//' /etc/boto.cfg
fi
elif [[ ${LINUX_DISTRO} = "RHEL" ]]; then
for package in $rhel_packages; do
local count=0;
local max_count=3;
while ! yum -y install "${package}"; do
count=$((count +1))
sleep 3
if [[ ${count} -gt ${max_count} ]]; then
main::errhandle_log_warning "Failed to install ${package}, continuing installation."
break
fi
done
done
# check for python interpreter - RHEL 8 does not have "python"
main::errhandle_log_info 'Checking for python interpreter'
if [[ ! -f "/bin/python" ]] && [[ -f "/usr/bin/python2" ]]; then
main::errhandle_log_info 'Updating alternatives for python to python2.7'
alternatives --set python /usr/bin/python2
fi
# make sure latest packages are installed (https://cloud.google.com/solutions/sap/docs/sap-hana-ha-config-rhel#install_the_cluster_agents_on_both_nodes)
main::errhandle_log_info 'Applying updates to packages on system'
if ! yum update -y; then
main::errhandle_log_warning 'Applying updates to packages on system failed ("yum update -y"). Logon to the VM to investigate the issue.'
fi
fi
main::errhandle_log_info 'Install of required operating system packages complete'
}
#######################################
# Finds and returns (via 'echo') first device in $by_id_dir that contains
# $searchstring. Works with SCSI (/dev/sdX) and NVME (/dev/nvmeX) devices.
#
# Input: searchstring
# Output: device name
#
# Examples for NVME and SCSI:
# main::get_device_by_id backup
# /dev/nvme0n3 (NVME)
# /dev/sdc (SCSI)
#######################################
main::get_device_by_id() {
local searchstring=${1}
local by_id_dir="/dev/disk/by-id"
local device_name=""
local nvme_script='/usr/lib/udev/google_nvme_id'
device_name=$(readlink -f ${by_id_dir}/$(ls ${by_id_dir} | grep google | grep -m 1 "${searchstring}"))
if [ ${device_name} != ${by_id_dir} ]; then
echo ${device_name}
return
fi
# TODO(franklegler): Remove workaround once b/249894430 is resolved
# On M3 with SLES devices are not yet listed by their name (b/249894430)
# Workaround: Run script to create symlinks ()
if [[ -b /dev/nvme0n1 ]] && [[ -f ${nvme_script} ]]; then
udevadm control --reload-rules && udevadm trigger # b/249894430#comment11
for i in $(ls /dev/nvme0n*); do # b/249894430#comment13
$nvme_script -d $i -s
done
device_name=$(readlink -f ${by_id_dir}/$(ls ${by_id_dir} | grep google | grep -m 1 "${searchstring}"))
if [ ${device_name} != ${by_id_dir} ]; then
echo ${device_name}
return
fi
fi
# End workaround
main::errhandle_log_error "No device containing '${searchstring}' found."
}
main::create_vg() {
local device=${1}
local volume_group=${2}
if [[ -b "$device" ]]; then
main::errhandle_log_info "--- Creating physical volume group ${device}"
pvcreate "${device}"
main::errhandle_log_info "--- Creating volume group ${volume_group} on ${device}"
vgcreate "${volume_group}" "${device}"
/sbin/vgchange -ay
else
main::errhandle_log_error "Unable to access ${device}"
fi
}
main::create_filesystem() {
local mount_point=${1}
local device=${2}
local filesystem=$3
local is_optional_file_system=${4}
if [[ -h /dev/disk/by-id/google-"${HOSTNAME}"-"${device}" ]]; then
main::errhandle_log_info "--- ${mount_point}"
pvcreate /dev/disk/by-id/google-"${HOSTNAME}"-"${device}"
vgcreate vg_"${device}" /dev/disk/by-id/google-"${HOSTNAME}"-"${device}"
lvcreate -l 100%FREE -n vol vg_"${device}"
main::format_mount "${mount_point}" /dev/vg_"${device}"/vol "${filesystem}"
if [[ "${mount_point}" != "swap" ]]; then
main::check_mount "${mount_point}"
fi
elif [[ ${is_optional_file_system:-"notOptional"} == "optional" ]]; then
main::errhandle_log_warning "Unable to create optional file system ${filesystem}."
else
main::errhandle_log_error "Unable to access ${device}"
fi
}
main::check_mount() {
local mount_point=${1}
local on_error=${2}
## check /etc/mtab to see if the filesystem is mounted
if ! grep -q "${mount_point}" /etc/mtab; then
case "${on_error}" in
error)
main::errhandle_log_error "Unable to mount ${mount_point}"
;;
info)
main::errhandle_log_info "Unable to mount ${mount_point}"
;;
warning)
main::errhandle_log_warning "Unable to mount ${mount_point}"
;;
*)
main::errhandle_log_error "Unable to mount ${mount_point}"
esac
fi
}
main::format_mount() {
local mount_point=${1}
local device=${2}
local filesystem=${3}
local options=${4}
if [[ -b "$device" ]]; then
if [[ "${filesystem}" = "swap" ]]; then
echo "${device} none ${filesystem} defaults,nofail 0 0" >>/etc/fstab
mkswap "${device}"
swapon "${device}"
else
main::errhandle_log_info "--- Creating ${mount_point}"
mkfs -t "${filesystem}" "${device}"
mkdir -p "${mount_point}"
if [[ ! "${options}" = "tmp" ]]; then
echo "${device} ${mount_point} ${filesystem} defaults,nofail,logbsize=256k 0 2" >>/etc/fstab
mount -a
else
mount -t "${filesystem}" "${device}" "${mount_point}"
fi
main::check_mount "${mount_point}"
fi
else
main::errhandle_log_error "Unable to access ${device}"
fi
}
main::get_settings() {
main::errhandle_log_info "Fetching GCE Instance Settings"
## set current zone as the default zone
readonly CLOUDSDK_COMPUTE_ZONE=$(main::get_metadata "http://169.254.169.254/computeMetadata/v1/instance/zone" | cut -d'/' -f4)
export CLOUDSDK_COMPUTE_ZONE
main::errhandle_log_info "--- Instance determined to be running in ${CLOUDSDK_COMPUTE_ZONE}. Setting this as the default zone"
readonly VM_REGION=${CLOUDSDK_COMPUTE_ZONE::-2}
## get instance type & details
readonly VM_INSTTYPE=$(main::get_metadata http://169.254.169.254/computeMetadata/v1/instance/machine-type | cut -d'/' -f4)
main::errhandle_log_info "--- Instance type determined to be ${VM_INSTTYPE}"
readonly VM_CPUPLAT=$(main::get_metadata "http://169.254.169.254/computeMetadata/v1/instance/cpu-platform")
main::errhandle_log_info "--- Instance is determined to be part on CPU Platform ${VM_CPUPLAT}"
readonly VM_CPUCOUNT=$(grep -c processor /proc/cpuinfo)
main::errhandle_log_info "--- Instance determined to have ${VM_CPUCOUNT} cores"
readonly VM_MEMSIZE=$(free -g | grep Mem | awk '{ print $2 }')
main::errhandle_log_info "--- Instance determined to have ${VM_MEMSIZE}GB of memory"
readonly VM_PROJECT=$(main::get_metadata "http://169.254.169.254/computeMetadata/v1/project/project-id")
main::errhandle_log_info "--- VM is in project ${VM_PROJECT}"
## get network settings
readonly VM_NETWORK=$(main::get_metadata http://169.254.169.254/computeMetadata/v1/instance/network-interfaces/0/network | cut -d'/' -f4)
main::errhandle_log_info "--- Instance is determined to be part of network ${VM_NETWORK}"
readonly VM_NETWORK_FULL=$(gcloud compute instances describe "${HOSTNAME}" | grep "subnetwork:" | head -1 | grep -o 'projects.*')
readonly VM_SUBNET=$(grep -o 'subnetworks.*' <<< "${VM_NETWORK_FULL}" | cut -f2- -d"/")
main::errhandle_log_info "--- Instance is determined to be part of subnetwork ${VM_SUBNET}"
readonly VM_NETWORK_PROJECT=$(cut -d'/' -f2 <<< "${VM_NETWORK_FULL}")
main::errhandle_log_info "--- Networking is hosted in project ${VM_NETWORK_PROJECT}"
readonly VM_IP=$(main::get_metadata http://169.254.169.254/computeMetadata/v1/instance/network-interfaces/0/ip)
main::errhandle_log_info "--- Instance IP is determined to be ${VM_IP}"
# fetch all custom metadata associated with the instance
main::errhandle_log_info "Fetching GCE Instance Metadata"
local value
local key
declare -g -A VM_METADATA
local uses_secret_password
uses_secret_password="false"
for key in $(curl --fail -sH'Metadata-Flavor: Google' http://169.254.169.254/computeMetadata/v1/instance/attributes/ | grep -v ssh-keys); do
value=$(main::get_metadata "${key}")
if [[ "${key}" = *"password"* ]]; then
main::errhandle_log_info "${key} determined to be *********"
else
main::errhandle_log_info "${key} determined to be '${value}'"
fi
if [[ ${uses_secret_password} == "true" ]] && [[ "${key}" = *"password" ]]; then
continue;
fi
if [[ "${key}" = *"password_secret"* ]]; then
if [[ -z ${value} ]]; then
continue;
fi
uses_secret_password="true"
pass_key=${key::-7} # strips off _secret
secret_ret=$(${GCLOUD} secrets versions access latest --secret="${value}")
VM_METADATA[$pass_key]="${secret_ret}"
else
VM_METADATA[$key]="${value}"
fi
done
# remove startup script
if [[ -n "${VM_METADATA[startup-script]}" ]]; then
main::remove_metadata startup-script
fi
# remove metrics info
if [[ -n "${VM_METADATA[template-type]}" ]]; then
main::remove_metadata template-type
else
VM_METADATA[template-type]="UNKNOWN"
fi
## if the startup script has previously completed, abort execution.
if [[ -n "${VM_METADATA[status]}" ]]; then
main::errhandle_log_info "Startup script has previously been run. Taking no further action."
exit 0
fi
}
main::create_static_ip() {
## attempt to reserve the current IP address as static
if [[ "$VM_NETWORK_PROJECT" == "${VM_PROJECT}" ]]; then
main::errhandle_log_info "Creating static IP address ${VM_IP} in subnetwork ${VM_SUBNET}"
${GCLOUD} --quiet compute --project "${VM_NETWORK_PROJECT}" addresses create "${HOSTNAME}" --addresses "${VM_IP}" --region "${VM_REGION}" --subnet "${VM_SUBNET}"
else
main::errhandle_log_info "Creating static IP address ${VM_IP} in shared VPC ${VM_NETWORK_PROJECT}"
${GCLOUD} --quiet compute --project "${VM_PROJECT}" addresses create "${HOSTNAME}" --addresses "${VM_IP}" --region "${VM_REGION}" --subnet "${VM_NETWORK_FULL}"
fi
}
main::remove_metadata() {
local key=${1}
${GCLOUD} --quiet compute instances remove-metadata "${HOSTNAME}" --keys "${key}"
}
main::install_gsdk() {
local install_location=${1}
local rc
if [[ -e /usr/bin/gsutil ]]; then
# if SDK is installed, link to the standard location for backwards compatibility
if [[ ! -d /usr/local/google-cloud-sdk/bin ]]; then
mkdir -p /usr/local/google-cloud-sdk/bin
fi
if [[ ! -e /usr/local/google-cloud-sdk/bin/gsutil ]]; then
ln -s /usr/bin/gsutil /usr/local/google-cloud-sdk/bin/gsutil
fi
if [[ ! -e /usr/local/google-cloud-sdk/bin/gcloud ]]; then
ln -s /usr/bin/gcloud /usr/local/google-cloud-sdk/bin/gcloud
fi
elif [[ ! -d "${install_location}/google-cloud-sdk" ]]; then
# b/188946979
if [[ "${LINUX_DISTRO}" = "SLES" && "${LINUX_MAJOR_VERSION}" = "12" ]]; then
export CLOUDSDK_PYTHON=/usr/bin/python
fi
bash <(curl -s https://dl.google.com/dl/cloudsdk/channels/rapid/install_google_cloud_sdk.bash) --disable-prompts --install-dir="${install_location}" >/dev/null
rc=$?
if [[ "${rc}" -eq 0 ]]; then
main::errhandle_log_info "Installed Google SDK in ${install_location}"
else
main::errhandle_log_error "Google SDK not correctly installed. Aborting installation."
fi
if [[ ${LINUX_DISTRO} = "SLES" ]]; then
update-alternatives --install /usr/bin/gsutil gsutil /usr/local/google-cloud-sdk/bin/gsutil 1 --force
update-alternatives --install /usr/bin/gcloud gcloud /usr/local/google-cloud-sdk/bin/gcloud 1 --force
fi
fi
readonly GCLOUD="/usr/bin/gcloud"
readonly GSUTIL="/usr/bin/gsutil"
## set default python version for Cloud SDK in SLES, move from 3.4 to 2.7
# b/188946979 - only applicable to SLES12
if [[ ${LINUX_DISTRO} = "SLES" && "${LINUX_MAJOR_VERSION}" = "12" ]]; then
update-alternatives --install /usr/bin/gsutil gsutil /usr/local/google-cloud-sdk/bin/gsutil 1 --force
update-alternatives --install /usr/bin/gcloud gcloud /usr/local/google-cloud-sdk/bin/gcloud 1 --force
export CLOUDSDK_PYTHON=/usr/bin/python
# b/189944327 - to avoid gcloud/gsutil fails when using Python3.4 on SLES12
if ! grep -q CLOUDSDK_PYTHON /etc/profile; then
echo "export CLOUDSDK_PYTHON=/usr/bin/python" | tee -a /etc/profile
fi
if ! grep -q CLOUDSDK_PYTHON /etc/environment; then
echo "export CLOUDSDK_PYTHON=/usr/bin/python" | tee -a /etc/environment
fi
fi
## run an instances list to ensure the software is up to date
${GCLOUD} --quiet beta compute instances list >/dev/null
}
main::check_default() {
local default=${1}
local current=${2}
if [[ -z ${current} ]]; then
echo "${default}"
else
echo "${current}"
fi
}
main::get_metadata() {
local key=${1}
local value
if [[ ${key} = *"169.254.169.254/computeMetadata"* ]]; then
value=$(curl --fail -sH'Metadata-Flavor: Google' "${key}")
else
value=$(curl --fail -sH'Metadata-Flavor: Google' http://169.254.169.254/computeMetadata/v1/instance/attributes/"${key}")
fi
echo "${value}"
}
main::update-metadata() {
local key="${1}"
local value="${2}"
local count=0
local max_count=10
while ! ${GCLOUD} --quiet compute instances add-metadata "${HOSTNAME}" --metadata "${key}=${value}" --zone "${CLOUDSDK_COMPUTE_ZONE}"; do
count=$((count +1))
if [ ${count} -gt ${max_count} ]; then
main::errhandle_log_info "Failed to update metadata key=${key}, value=${value}, continuing."
break
else
main::errhandle_log_info "Failed to update metadata key=${key}, value=${value}, trying again in 5 seconds. [Attempt ${count}/${max_count}"
sleep 5s
fi
done
}
main::complete() {
local on_error=${1}
## update instance metadata with status
if [[ -n "${on_error}" ]]; then
main::update-metadata "status" "failed_or_error"
metrics::send_metric -s "ERROR" -e "1"
elif [[ -n "${deployment_warnings}" ]]; then
main::errhandle_log_info "INSTANCE DEPLOYMENT COMPLETE"
main::update-metadata "status" "completed_with_warnings"
metrics::send_metric -s "ERROR" -e "2"
else
main::errhandle_log_info "INSTANCE DEPLOYMENT COMPLETE"
main::update-metadata "status" "completed"
metrics::send_metric -s "CONFIGURED"
fi
## prepare advanced logs
if [[ "${VM_METADATA[sap_deployment_debug]}" = "True" ]]; then
mkdir -p /root/.deploy
main::errhandle_log_info "--- Debug mode is turned on. Preparing additional logs"
env > /root/.deploy/"${HOSTNAME}"_debug_env.log
grep startup /var/log/messages > /root/.deploy/"${HOSTNAME}"_debug_startup_script_output.log
tar -czvf /root/.deploy/"${HOSTNAME}"_deployment_debug.tar.gz -C /root/.deploy/ .
main::errhandle_log_info "--- Debug logs stored in /root/.deploy/"
## Upload logs to GCS bucket & display complete message
if [ -n "${VM_METADATA[sap_hana_deployment_bucket]}" ]; then
main::errhandle_log_info "--- Uploading logs to Google Cloud Storage bucket"
${GSUTIL} -q cp /root/.deploy/"${HOSTNAME}"_deployment_debug.tar.gz gs://"${VM_METADATA[sap_hana_deployment_bucket]}"/logs/
fi
fi
## Run custom post deployment script
if [[ -n "${VM_METADATA[post_deployment_script]}" ]]; then
main::errhandle_log_info "--- Running custom post deployment script - ${VM_METADATA[post_deployment_script]}"
if [[ "${VM_METADATA[post_deployment_script]:0:8}" = "https://" ]] || [[ "${VM_METADATA[post_deployment_script]:0:7}" = "http://" ]]; then
source /dev/stdin <<< "$(curl -s "${VM_METADATA[post_deployment_script]}")"
elif [[ "${VM_METADATA[post_deployment_script]:0:5}" = "gs://" ]]; then
source /dev/stdin <<< "$("${GSUTIL}" cat "${VM_METADATA[post_deployment_script]}")"
else
main::errhandle_log_warning "--- Unknown post deployment script. URL must begin with https:// http:// or gs://"
fi
fi
if [[ -z "${deployment_warnings}" ]]; then
main::errhandle_log_info "--- Finished"
else
main::errhandle_log_warning "--- Finished (${deployment_warnings} warnings)"
fi
## exit sending right error code
if [[ -z "${on_error}" ]]; then
exit 0
else
exit 1
fi
}
main::send_start_metrics() {
metrics::send_metric -s "STARTED"
metrics::send_metric -s "TEMPLATEID"
}
main::install_ops_agent() {
if [[ ! "${VM_METADATA[install_cloud_ops_agent]}" == "false" ]]; then
main::errhandle_log_info "Installing Google Ops Agent"
curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
sudo bash add-google-cloud-ops-agent-repo.sh --also-install
fi
}
main::install_monitoring_agent() {
local msg1
local msg2
main::errhandle_log_info "Installing SAP Agent"
if [ "${LINUX_DISTRO}" = "SLES" ]; then
main::errhandle_log_info "Installing agent for SLES"
# SLES
zypper addrepo --gpgcheck-allow-unsigned-package --refresh https://packages.cloud.google.com/yum/repos/google-cloud-sap-agent-sles$(grep "VERSION_ID=" /etc/os-release | cut -d = -f 2 | tr -d '"' | cut -d . -f 1)-\$basearch google-cloud-sap-agent
rpm --import https://packages.cloud.google.com/yum/doc/yum-key.gpg
if timeout 300 zypper -n --no-gpg-checks install "google-cloud-sap-agent"; then
main::errhandle_log_info "Finished installation SAP Agent"
else
local msg1="SAP Agent did not install correctly."
local msg2="Try to install it manually."
main::errhandle_log_info "${msg1} ${msg2}"
fi
elif [ "${LINUX_DISTRO}" = "RHEL" ]; then
# RHEL
main::errhandle_log_info "Installing agent for RHEL"
tee /etc/yum.repos.d/google-cloud-sap-agent.repo << EOM
[google-cloud-sap-agent]
name=Google Cloud Agent for SAP
baseurl=https://packages.cloud.google.com/yum/repos/google-cloud-sap-agent-el$(cat /etc/redhat-release | cut -d . -f 1 | tr -d -c 0-9)-\$basearch
enabled=1
gpgcheck=0
repo_gpgcheck=0
EOM
if timeout 300 yum install -y "google-cloud-sap-agent"; then
main::errhandle_log_info "Finished installation SAP Agent"
else
local msg1="SAP Agent did not install correctly."
local msg2="Try to install it manually."
main::errhandle_log_info "${msg1} ${msg2}"
fi
fi
set +e
}
hdb::calculate_volume_sizes() {
main::errhandle_log_info "Calculating disk volume sizes"
hana_log_size=$((VM_MEMSIZE/2))
if [[ ${hana_log_size} -gt 512 ]]; then
hana_log_size=512
fi
hana_data_size=$(((VM_MEMSIZE*12)/10))
# check if node is a standby or not
if [[ "${VM_METADATA[hana_node_type]}" = "secondary" ]]; then
hana_shared_size=0
else
# determine hana shared size based on memory size
hana_shared_size=${VM_MEMSIZE}
if [[ ${hana_shared_size} -gt 1024 ]]; then
hana_shared_size=1024
fi
# increase shared size if there are more than 3 nodes
if [[ ${VM_METADATA[sap_hana_scaleout_nodes]} -gt 3 ]]; then
hana_shared_size_multi=$(/usr/bin/python -c "print (int(round(${VM_METADATA[sap_hana_scaleout_nodes]} /4 + 0.5)))")
hana_shared_size=$((hana_shared_size * hana_shared_size_multi))
fi
fi
## if there is enough space (i.e, multi_sid enabled or if 208GB instances) then double the volume sizes
hana_pdssd_size=$(($(lsblk --nodeps --bytes --noheadings --output SIZE $DEVICE_DATA_LOG)/1024/1024/1024))
hana_pdssd_size_x2=$(((hana_data_size+hana_log_size)*2 +hana_shared_size))
if [[ ${hana_pdssd_size} -gt ${hana_pdssd_size_x2} ]]; then
main::errhandle_log_info "--- Determined double volume sizes are required"
main::errhandle_log_info "--- Determined minimum data volume requirement to be $((hana_data_size*2))"
hana_log_size=$((hana_log_size*2))
else
main::errhandle_log_info "--- Determined minimum data volume requirement to be ${hana_data_size}"
main::errhandle_log_info "--- Determined log volume requirement to be ${hana_log_size}"
main::errhandle_log_info "--- Determined shared volume requirement to be ${hana_shared_size}"
fi
}
hdb::create_sap_data_log_volumes() {
main::errhandle_log_info "Building /usr/sap, /hana/data & /hana/log"
## create volume group
main::create_vg $DEVICE_DATA_LOG vg_hana
## create logical volumes
main::errhandle_log_info '--- Creating logical volumes'
lvcreate -L 32G -n sap vg_hana
lvcreate -L ${hana_log_size}G -n log vg_hana
lvcreate -l 100%FREE -n data vg_hana
## format file systems
main::format_mount /usr/sap /dev/vg_hana/sap xfs
main::format_mount /hana/data /dev/vg_hana/data xfs
main::format_mount /hana/log /dev/vg_hana/log xfs
## create base folders
mkdir -p /hana/data/"${VM_METADATA[sap_hana_sid]}" /hana/log/"${VM_METADATA[sap_hana_sid]}"
chmod 777 /hana/data/"${VM_METADATA[sap_hana_sid]}" /hana/log/"${VM_METADATA[sap_hana_sid]}"
## add 2GB swap file as per Note 1999997, point 21. Non-critical, warning on failure
main::errhandle_log_info "Attempting to add swap space"
if (( $(free -k | grep -i swap | awk '{print $2}') > 2097152 )); then
main::errhandle_log_warning "Swap space larger than recommended 2GiB. Please review."
elif (( $(free -k | grep -i swap | awk '{print $2}') > 0 )); then
main::errhandle_log_info "Non-zero swap already exists. Skipping."
else
if dd if=/dev/zero of=/swapfile bs=1048576 count=2048; then
chmod 0600 /swapfile
mkswap /swapfile
echo "/swapfile swap swap defaults 0 0" >> /etc/fstab
systemctl daemon-reload
swapon /swapfile
fi
if (( $(free -k | grep -i swap | awk '{print $2}') > 0 )); then
main::errhandle_log_info "Swap space added."
else
main::errhandle_log_warning "Swap space not added. Post-processing needed."
fi
fi
}
hdb::create_shared_volume() {
if [[ -n ${VM_METADATA[sap_hana_shared_nfs]} ]]; then
main::errhandle_log_info "NFS endpoint specified for /hana/shared. Skipping block device."
return 0
fi
main::create_vg $DEVICE_DATA_LOG vg_hana
lvcreate -L ${hana_shared_size}G -n shared vg_hana
## format and mount
main::format_mount /hana/shared /dev/vg_hana/shared xfs
}
hdb::create_backup_volume() {
if [[ -n ${VM_METADATA[sap_hana_backup_nfs]} ]]; then
main::errhandle_log_info "NFS endpoint specified for /hanabackup. Skipping block device."
return 0
fi
main::errhandle_log_info "Building /hanabackup"
## create volume group
main::create_vg $DEVICE_BACKUP vg_hanabackup
main::errhandle_log_info "--- Creating logical volume"
lvcreate -l 100%FREE -n backup vg_hanabackup
## create filesystems
main::format_mount /hanabackup /dev/vg_hanabackup/backup xfs
}
hdb::set_kernel_parameters(){
main::errhandle_log_info "Setting kernel paramaters"
# b/190863339 - pagecache_limit_mb only relevant to SLES 12
if [[ "${LINUX_DISTRO}" = "SLES" && "${LINUX_MAJOR_VERSION}" = "12" ]]; then
echo "vm.pagecache_limit_mb = 0" >> /etc/sysctl.conf
fi
{
echo "net.ipv4.tcp_slow_start_after_idle=0"
echo "kernel.numa_balancing = 0"
echo "net.ipv4.tcp_slow_start_after_idle=0"
echo "net.core.somaxconn = 4096"
echo "net.ipv4.tcp_tw_reuse = 1"
echo "net.ipv4.tcp_tw_recycle = 1"
echo "net.ipv4.tcp_timestamps = 1"
echo "net.ipv4.tcp_syn_retries = 8"
echo "net.ipv4.tcp_wmem = 4096 16384 4194304"
} >> /etc/sysctl.conf
sysctl -p
main::errhandle_log_info "Preparing tuned/saptune"
if [[ "${LINUX_DISTRO}" = "SLES" ]]; then
saptune solution apply HANA
saptune daemon start
else
mkdir -p /etc/tuned/sap-hana/
cp /usr/lib/tuned/sap-hana/tuned.conf /etc/tuned/sap-hana/
systemctl start tuned
systemctl enable tuned
tuned-adm profile sap-hana
fi
}
hdb::download_media() {
main::errhandle_log_info "Downloading HANA media from ${VM_METADATA[sap_hana_deployment_bucket]}"
mkdir -p /hana/shared/media
# Check for sap_hana_deployment_bucket being empty in hdb::create_install_cfg()
# Check you have access to the bucket
if ! ${GSUTIL} ls gs://"${VM_METADATA[sap_hana_deployment_bucket]}"/; then
main::errhandle_log_error "SAP HANA media bucket '${VM_METADATA[sap_hana_deployment_bucket]}' cannot be accessed. The deployment has finished and is ready for SAP HANA, but SAP HANA will need to be downloaded and installed manually."
fi
# Set the media number, so we know
VM_METADATA[sap_hana_media_number]="$(${GSUTIL} ls gs://${VM_METADATA[sap_hana_deployment_bucket]} | grep _part1.exe | awk -F"/" '{print $NF}' | sed 's/_part1.exe//')"
# If SP4 or above, get the media number from the .ZIP
if [[ -z ${VM_METADATA[sap_hana_media_number]} ]]; then
VM_METADATA[sap_hana_media_number]="$(${GSUTIL} ls gs://${VM_METADATA[sap_hana_deployment_bucket]}/51* | grep -i .ZIP | awk -F"/" '{print $NF}' | sed 's/.ZIP//I')"
fi
# b/169984954 fail here already so user understands easier what is wrong
if [[ -z ${VM_METADATA[sap_hana_media_number]} ]]; then
main::errhandle_log_error "HANA Media not found in bucket. Expected format gs://${VM_METADATA[sap_hana_deployment_bucket]}/51*.[zip|ZIP]. The deployment has finished and is ready for SAP HANA, but SAP HANA will need to be downloaded and installed manually."
fi
## download unrar from GCS. Fix for RHEL missing unrar and SAP packaging change which stoppped unar working.
if [[ ${DEPLOY_URL} = gs* ]]; then
${GSUTIL} -q cp "${DEPLOY_URL}"/third_party/unrar/unrar /root/.deploy/unrar
else
curl "${DEPLOY_URL}"/third_party/unrar/unrar -o /root/.deploy/unrar
fi
chmod a=wrx /root/.deploy/unrar
## download SAP HANA media
main::errhandle_log_info "gsutil cp of gs://${VM_METADATA[sap_hana_deployment_bucket]} to /hana/shared/media/ in progress..."
# b/259315464 - no parallelism on SLES12
local parallel="-m"
if [[ ${LINUX_DISTRO} = "SLES" && "${LINUX_MAJOR_VERSION}" = "12" ]]; then
parallel=""
fi
if ! ${GSUTIL} -q -o "GSUtil:state_dir=/root/.deploy" ${parallel} cp gs://"${VM_METADATA[sap_hana_deployment_bucket]}"/* /hana/shared/media/; then
main::errhandle_log_error "HANA Media Download Failed. The deployment has finished and is ready for SAP HANA, but SAP HANA will need to be downloaded and installed manually."
fi
main::errhandle_log_info "gsutil cp of HANA media complete."
}
hdb::create_install_cfg() {
## output settings to log
main::errhandle_log_info "Creating HANA installation configuration file /root/.deploy/${HOSTNAME}_hana_install.cfg"
errored=""
## check parameters
if [ -z "${VM_METADATA[sap_hana_deployment_bucket]}" ]; then
main::errhandle_log_warning "SAP HANA deployment bucket is missing or incorrect in the accelerator template."
errored="true"
fi
if [ -z "${VM_METADATA[sap_hana_system_password]}" ]; then
main::errhandle_log_warning "SAP HANA system password or password secret was missing or incomplete in the accelerator template."
errored="true"
fi
if [ -z "${VM_METADATA[sap_hana_sidadm_password]}" ]; then
main::errhandle_log_warning "SAP HANA sidadm password or password secret was missing or incomplete in the accelerator template."
errored="true"
fi
if [ -z "${VM_METADATA[sap_hana_sid]}" ]; then
main::errhandle_log_warning "SAP HANA sid was missing or incomplete in the accelerator template."
errored="true"
fi
if [ -z "${VM_METADATA[sap_hana_sidadm_uid]}" ]; then
main::errhandle_log_warning "SAP HANA sidadm uid was missing or incomplete in the accelerator template."
errored="true"
fi
if [ -n "${errored}" ]; then
main::errhandle_log_error "Due to missing parameters, the deployment has finished and ready for SAP HANA, but SAP HANA will need to be installed manually."
fi
mkdir -p /root/.deploy
## create hana_install.cfg file
{
echo "[Server]" >/root/.deploy/"${HOSTNAME}"_hana_install.cfg
echo "sid=${VM_METADATA[sap_hana_sid]}"
echo "number=${VM_METADATA[sap_hana_instance_number]}"
echo "userid=${VM_METADATA[sap_hana_sidadm_uid]}"
echo "groupid=${VM_METADATA[sap_hana_sapsys_gid]}"
echo "apply_system_size_dependent_parameters=off"
} >>/root/.deploy/"${HOSTNAME}"_hana_install.cfg
## If HA configured, disable autostart
if [ -n "${VM_METADATA[sap_vip]}" ]; then
echo "autostart=n" >>/root/.deploy/"${HOSTNAME}"_hana_install.cfg
else
echo "autostart=y" >>/root/.deploy/"${HOSTNAME}"_hana_install.cfg
fi
## If scale-out then add the GCE Storage Connector
if [ -n "${VM_METADATA[sap_hana_standby_nodes]}" ]; then
echo "storage_cfg=/hana/shared/gceStorageClient" >>/root/.deploy/"${HOSTNAME}"_hana_install.cfg
fi
}
hdb::build_pw_xml() {
if [ -n "${VM_METADATA[sap_hana_system_password]}" ] || [ -n "${VM_METADATA[sap_hana_sidadm_password]}" ]; then
## set password for stdin use with hdblcm --read_password_from_stdin=xml
## single quotes required for ! as special character
local hana_xml='<?xml version="1.0" encoding="UTF-8"?><Passwords>'
hana_xml+='<password><![CDATA['
hana_xml+=${VM_METADATA[sap_hana_sidadm_password]}
hana_xml+=']]></password><sapadm_password><![CDATA['
hana_xml+=${VM_METADATA[sap_hana_sidadm_password]}
hana_xml+=']]></sapadm_password><system_user_password><![CDATA['
hana_xml+=${VM_METADATA[sap_hana_system_password]}
hana_xml+=']]></system_user_password></Passwords>'
echo ${hana_xml}
else
main::errhandle_log_error "Required passwords could not be retrieved. The server deployment is complete but SAP HANA is not deployed. Manual SAP HANA installation will be required."
fi
}
hdb::extract_media() {
local media_file
main::errhandle_log_info "Extracting SAP HANA media"
cd /hana/shared/media/ || main::errhandle_log_error "Unable to access /hana/shared/media. The server deployment is complete but SAP HANA is not deployed. Manual SAP HANA installation will be required."
media_file=$(find /hana/shared/media -maxdepth 1 -type f -iname "${VM_METADATA[sap_hana_media_number]}*.ZIP")