{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if (include "elasticsearch.master.enabled" .) }}
apiVersion: {{ template "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ include "elasticsearch.master.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: master
    {{- if .Values.useIstioLabels }}
    ## Istio Labels: https://istio.io/docs/ops/deployment/requirements/
    app: master
    {{- end }}
  {{- if or .Values.master.annotations .Values.commonAnnotations }}
  {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.master.annotations .Values.commonAnnotations ) "context" . ) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $) | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.master.autoscaling.enabled }}
  replicas: {{ .Values.master.replicaCount }}
  {{- end }}
  podManagementPolicy: {{ .Values.master.podManagementPolicy }}
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.master.podLabels .Values.commonLabels ) "context" . ) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/component: master
  serviceName: {{ include "elasticsearch.master.servicename" . }}
  {{- if .Values.master.updateStrategy }}
  updateStrategy: {{- toYaml .Values.master.updateStrategy | nindent 4 }}
  {{- end }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: master
        {{- if .Values.useIstioLabels }}
        ## Istio Labels: https://istio.io/docs/ops/deployment/requirements/
        app: master
        {{- end }}
      annotations:
        {{- if and (include "elasticsearch.createTlsSecret" .) (not .Values.security.tls.master.existingSecret) }}
        checksum/tls: {{ include (print $.Template.BasePath "/tls-secret.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.master.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
    spec:
      serviceAccountName: {{ template "elasticsearch.master.serviceAccountName" . }}
      {{- include "elasticsearch.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.master.automountServiceAccountToken }}
      {{- if .Values.master.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.master.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.master.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.master.podAffinityPreset "component" "master" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.master.podAntiAffinityPreset "component" "master" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.master.nodeAffinityPreset.type "key" .Values.master.nodeAffinityPreset.key "values" .Values.master.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.master.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.master.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.master.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.schedulerName }}
      schedulerName: {{ .Values.master.schedulerName }}
      {{- end }}
      {{- if .Values.master.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.master.topologySpreadConstraints "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.priorityClassName }}
      priorityClassName: {{ .Values.master.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.master.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.master.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.shareProcessNamespace }}
      shareProcessNamespace: {{ .Values.master.shareProcessNamespace }}
      {{- end }}
      {{- if .Values.master.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.master.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if or .Values.initContainers .Values.master.initContainers (and  .Values.enableDefaultInitContainers (or .Values.security.enabled .Values.sysctlImage.enabled (and .Values.volumePermissions.enabled .Values.master.persistence.enabled))) }}
      initContainers:
        {{- if and .Values.sysctlImage.enabled .Values.enableDefaultInitContainers }}
        ## Image that performs the sysctl operation to modify Kernel settings (needed sometimes to avoid boot errors)
        - name: sysctl
          image: {{ include "elasticsearch.sysctl.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          command:
            - /bin/bash
            - -ec
            - |
              {{- include "elasticsearch.sysctlIfLess" (dict "key" "vm.max_map_count" "value" "262144") | nindent 14 }}
              {{- include "elasticsearch.sysctlIfLess" (dict "key" "fs.file-max" "value" "65536") | nindent 14 }}
          securityContext:
            privileged: true
            runAsUser: 0
          {{- if .Values.sysctlImage.resources }}
          resources: {{- toYaml .Values.sysctlImage.resources | nindent 12 }}
          {{- else if ne .Values.sysctlImage.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.sysctlImage.resourcesPreset) | nindent 12 }}
          {{- end }}
        {{- end }}
        {{- if and .Values.volumePermissions.enabled .Values.master.persistence.enabled  .Values.enableDefaultInitContainers }}
        - name: volume-permissions
          image: {{ include "elasticsearch.volumePermissions.image" . }}
          imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - /bin/bash
            - -ec
            - |
              mkdir -p /bitnami/elasticsearch/data
              chown {{ .Values.master.containerSecurityContext.runAsUser }}:{{ .Values.master.podSecurityContext.fsGroup }} /bitnami/elasticsearch/data
              find /bitnami/elasticsearch/data -mindepth 1 -maxdepth 1 -not -name ".snapshot" -not -name "lost+found" | xargs -r chown -R {{ .Values.master.containerSecurityContext.runAsUser }}:{{ .Values.master.podSecurityContext.fsGroup }}
          securityContext:
            runAsUser: 0
          {{- if .Values.volumePermissions.resources }}
          resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }}
          {{- else if ne .Values.volumePermissions.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.volumePermissions.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: /bitnami/elasticsearch/data
        {{- end }}
        {{- if .Values.enableDefaultInitContainers }}
        - name: copy-default-plugins
          image: {{ include "elasticsearch.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.master.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.master.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.master.resources }}
          resources: {{- toYaml .Values.master.resources | nindent 12 }}
          {{- else if ne .Values.master.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.master.resourcesPreset) | nindent 12 }}
          {{- end }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              #!/bin/bash

              . /opt/bitnami/scripts/libfs.sh
              . /opt/bitnami/scripts/elasticsearch-env.sh

              if ! is_dir_empty "$DB_DEFAULT_PLUGINS_DIR"; then
                  cp -nr "$DB_DEFAULT_PLUGINS_DIR"/* /plugins
              fi
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /plugins
              subPath: app-plugins-dir
        {{- end }}
        {{- if .Values.master.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.initContainers "context" $) | nindent 8 }}
        {{- end }}
        {{- if .Values.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }}
        {{- end }}
      {{- end }}
      containers:
        - name: elasticsearch
          image: {{ include "elasticsearch.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.master.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.master.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.master.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.master.command "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }}
          {{- else if .Values.master.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.master.args "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.master.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.master.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: ELASTICSEARCH_IS_DEDICATED_NODE
              value: {{ ternary "yes" "no" .Values.master.masterOnly | quote }}
            - name: ELASTICSEARCH_NODE_ROLES
              value: {{ prepend .Values.master.extraRoles "master" | join "," | quote }}
            - name: ELASTICSEARCH_TRANSPORT_PORT_NUMBER
              value: {{ .Values.containerPorts.transport | quote }}
            - name: ELASTICSEARCH_HTTP_PORT_NUMBER
              value: {{ .Values.containerPorts.restAPI | quote }}
            - name: ELASTICSEARCH_CLUSTER_NAME
              value: {{ .Values.clusterName | quote }}
            {{ if not (include "elasticsearch.singleNode.enabled" .) }}
            - name: ELASTICSEARCH_CLUSTER_HOSTS
              value: {{ include "elasticsearch.hosts" . | quote }}
            - name: ELASTICSEARCH_TOTAL_NODES
              value: {{ add (ternary .Values.master.autoscaling.minReplicas .Values.master.replicaCount .Values.master.autoscaling.enabled) (ternary .Values.data.autoscaling.minReplicas .Values.data.replicaCount .Values.data.autoscaling.enabled) | quote }}
            - name: ELASTICSEARCH_CLUSTER_MASTER_HOSTS
              {{- $elasticsearchMasterFullname := include "elasticsearch.master.fullname" . }}
              {{- $replicas := int (ternary .Values.master.autoscaling.minReplicas .Values.master.replicaCount .Values.master.autoscaling.enabled) }}
              value: {{ range $i, $e := until $replicas }}{{ printf "%s-%d" $elasticsearchMasterFullname $e }} {{ end }}
            - name: ELASTICSEARCH_MINIMUM_MASTER_NODES
              value: {{ add (div (ternary .Values.master.autoscaling.minReplicas .Values.master.replicaCount .Values.master.autoscaling.enabled) 2) 1 | quote }}
            - name: ELASTICSEARCH_ADVERTISED_HOSTNAME
              value: "$(MY_POD_NAME).{{ (include "elasticsearch.master.servicename" .) | trunc 63 | trimSuffix "-" }}.{{ include "common.names.namespace" . }}.svc.{{ .Values.clusterDomain }}"
            {{- end }}
            {{- if .Values.plugins }}
            - name: ELASTICSEARCH_PLUGINS
              value: {{ .Values.plugins | quote }}
            {{- end }}
            {{- if .Values.snapshotRepoPath }}
            - name: ELASTICSEARCH_FS_SNAPSHOT_REPO_PATH
              value: {{ .Values.snapshotRepoPath | quote }}
            {{- end }}
            {{- if .Values.master.heapSize }}
            - name: ELASTICSEARCH_HEAP_SIZE
              value: {{ .Values.master.heapSize | quote }}
            {{- end }}
            {{- if .Values.security.enabled }}
            {{- include "elasticsearch.configure.security" . | nindent 12 }}
            {{- end }}
            {{- if .Values.master.extraEnvVars }}
            {{- include "common.tplvalues.render" ( dict "value" .Values.master.extraEnvVars "context" $ ) | nindent 12 }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" ( dict "value" .Values.extraEnvVars "context" $ ) | nindent 12 }}
            {{- end }}
          {{- if or .Values.extraEnvVarsCM .Values.extraEnvVarsSecret .Values.master.extraEnvVarsCM .Values.master.extraEnvVarsSecret }}
          envFrom:
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" ( dict "value" .Values.extraEnvVarsCM "context" $ ) }}
            {{- end }}
            {{- if .Values.master.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" ( dict "value" .Values.master.extraEnvVarsCM "context" $ ) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" ( dict "value" .Values.extraEnvVarsSecret "context" $ ) }}
            {{- end }}
            {{- if .Values.master.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" ( dict "value" .Values.master.extraEnvVarsSecret "context" $ ) }}
            {{- end }}
          {{- end }}
          ports:
            - name: rest-api
              containerPort: {{ .Values.containerPorts.restAPI }}
            - name: transport
              containerPort: {{ .Values.containerPorts.transport }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.master.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.startupProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: rest-api
          {{- end }}
          {{- if .Values.master.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: rest-api
          {{- end }}
          {{- if .Values.master.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.readinessProbe "enabled") "context" $) | nindent 12 }}
            exec:
              command:
                - /opt/bitnami/scripts/elasticsearch/healthcheck.sh
          {{- end }}
          {{- end }}
          {{- if .Values.master.resources }}
          resources: {{- toYaml .Values.master.resources | nindent 12 }}
          {{- else if ne .Values.master.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.master.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/elasticsearch/config
              subPath: app-conf-dir
            - name: empty-dir
              mountPath: /opt/bitnami/elasticsearch/tmp
              subPath: app-tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/elasticsearch/logs
              subPath: app-logs-dir
            - name: empty-dir
              mountPath: /opt/bitnami/elasticsearch/plugins
              subPath: app-plugins-dir
            - name: empty-dir
              mountPath: /bitnami/elasticsearch
              subPath: app-volume-dir
            - name: data
              mountPath: /bitnami/elasticsearch/data
            {{- if and .Values.usePasswordFiles .Values.security.enabled }}
            - name: elasticsearch-secrets
              mountPath: /opt/bitnami/elasticsearch/secrets
            {{- end }}
            {{- if .Values.config }}
            - mountPath: /opt/bitnami/elasticsearch/config/elasticsearch.yml
              name: config
              subPath: elasticsearch.yml
            {{- end }}
            {{- if .Values.extraConfig }}
            - mountPath: /opt/bitnami/elasticsearch/config/my_elasticsearch.yml
              name: config
              subPath: my_elasticsearch.yml
            {{- end }}
            {{- if .Values.security.enabled }}
            - name: elasticsearch-certificates
              mountPath: /opt/bitnami/elasticsearch/config/certs
              readOnly: true
            {{- end }}
            {{- if .Values.initScripts }}
            - name: custom-init-scripts
              mountPath: /docker-entrypoint-initdb.d/init-scripts
            {{- end }}
            {{- if .Values.initScriptsCM }}
            - name: custom-init-scripts-cm
              mountPath: /docker-entrypoint-initdb.d/init-scripts-cm
            {{- end }}
            {{- if .Values.initScriptsSecret }}
            - name: custom-init-scripts-secret
              mountPath: /docker-entrypoint-initdb.d/init-scripts-secret
            {{- end }}
            {{- if .Values.master.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.master.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        {{- if .Values.master.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.master.sidecars "context" $) | nindent 8 }}
        {{- end }}
        {{- if .Values.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if and .Values.usePasswordFiles .Values.security.enabled }}
        - name: elasticsearch-secrets
          projected:
            sources:
              - secret:
                  name: {{ include "elasticsearch.secretName" . }}
              {{- if or .Values.security.tls.passwordsSecret .Values.security.tls.keystorePassword .Values.security.tls.truststorePassword .Values.security.tls.keyPassword }}
              - secret:
                  name: {{ include "elasticsearch.tlsPasswordsSecret" . }}
              {{- end }}
        {{- end }}
        {{- if or .Values.config .Values.extraConfig }}
        - name: config
          configMap:
            name: {{ template "common.names.fullname" . }}
        {{- end }}
        {{- if .Values.security.enabled }}
        - name: elasticsearch-certificates
          secret:
            secretName: {{ template "elasticsearch.master.tlsSecretName" . }}
            defaultMode: 256
        {{- end }}
        {{- if .Values.initScripts }}
        - name: custom-init-scripts
          configMap:
            name: {{ template "elasticsearch.initScripts" . }}
        {{- end }}
        {{- if .Values.initScriptsCM }}
        - name: custom-init-scripts-cm
          configMap:
            name: {{ template "elasticsearch.initScriptsCM" . }}
        {{- end }}
        {{- if .Values.initScriptsSecret }}
        - name: custom-init-scripts-secret
          secret:
            secretName: {{ template "elasticsearch.initScriptsSecret" . }}
            defaultMode: 0755
        {{- end }}
        {{- if .Values.master.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
  {{- if not .Values.master.persistence.enabled }}
        - name: "data"
          emptyDir: {}
  {{- else if .Values.master.persistence.existingClaim }}
        - name: "data"
          persistentVolumeClaim:
            claimName: {{ .Values.master.persistence.existingClaim }}
  {{- else }}
  {{- if .Values.master.persistentVolumeClaimRetentionPolicy.enabled }}
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: {{ .Values.master.persistentVolumeClaimRetentionPolicy.whenDeleted }}
    whenScaled: {{ .Values.master.persistentVolumeClaimRetentionPolicy.whenScaled }}
  {{- end }}
  volumeClaimTemplates:
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: "data"
        {{- if or .Values.master.persistence.annotations .Values.commonAnnotations }}
        {{- $claimAnnotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.master.persistence.annotations .Values.commonAnnotations ) "context" . ) }}
        annotations: {{- include "common.tplvalues.render" ( dict "value" $claimAnnotations "context" $) | nindent 10 }}
        {{- end }}
        {{- if .Values.commonLabels }}
        labels: {{- include "common.tplvalues.render" (dict "value" .Values.commonLabels "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
          {{- range .Values.master.persistence.accessModes }}
          - {{ . | quote }}
          {{- end }}
        resources:
          requests:
            storage: {{ .Values.master.persistence.size | quote }}
        {{- if .Values.master.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.master.persistence.selector "context" $) | nindent 10 }}
        {{- else if .Values.master.persistence.existingVolume }}
        selector:
          matchLabels:
            volume: {{ .Values.master.persistence.existingVolume }}
        {{- end }}
        {{- include "common.storage.class" (dict "persistence" .Values.master.persistence "global" .Values.global) | nindent 8 }}
  {{- end }}
{{- end }}
