| gio | 07eb108 | 2024-10-25 14:35:56 +0400 | [diff] [blame] | 1 | {{- /* |
| 2 | Copyright Broadcom, Inc. All Rights Reserved. |
| 3 | SPDX-License-Identifier: APACHE-2.0 |
| 4 | */}} |
| 5 | |
| 6 | {{- if eq .Values.architecture "replicaset" }} |
| 7 | apiVersion: v1 |
| 8 | kind: ConfigMap |
| 9 | metadata: |
| 10 | name: {{ printf "%s-scripts" (include "mongodb.fullname" .) }} |
| 11 | namespace: {{ include "mongodb.namespace" . | quote }} |
| 12 | labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }} |
| 13 | app.kubernetes.io/component: mongodb |
| 14 | {{- if .Values.commonAnnotations }} |
| 15 | annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }} |
| 16 | {{- end }} |
| 17 | data: |
| 18 | {{- $fullname := include "mongodb.fullname" . }} |
| 19 | {{- $releaseNamespace := include "mongodb.namespace" . }} |
| 20 | {{- if and .Values.externalAccess.autoDiscovery.enabled (eq .Values.externalAccess.service.type "LoadBalancer") }} |
| 21 | auto-discovery.sh: |- |
| 22 | #!/bin/bash |
| 23 | |
| 24 | SVC_NAME="${MY_POD_NAME}-external" |
| 25 | |
| 26 | # Auxiliary functions |
| 27 | retry_while() { |
| 28 | local -r cmd="${1:?cmd is missing}" |
| 29 | local -r retries="${2:-12}" |
| 30 | local -r sleep_time="${3:-5}" |
| 31 | local return_value=1 |
| 32 | |
| 33 | read -r -a command <<< "$cmd" |
| 34 | for ((i = 1 ; i <= retries ; i+=1 )); do |
| 35 | "${command[@]}" && return_value=0 && break |
| 36 | sleep "$sleep_time" |
| 37 | done |
| 38 | return $return_value |
| 39 | } |
| 40 | k8s_svc_lb_ip() { |
| 41 | local namespace=${1:?namespace is missing} |
| 42 | local service=${2:?service is missing} |
| 43 | local service_ip=$(kubectl get svc "$service" -n "$namespace" -o jsonpath="{.status.loadBalancer.ingress[0].ip}") |
| 44 | local service_hostname=$(kubectl get svc "$service" -n "$namespace" -o jsonpath="{.status.loadBalancer.ingress[0].hostname}") |
| 45 | |
| 46 | if [[ -n ${service_ip} ]]; then |
| 47 | echo "${service_ip}" |
| 48 | else |
| 49 | echo "${service_hostname}" |
| 50 | fi |
| 51 | } |
| 52 | k8s_svc_lb_ip_ready() { |
| 53 | local namespace=${1:?namespace is missing} |
| 54 | local service=${2:?service is missing} |
| 55 | [[ -n "$(k8s_svc_lb_ip "$namespace" "$service")" ]] |
| 56 | } |
| 57 | # Wait until LoadBalancer IP is ready |
| 58 | retry_while "k8s_svc_lb_ip_ready {{ $releaseNamespace }} $SVC_NAME" || exit 1 |
| 59 | # Obtain LoadBalancer external IP |
| 60 | k8s_svc_lb_ip "{{ $releaseNamespace }}" "$SVC_NAME" | tee "$SHARED_FILE" |
| 61 | {{- end }} |
| 62 | setup.sh: |- |
| 63 | #!/bin/bash |
| 64 | |
| 65 | . /opt/bitnami/scripts/mongodb-env.sh |
| 66 | . /opt/bitnami/scripts/libfs.sh |
| 67 | . /opt/bitnami/scripts/liblog.sh |
| 68 | . /opt/bitnami/scripts/libvalidations.sh |
| 69 | |
| 70 | {{- if .Values.externalAccess.enabled }} |
| 71 | {{- if eq .Values.externalAccess.service.type "LoadBalancer" }} |
| 72 | {{- if .Values.externalAccess.autoDiscovery.enabled }} |
| 73 | export MONGODB_ADVERTISED_HOSTNAME="$(<${SHARED_FILE})" |
| 74 | {{- else }} |
| 75 | ID="${MY_POD_NAME#"{{ $fullname }}-"}" |
| 76 | export MONGODB_ADVERTISED_HOSTNAME=$(echo '{{ coalesce .Values.externalAccess.service.publicNames .Values.externalAccess.service.loadBalancerIPs }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") |
| 77 | {{- end }} |
| 78 | {{- else if eq .Values.externalAccess.service.type "NodePort" }} |
| 79 | ID="${MY_POD_NAME#"{{ $fullname }}-"}" |
| 80 | if is_empty_value "$MONGODB_ADVERTISED_PORT_NUMBER"; then |
| 81 | export MONGODB_ADVERTISED_PORT_NUMBER=$(echo '{{ .Values.externalAccess.service.nodePorts }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") |
| 82 | fi |
| 83 | {{- if .Values.externalAccess.service.domain }} |
| 84 | export MONGODB_ADVERTISED_HOSTNAME={{ .Values.externalAccess.service.domain }} |
| 85 | {{- else }} |
| 86 | export MONGODB_ADVERTISED_HOSTNAME=$MY_POD_HOST_IP |
| 87 | {{- end }} |
| 88 | {{- end }} |
| 89 | {{- end }} |
| 90 | |
| 91 | {{- if .Values.replicaSetConfigurationSettings.enabled }} |
| 92 | # placed here before root password env is overwritten |
| 93 | # makes no assumption about starting state |
| 94 | # ensures that any stepDown or non-default starting state is handled |
| 95 | /scripts/replicaSetConfigurationSettings.sh & |
| 96 | {{- end }} |
| 97 | |
| 98 | if is_empty_value "$MONGODB_ADVERTISED_PORT_NUMBER"; then |
| 99 | export MONGODB_ADVERTISED_PORT_NUMBER="$MONGODB_PORT_NUMBER" |
| 100 | fi |
| 101 | |
| 102 | info "Advertised Hostname: $MONGODB_ADVERTISED_HOSTNAME" |
| 103 | info "Advertised Port: $MONGODB_ADVERTISED_PORT_NUMBER" |
| 104 | |
| 105 | # Check for existing replica set in case there is no data in the PVC |
| 106 | # This is for cases where the PVC is lost or for MongoDB caches without |
| 107 | # persistence |
| 108 | current_primary="" |
| 109 | if is_dir_empty "${MONGODB_DATA_DIR}/db"; then |
| 110 | info "Data dir empty, checking if the replica set already exists" |
| 111 | {{- $replicaCount := int .Values.replicaCount }} |
| 112 | {{- $portNumber := int .Values.service.ports.mongodb }} |
| 113 | {{- $fullname := include "mongodb.fullname" . }} |
| 114 | {{- $releaseNamespace := include "mongodb.namespace" . }} |
| 115 | {{- $clusterDomain := .Values.clusterDomain }} |
| 116 | {{- $mongoList := list }} |
| 117 | {{- range $e, $i := until $replicaCount }} |
| 118 | {{- $mongoList = append $mongoList (printf "%s-%d.%s-headless.%s.svc.%s:%d" $fullname $i $fullname $releaseNamespace $clusterDomain $portNumber) }} |
| 119 | {{- end }} |
| 120 | |
| 121 | {{- if .Values.externalAccess.externalMaster.enabled }} |
| 122 | current_primary={{ printf "%s:%d" (.Values.externalAccess.externalMaster.host) ( int .Values.externalAccess.externalMaster.port) }} |
| 123 | {{- else }} |
| 124 | current_primary=$(mongosh admin --host "{{ join "," $mongoList }}" {{- if .Values.auth.enabled }} --authenticationDatabase admin -u $MONGODB_ROOT_USER -p $MONGODB_ROOT_PASSWORD{{- end }}{{- if .Values.tls.enabled}} --tls {{ if .Values.tls.mTLS.enabled }}--tlsCertificateKeyFile=/certs/mongodb.pem {{ end }}--tlsCAFile=/certs/mongodb-ca-cert{{- end }} --eval 'db.runCommand("ismaster")' | awk -F\' '/primary:/ {print $2}') |
| 125 | {{- end }} |
| 126 | if ! is_empty_value "$current_primary"; then |
| 127 | info "Detected existing primary: ${current_primary}" |
| 128 | fi |
| 129 | fi |
| 130 | |
| 131 | if ! is_empty_value "$current_primary" && [[ "$MONGODB_ADVERTISED_HOSTNAME:$MONGODB_ADVERTISED_PORT_NUMBER" == "$current_primary" ]]; then |
| 132 | info "Advertised name matches current primary, configuring node as a primary" |
| 133 | export MONGODB_REPLICA_SET_MODE="primary" |
| 134 | elif ! is_empty_value "$current_primary" && [[ "$MONGODB_ADVERTISED_HOSTNAME:$MONGODB_ADVERTISED_PORT_NUMBER" != "$current_primary" ]]; then |
| 135 | info "Current primary is different from this node. Configuring the node as replica of ${current_primary}" |
| 136 | export MONGODB_REPLICA_SET_MODE="secondary" |
| 137 | export MONGODB_INITIAL_PRIMARY_HOST="${current_primary%:*}" |
| 138 | export MONGODB_INITIAL_PRIMARY_PORT_NUMBER="${current_primary#*:}" |
| 139 | export MONGODB_SET_SECONDARY_OK="yes" |
| 140 | elif [[ "$MY_POD_NAME" = "{{ $fullname }}-0" ]]; then |
| 141 | info "Pod name matches initial primary pod name, configuring node as a primary" |
| 142 | export MONGODB_REPLICA_SET_MODE="primary" |
| 143 | else |
| 144 | info "Pod name doesn't match initial primary pod name, configuring node as a secondary" |
| 145 | export MONGODB_REPLICA_SET_MODE="secondary" |
| 146 | export MONGODB_INITIAL_PRIMARY_PORT_NUMBER="$MONGODB_PORT_NUMBER" |
| 147 | fi |
| 148 | |
| 149 | if [[ "$MONGODB_REPLICA_SET_MODE" == "secondary" ]]; then |
| 150 | export MONGODB_INITIAL_PRIMARY_ROOT_USER="$MONGODB_ROOT_USER" |
| 151 | export MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD="$MONGODB_ROOT_PASSWORD" |
| 152 | export MONGODB_ROOT_PASSWORD="" |
| 153 | export MONGODB_EXTRA_USERNAMES="" |
| 154 | export MONGODB_EXTRA_DATABASES="" |
| 155 | export MONGODB_EXTRA_PASSWORDS="" |
| 156 | export MONGODB_ROOT_PASSWORD_FILE="" |
| 157 | export MONGODB_EXTRA_USERNAMES_FILE="" |
| 158 | export MONGODB_EXTRA_DATABASES_FILE="" |
| 159 | export MONGODB_EXTRA_PASSWORDS_FILE="" |
| 160 | fi |
| 161 | exec /opt/bitnami/scripts/mongodb/entrypoint.sh /opt/bitnami/scripts/mongodb/run.sh |
| 162 | setup-hidden.sh: |- |
| 163 | #!/bin/bash |
| 164 | |
| 165 | . /opt/bitnami/scripts/mongodb-env.sh |
| 166 | |
| 167 | {{- if .Values.externalAccess.hidden.enabled }} |
| 168 | {{- if eq .Values.externalAccess.hidden.service.type "LoadBalancer" }} |
| 169 | {{- if .Values.externalAccess.autoDiscovery.enabled }} |
| 170 | export MONGODB_ADVERTISED_HOSTNAME="$(<${SHARED_FILE})" |
| 171 | {{- else }} |
| 172 | ID="${MY_POD_NAME#"{{ $fullname }}-hidden-"}" |
| 173 | export MONGODB_ADVERTISED_HOSTNAME=$(echo '{{ .Values.externalAccess.hidden.service.loadBalancerIPs }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") |
| 174 | {{- end }} |
| 175 | {{- else if eq .Values.externalAccess.hidden.service.type "NodePort" }} |
| 176 | ID="${MY_POD_NAME#"{{ $fullname }}-hidden-"}" |
| 177 | if is_empty_value "$MONGODB_ADVERTISED_PORT_NUMBER"; then |
| 178 | export MONGODB_ADVERTISED_PORT_NUMBER=$(echo '{{ .Values.externalAccess.service.nodePorts }}' | tr -d '[]' | cut -d ' ' -f "$(($ID + 1))") |
| 179 | fi |
| 180 | {{- if .Values.externalAccess.hidden.service.domain }} |
| 181 | export MONGODB_ADVERTISED_HOSTNAME={{ .Values.externalAccess.hidden.service.domain }} |
| 182 | {{- else }} |
| 183 | export MONGODB_ADVERTISED_HOSTNAME=$MY_POD_HOST_IP |
| 184 | {{- end }} |
| 185 | {{- end }} |
| 186 | {{- end }} |
| 187 | |
| 188 | {{- if .Values.replicaSetConfigurationSettings.enabled }} |
| 189 | # placed here before root password env is overwritten |
| 190 | # makes no assumption about starting state |
| 191 | # ensures that any stepDown or non-default starting state is handled |
| 192 | /scripts/replicaSetConfigurationSettings.sh & |
| 193 | {{- end }} |
| 194 | |
| 195 | echo "Advertised Hostname: $MONGODB_ADVERTISED_HOSTNAME" |
| 196 | echo "Advertised Port: $MONGODB_ADVERTISED_PORT_NUMBER" |
| 197 | echo "Configuring node as a hidden node" |
| 198 | export MONGODB_REPLICA_SET_MODE="hidden" |
| 199 | export MONGODB_INITIAL_PRIMARY_ROOT_USER="$MONGODB_ROOT_USER" |
| 200 | export MONGODB_INITIAL_PRIMARY_ROOT_PASSWORD="$MONGODB_ROOT_PASSWORD" |
| 201 | export MONGODB_INITIAL_PRIMARY_PORT_NUMBER="$MONGODB_PORT_NUMBER" |
| 202 | export MONGODB_ROOT_PASSWORD="" |
| 203 | export MONGODB_EXTRA_USERNAMES="" |
| 204 | export MONGODB_EXTRA_DATABASES="" |
| 205 | export MONGODB_EXTRA_PASSWORDS="" |
| 206 | export MONGODB_ROOT_PASSWORD_FILE="" |
| 207 | export MONGODB_EXTRA_USERNAMES_FILE="" |
| 208 | export MONGODB_EXTRA_DATABASES_FILE="" |
| 209 | export MONGODB_EXTRA_PASSWORDS_FILE="" |
| 210 | exec /opt/bitnami/scripts/mongodb/entrypoint.sh /opt/bitnami/scripts/mongodb/run.sh |
| 211 | {{- if .Values.replicaSetConfigurationSettings.enabled }} |
| 212 | replicaSetConfigurationSettings.sh: |- |
| 213 | #!/bin/bash |
| 214 | # This script to be called when pod starts. |
| 215 | # This script sets rs settings which can not be applied via conf file |
| 216 | |
| 217 | function logger () |
| 218 | #$1 is the line to be logged |
| 219 | { |
| 220 | echo "replicaSetConfigurationSettings.sh -- ${1}" >&1 |
| 221 | } |
| 222 | |
| 223 | SLEEP_PERIOD=10 |
| 224 | |
| 225 | {{- if and .Values.auth.enabled (or .Values.auth.rootPassword .Values.auth.existingSecret)}} |
| 226 | usernameAndPassword="{{- if .Values.tls.enabled}} --tls {{ if .Values.tls.mTLS.enabled }}--tlsCertificateKeyFile=/certs/mongodb.pem {{ end }}--tlsCAFile=/certs/mongodb-ca-cert{{- end }} -u ${MONGODB_ROOT_USER} -p ${MONGODB_ROOT_PASSWORD}" |
| 227 | {{- else }} |
| 228 | usernameAndPassword="" |
| 229 | {{- end }} |
| 230 | |
| 231 | # load Values.replicaSetConfigurationSettings.configuration into associtive array which makes iterating and string manipulation easy |
| 232 | declare -A desiredRsConf |
| 233 | {{ range $setting, $value := .Values.replicaSetConfigurationSettings.configuration -}} |
| 234 | {{ printf "desiredRsConf[%s]='%v'" $setting $value }} |
| 235 | {{ end }} |
| 236 | |
| 237 | rsConfWriteAttempts=0 |
| 238 | rs_conf_configured_ok=unknown |
| 239 | |
| 240 | while [[ "${rs_conf_configured_ok}" != "true" ]]; do |
| 241 | |
| 242 | # give the rs setup a chance to succeed before attempting to read or configure |
| 243 | sleep ${SLEEP_PERIOD} |
| 244 | |
| 245 | counter=0 |
| 246 | while ! mongosh ${usernameAndPassword} --eval 'rs.conf()'; do |
| 247 | counter=$((${counter} +1)) |
| 248 | logger "not yet able to read rs.conf settings from the currently running rs (after ${counter} attempts)" |
| 249 | sleep ${SLEEP_PERIOD} |
| 250 | done |
| 251 | counter=$((${counter} +1)) |
| 252 | logger "rs.conf settings have been read from the currently running rs (after ${counter} attempts)" |
| 253 | |
| 254 | # read rs.conf again and store it. settings format is '"<key>" : <value>,' |
| 255 | currentRsConf=$(mongosh ${usernameAndPassword} --eval 'rs.conf()') |
| 256 | |
| 257 | desiredEqualsactual=unknown |
| 258 | settingsToConfigure="" |
| 259 | for key in ${!desiredRsConf[@]}; do |
| 260 | value=${desiredRsConf[$key]} |
| 261 | if ! $(echo "\"${currentRsConf}"\" | grep -q -e "${key}: ${value},"); then |
| 262 | if [[ $key =~ ^members\[[0-9]+\]\..+ ]]; then |
| 263 | memberIndex=$(echo $key | grep -o -E '[0-9]+') |
| 264 | nodeConfigKey=${key#*.} |
| 265 | settingsToConfigure="${settingsToConfigure}cfg.members[${memberIndex}].${nodeConfigKey} = ${value}; " |
| 266 | else |
| 267 | # General rs settings |
| 268 | settingsToConfigure="${settingsToConfigure}cfg.settings.${key} = ${value}; " |
| 269 | fi |
| 270 | desiredEqualsactual=false |
| 271 | else |
| 272 | logger "rs conf: ${key} is already at desired value: ${value}" |
| 273 | fi |
| 274 | done |
| 275 | |
| 276 | if [[ "${desiredEqualsactual}" != "false" ]]; then |
| 277 | logger "replicaSetConfigurationSettings match the settings of the currently running rs" |
| 278 | desiredEqualsactual=true |
| 279 | rs_conf_configured_ok=true |
| 280 | logger "Current settings match desired settings (There have been ${rsConfWriteAttempts} attempts to write to mongoDB rs configuration)" |
| 281 | exit |
| 282 | fi |
| 283 | |
| 284 | # apply the settings only if this member is currently the mongo replicaset PRIMARY |
| 285 | # it might take a little time before any pod is PRIMARY |
| 286 | isMaster=unknown |
| 287 | if ! mongosh ${usernameAndPassword} --eval 'rs.isMaster()' | grep -q "ismaster: true"; then |
| 288 | isMaster=false |
| 289 | logger "This node is not yet PRIMARY - replicaSetConfigurationSettings will only be set on the member that is currently PRIMARY" |
| 290 | else |
| 291 | isMaster=true |
| 292 | logger "This node is PRIMARY" |
| 293 | fi |
| 294 | |
| 295 | if [[ "${isMaster}" == "true" ]]; then |
| 296 | logger "This node is currently PRIMARY - will apply rs.conf settings" |
| 297 | |
| 298 | # avoiding tricky string substitution with single quotes by making the eval string a set of vars |
| 299 | rsconf="cfg = rs.conf();" |
| 300 | rsreconf="rs.reconfig(cfg);" |
| 301 | rsCommand="${rsconf} ${settingsToConfigure} ${rsreconf}" |
| 302 | |
| 303 | mongosh ${usernameAndPassword} --eval "${rsCommand}" |
| 304 | if [ $? -ne 0 ]; then |
| 305 | logger "Failed to apply mongodb cfg.settings configuration" |
| 306 | else |
| 307 | logger "mongodb replicaset cfg.settings configuration applied" |
| 308 | logger "Will check rs conf" |
| 309 | # don't exit just yet - the settings will be checked in the next loop |
| 310 | fi |
| 311 | rsConfWriteAttempts=$((${rsConfWriteAttempts} + 1 )) |
| 312 | fi |
| 313 | done |
| 314 | {{- end }} |
| 315 | {{- end }} |
| 316 | |