apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ template "zookeeper.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels: {{- include "zookeeper.labels" . | nindent 4 }}
    app.kubernetes.io/component: zookeeper
    role: zookeeper
    {{- if .Values.commonLabels }}
    {{- include "zookeeper.tplValue" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "zookeeper.tplValue" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  serviceName: {{ template "zookeeper.fullname" . }}-headless
  replicas: {{ .Values.replicaCount }}
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  updateStrategy:
    type: {{ .Values.updateStrategy }}
    {{- if (eq "Recreate" .Values.updateStrategy) }}
    rollingUpdate: null
    {{- else if .Values.rollingUpdatePartition }}
    rollingUpdate:
      partition: {{ .Values.rollingUpdatePartition }}
    {{- end }}
  selector:
    matchLabels: {{- include "zookeeper.matchLabels" . | nindent 6 }}
      app.kubernetes.io/component: zookeeper
  template:
    metadata:
      name: {{ template "zookeeper.fullname" . }}
      labels: {{- include "zookeeper.labels" . | nindent 8 }}
        app.kubernetes.io/component: zookeeper
        {{- if .Values.podLabels }}
        {{- include "zookeeper.tplValue" (dict "value" .Values.podLabels "context" $) | nindent 8 }}
        {{- end }}
      {{- if .Values.podAnnotations }}
      annotations: {{- include "zookeeper.tplValue" ( dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
      {{- end }}
    spec:
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName }}
      {{- end }}
      {{- include "zookeeper.imagePullSecrets" . | nindent 6 }}
      serviceAccountName: {{ template "zookeeper.serviceAccountName" . }}
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
      {{- end }}
      {{- if .Values.affinity }}
      affinity: {{- include "zookeeper.tplValue" (dict "value" .Values.affinity "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "zookeeper.tplValue" (dict "value" .Values.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "zookeeper.tplValue" (dict "value" .Values.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      {{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }}
      initContainers:
        - name: volume-permissions
          image: {{ template "zookeeper.volumePermissions.image" . }}
          imagePullPolicy: {{ default "" .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - chown
          args:
            - -R
            - {{ .Values.securityContext.runAsUser }}:{{ .Values.securityContext.fsGroup }}
            - /bitnami/zookeeper
            {{- if .Values.dataLogDir }}
            - {{ .Values.dataLogDir }}
            {{- end }}
          securityContext:
            runAsUser: 0
          {{- if .Values.volumePermissions.resources }}
          resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: /bitnami/zookeeper
            {{- if .Values.dataLogDir }}
            - name: data-log
              mountPath: {{ .Values.dataLogDir }}
            {{- end }}
      {{- end }}
      containers:
        - name: zookeeper
          image: {{ template "zookeeper.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.securityContext.enabled }}
          securityContext:
            runAsUser: {{ .Values.securityContext.runAsUser }}
          {{- end }}
          command:
            - bash
            - -ec
            - |
                # Execute entrypoint as usual after obtaining ZOO_SERVER_ID based on POD hostname
                HOSTNAME=`hostname -s`
                if [[ $HOSTNAME =~ (.*)-([0-9]+)$ ]]; then
                  ORD=${BASH_REMATCH[2]}
                  export ZOO_SERVER_ID=$((ORD+1))
                else
                  echo "Failed to get index from hostname $HOST"
                  exit 1
                fi
                exec /entrypoint.sh /run.sh
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- end }}
          env:
            - name: ZOO_DATA_LOG_DIR
              value: {{ .Values.dataLogDir | quote }}
            - name: ZOO_PORT_NUMBER
              value: {{ .Values.service.port | quote }}
            - name: ZOO_TICK_TIME
              value: {{ .Values.tickTime | quote }}
            - name: ZOO_INIT_LIMIT
              value: {{ .Values.initLimit | quote }}
            - name: ZOO_SYNC_LIMIT
              value: {{ .Values.syncLimit | quote }}
            - name: ZOO_MAX_CLIENT_CNXNS
              value: {{ .Values.maxClientCnxns | quote }}
            - name: ZOO_4LW_COMMANDS_WHITELIST
              value: {{ .Values.fourlwCommandsWhitelist | quote }}
            - name: ZOO_LISTEN_ALLIPS_ENABLED
              value: {{ ternary "yes" "no" .Values.listenOnAllIPs | quote }}
            - name: ZOO_AUTOPURGE_INTERVAL
              value: {{ .Values.autopurge.purgeInterval | quote }}
            - name: ZOO_AUTOPURGE_RETAIN_COUNT
              value: {{ .Values.autopurge.snapRetainCount | quote }}
            - name: ZOO_MAX_SESSION_TIMEOUT
              value: {{ .Values.maxSessionTimeout | quote }}
            - name: ZOO_SERVERS
              {{- $replicaCount := int .Values.replicaCount }}
              {{- $followerPort := int .Values.service.followerPort }}
              {{- $electionPort := int .Values.service.electionPort }}
              {{- $releaseNamespace := .Release.Namespace }}
              {{- $zookeeperFullname := include "zookeeper.fullname" . }}
              {{- $zookeeperHeadlessServiceName := printf "%s-%s" $zookeeperFullname "headless" | trunc 63  }}
              {{- $clusterDomain := .Values.clusterDomain }}
              value: {{ range $i, $e := until $replicaCount }}{{ $zookeeperFullname }}-{{ $e }}.{{ $zookeeperHeadlessServiceName }}.{{ $releaseNamespace }}.svc.{{ $clusterDomain }}:{{ $followerPort }}:{{ $electionPort }} {{ end }}
            - name: ZOO_ENABLE_AUTH
              value: {{ ternary "yes" "no" .Values.auth.enabled | quote }}
            {{- if .Values.auth.enabled }}
            - name: ZOO_CLIENT_USER
              value: {{ .Values.auth.clientUser | quote }}
            - name: ZOO_CLIENT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ if .Values.auth.existingSecret }}{{ .Values.auth.existingSecret }}{{ else }}{{ template "zookeeper.fullname" . }}{{ end }}
                  key: client-password
            - name: ZOO_SERVER_USERS
              value: {{ .Values.auth.serverUsers | quote }}
            - name: ZOO_SERVER_PASSWORDS
              valueFrom:
                secretKeyRef:
                  name: {{ if .Values.auth.existingSecret }}{{ .Values.auth.existingSecret }}{{ else }}{{ template "zookeeper.fullname" . }}{{ end }}
                  key: server-password
            {{- end }}
            - name: ZOO_HEAP_SIZE
              value: {{ .Values.heapSize | quote }}
            - name: ZOO_LOG_LEVEL
              value: {{ .Values.logLevel | quote }}
            - name: ALLOW_ANONYMOUS_LOGIN
              value: {{ ternary "yes" "no" .Values.allowAnonymousLogin | quote }}
            {{- if .Values.jvmFlags }}
            - name: JVMFLAGS
              value: {{ .Values.jvmFlags | quote }}
            {{- end }}
            {{- if .Values.metrics.enabled }}
            - name: ZOO_ENABLE_PROMETHEUS_METRICS
              value: "yes"
            - name: ZOO_PROMETHEUS_METRICS_PORT_NUMBER
              value: {{ .Values.metrics.containerPort | quote }}
            {{- end }}
            {{- if .Values.service.tls.client_enable }}
            - name: ZOO_TLS_CLIENT_ENABLE
              value: {{ .Values.service.tls.client_enable | quote }}
            - name: ZOO_TLS_CLIENT_KEYSTORE_FILE
              value: {{ .Values.service.tls.client_keystore_path | quote }}
            - name: ZOO_TLS_CLIENT_KEYSTORE_PASSWORD
              value: {{ .Values.service.tls.client_keystore_password | quote }}
            - name: ZOO_TLS_CLIENT_TRUSTSTORE_FILE
              value: {{ .Values.service.tls.client_truststore_path | quote }}
            - name: ZOO_TLS_CLIENT_TRUSTSTORE_PASSWORD
              value: {{ .Values.service.tls.client_truststore_password | quote }}
            {{ end }}
            {{- if .Values.service.tls.quorum_enable }}
            - name: ZOO_TLS_QUORUM_ENABLE
              value: {{ .Values.service.tls.quorum_enable | quote }}
            - name: ZOO_TLS_QUORUM_KEYSTORE_FILE
              value: {{ .Values.service.tls.quorum_keystore_path | quote }}
            - name: ZOO_TLS_QUORUM_KEYSTORE_PASSWORD
              value: {{ .Values.service.tls.quorum_keystore_password | quote }}
            - name: ZOO_TLS_QUORUM_TRUSTSTORE_FILE
              value: {{ .Values.service.tls.quorum_truststore_path | quote }}
            - name: ZOO_TLS_QUORUM_TRUSTSTORE_PASSWORD
              value: {{ .Values.service.tls.quorum_truststore_password | quote }}
            {{ end }}
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.name
            {{- if .Values.extraEnvVars }}
            {{- toYaml .Values.extraEnvVars | nindent 12 }}
            {{- end }}
          ports:
            {{ if not .Values.service.tls.disable_base_client_port }}
            - name: client
              containerPort: {{ .Values.service.port }}
            {{ end }}
            {{ if .Values.service.tls.client_enable }}
            - name: client-tls
              containerPort: {{ .Values.service.tls.client_port }}
            {{ end }}
            - name: follower
              containerPort: {{ .Values.service.followerPort }}
            - name: election
              containerPort: {{ .Values.service.electionPort }}
            {{- if .Values.metrics.enabled }}
            - name: metrics
              containerPort: {{ .Values.metrics.containerPort }}
            {{- end }}
          {{- if .Values.livenessProbe.enabled }}
          livenessProbe:
            exec:
              {{- if not .Values.service.tls.disable_base_client_port }}
              command: ['/bin/bash', '-c', 'echo "ruok" | timeout {{ .Values.livenessProbe.probeCommandTimeout }} nc -w {{ .Values.livenessProbe.probeCommandTimeout }} localhost {{ .Values.service.port }} | grep imok']
              {{- else }}
              command: ['/bin/bash', '-c', 'echo "ruok" | timeout {{ .Values.livenessProbe.probeCommandTimeout }} openssl s_client -quiet -crlf -connect localhost:{{ .Values.service.tls.client_port }} | grep imok']
              {{- end }}
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.livenessProbe.successThreshold }}
            failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.readinessProbe.enabled }}
          readinessProbe:
            exec:
              {{- if not .Values.service.tls.disable_base_client_port }}
              command: ['/bin/bash', '-c', 'echo "ruok" | timeout {{ .Values.readinessProbe.probeCommandTimeout }} nc -w {{ .Values.readinessProbe.probeCommandTimeout }} localhost {{ .Values.service.port }} | grep imok']
              {{- else }}
              command: ['/bin/bash', '-c', 'echo "ruok" | timeout {{ .Values.readinessProbe.probeCommandTimeout }} openssl s_client -quiet -crlf -connect localhost:{{ .Values.service.tls.client_port }} | grep imok']
              {{- end }}
            initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.readinessProbe.successThreshold }}
            failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: /bitnami/zookeeper
            {{- if .Values.dataLogDir }}
            - name: data-log
              mountPath: {{ .Values.dataLogDir }}
            {{- end }}
            {{- if .Values.config }}
            - name: config
              mountPath: /opt/bitnami/zookeeper/conf/zoo.cfg
              subPath: zoo.cfg
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- toYaml .Values.extraVolumeMounts | nindent 12 }}
            {{- end }}
      volumes:
        {{- if .Values.config }}
        - name: config
          configMap:
            name: {{ template "zookeeper.fullname" . }}
        {{- end }}
        {{- if and .Values.persistence.enabled .Values.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ printf "%s" (tpl .Values.persistence.existingClaim .) }}
        {{- else if not .Values.persistence.enabled }}
        - name: data
          emptyDir: {}
        {{- end }}
        {{- if and .Values.persistence.enabled .Values.persistence.dataLogDir.existingClaim }}
        - name: data-log
          persistentVolumeClaim:
            claimName: {{ printf "%s" (tpl .Values.persistence.dataLogDir.existingClaim .) }}
        {{- else if and ( not .Values.persistence.enabled ) .Values.dataLogDir }}
        - name: data-log
          emptyDir: {}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- toYaml .Values.extraVolumes | nindent 8 }}
        {{- end }}
  {{- if and .Values.persistence.enabled (not (and .Values.persistence.existingClaim .Values.persistence.dataLogDir.existingClaim) )}}
  volumeClaimTemplates:
  {{- if not .Values.persistence.existingClaim }}
    - metadata:
        name: data
        annotations:
        {{- range $key, $value := .Values.persistence.annotations }}
          {{ $key }}: {{ $value }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.size | quote }}
        {{- include "zookeeper.storageClass" . | nindent 8 }}
    {{- end }}
    {{- if and (not .Values.persistence.dataLogDir.existingClaim) .Values.dataLogDir }}
    - metadata:
        name: data-log
        annotations:
        {{- range $key, $value := .Values.persistence.annotations }}
          {{ $key }}: {{ $value }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.dataLogDir.size | quote }}
        {{- include "zookeeper.storageClass" . | nindent 8 }}
    {{- end }}
  {{- end }}
