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

apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ include "dremio.coordinator.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: dremio
    app.kubernetes.io/component: coordinator
    {{- /* We need an extra label that applies to both master and non-master coordinators. Taken from upstream dremio chart */}}
    app: dremio-coordinator
  {{- if or .Values.coordinator.statefulsetAnnotations .Values.commonAnnotations }}
  {{- $annotations := include "common.tplvalues.merge" (dict "values" (list .Values.coordinator.statefulsetAnnotations .Values.commonAnnotations) "context" .) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.coordinator.autoscaling.hpa.enabled }}
  replicas: {{ .Values.coordinator.replicaCount }}
  {{- end }}
  podManagementPolicy: {{ .Values.coordinator.podManagementPolicy | quote }}
  {{- $podLabels := include "common.tplvalues.merge" (dict "values" (list .Values.coordinator.podLabels .Values.commonLabels) "context" .) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/part-of: dremio
      app.kubernetes.io/component: coordinator
      app: dremio-coordinator
  serviceName: {{ template "dremio.headlessServiceName" . }}
  {{- if .Values.coordinator.updateStrategy }}
  updateStrategy: {{- toYaml .Values.coordinator.updateStrategy | nindent 4 }}
  {{- end }}
  template:
    metadata:
      annotations:
        checksum/dremio-conf-cm: {{ include (print $.Template.BasePath "/coordinator/configmap-dremio-conf.yaml") . | sha256sum }}
        checksum/dremio-conf-secret: {{ include (print $.Template.BasePath "/coordinator/secret-dremio-conf.yaml") . | sha256sum }}
        checksum/core-site-secret: {{ include (print $.Template.BasePath "/secret-core-site.yaml") . | sha256sum }}
      {{- if .Values.coordinator.podAnnotations }}
      {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.podAnnotations "context" $) | nindent 8 }}
      {{- end }}
      labels: {{- include "common.labels.standard" (dict "customLabels" $podLabels "context" $) | nindent 8 }}
        app.kubernetes.io/part-of: dremio
        app.kubernetes.io/component: coordinator
        app: dremio-coordinator
    spec:
      {{- include "dremio.imagePullSecrets" . | nindent 6 }}
      serviceAccountName: {{ template "dremio.coordinator.serviceAccountName" . }}
      automountServiceAccountToken: {{ .Values.coordinator.automountServiceAccountToken }}
      {{- if .Values.coordinator.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.coordinator.affinity }}
      affinity: {{- include "common.tplvalues.render" ( dict "value" .Values.coordinator.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.coordinator.podAffinityPreset "component" "coordinator" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.coordinator.podAntiAffinityPreset "component" "coordinator" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.coordinator.nodeAffinityPreset.type "key" .Values.coordinator.nodeAffinityPreset.key "values" .Values.coordinator.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.coordinator.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" ( dict "value" .Values.coordinator.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.coordinator.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.coordinator.priorityClassName }}
      priorityClassName: {{ .Values.coordinator.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.coordinator.schedulerName }}
      schedulerName: {{ .Values.coordinator.schedulerName | quote }}
      {{- end }}
      {{- if .Values.coordinator.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.coordinator.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.coordinator.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.coordinator.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.coordinator.terminationGracePeriodSeconds }}
      {{- end }}
      initContainers:
        {{- /* As most Bitnami charts have volumePermissions in the root, we add a volumePermissions.enabled check to maintain a similar UX */}}
        {{- if and (or .Values.defaultInitContainers.volumePermissions.enabled ((.Values.volumePermissions).enabled)) .Values.coordinator.persistence.enabled }}
        {{- include "dremio.init-containers.volume-permissions" (dict "context" . "componentValues" .Values.coordinator) | nindent 8}}
        {{- end }}
        {{- if .Values.defaultInitContainers.copyDefaultConf.enabled }}
        {{- include "dremio.init-containers.copy-default-conf" . | nindent 8 }}
        {{- end }}
        {{- if .Values.defaultInitContainers.wait.enabled }}
        {{- if or (eq .Values.dremio.distStorageType "minio") (eq .Values.dremio.distStorageType "aws") }}
        {{- include "dremio.init-containers.wait-for-s3" . | nindent 8 }}
        {{- end }}
        {{- include "dremio.init-containers.wait-for-zookeeper" . | nindent 8 }}
        {{- include "dremio.init-containers.wait-for-master-coordinator" . | nindent 8 }}
        {{- end }}
        {{- if .Values.defaultInitContainers.generateConf.enabled }}
        {{- include "dremio.init-containers.generate-conf" (dict "context" . "mountDremioConfSecret" (include "dremio.coordinator.dremio-conf.useSecret" .)) | nindent 8 }}
        {{- end }}
        {{- if and .Values.dremio.tls.enabled .Values.defaultInitContainers.initCerts.enabled }}
        {{- include "dremio.init-containers.init-certs" . | nindent 8 }}
        {{- end }}
        {{- if and (eq .Values.dremio.distStorageType "minio") .Values.minio.enabled .Values.minio.tls.enabled }}
        {{- include "dremio.init-containers.importMinIOCert" . | nindent 8 }}
        {{- end }}
        {{- if .Values.coordinator.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.initContainers "context" $) | nindent 8 }}
        {{- end }}
      containers:
        - name: dremio
          image: {{ template "dremio.image" . }}
          imagePullPolicy: {{ .Values.dremio.image.pullPolicy }}
          {{- if .Values.coordinator.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.coordinator.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.coordinator.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.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.coordinator.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.args "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.dremio.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: DREMIO_JAVA_SERVER_EXTRA_OPTS
              value: |
                {{- if and (not .Values.minio.enabled) .Values.externalS3.disableCertChecking }}
                -Dcom.amazonaws.sdk.disableCertChecking=true
                {{- end }}
                {{- if .Values.metrics.enabled }}
                -Dcom.sun.management.jmxremote.port={{ .Values.dremio.containerPorts.jmx }}
                -Dcom.sun.management.jmxremote.authenticate=false
                -Dcom.sun.management.jmxremote.ssl=false
                {{- end }}
                {{- if .Values.coordinator.extraJavaOpts }}
                {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.extraJavaOpts "context" $) | nindent 16 }}
                {{- end }}
            - name: DREMIO_MAX_MEMORY_SIZE_MB
              valueFrom:
                resourceFieldRef:
                  containerName: dremio
                  resource: limits.memory
                  divisor: 1Mi
            {{- if .Values.coordinator.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.coordinator.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.coordinator.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.coordinator.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.coordinator.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if .Values.coordinator.resources }}
          resources: {{- toYaml .Values.coordinator.resources | nindent 12 }}
          {{- else if ne .Values.coordinator.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.coordinator.resourcesPreset) | nindent 12 }}
          {{- end }}
          ports:
            - containerPort: {{ .Values.dremio.containerPorts.web }}
              name: web
            - containerPort: {{ .Values.dremio.containerPorts.client }}
              name: client
            - containerPort: {{ .Values.dremio.containerPorts.flight }}
              name: flight
            - containerPort: {{ .Values.dremio.containerPorts.liveness }}
              name: liveness
            - containerPort: {{ .Values.dremio.containerPorts.fabric }}
              name: server-fabric
            - containerPort: {{ .Values.dremio.containerPorts.conduit }}
              name: server-conduit
            {{- if .Values.metrics.enabled }}
            - containerPort: {{ .Values.dremio.containerPorts.jmx }}
              name: jmx
            {{- end }}
            {{- if .Values.coordinator.extraContainerPorts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.extraContainerPorts "context" $) | nindent 12 }}
            {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.coordinator.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.coordinator.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.coordinator.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: liveness
          {{- end }}
          {{- if .Values.coordinator.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.coordinator.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.coordinator.readinessProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /
              port: web
              scheme: {{ ternary "HTTPS" "HTTP" .Values.dremio.tls.enabled }}
          {{- end }}
          {{- if .Values.coordinator.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.coordinator.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.coordinator.startupProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: liveness
          {{- end }}
          {{- end }}
          {{- if .Values.coordinator.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.coordinator.persistence.mountPath }}
              {{- if .Values.coordinator.persistence.subPath }}
              subPath: {{ .Values.coordinator.persistence.subPath }}
              {{- end }}
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/dremio/tmp
              subPath: app-tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/dremio/run
              subPath: app-run-dir
            - name: empty-dir
              mountPath: /opt/bitnami/dremio/log
              subPath: app-log-dir
            - name: empty-dir
              mountPath: /opt/bitnami/dremio/conf
              subPath: app-conf-dir
            {{- if .Values.dremio.tls.enabled }}
            - name: empty-dir
              mountPath: /opt/bitnami/dremio/certs
              subPath: app-processed-certs-dir
            {{- end }}
            {{- if and (eq .Values.dremio.distStorageType "minio") .Values.minio.enabled .Values.minio.tls.enabled }}
            - name: empty-dir
              mountPath: /opt/bitnami/java/lib/security/cacerts
              subPath: java-cacerts-dir/cacerts
            {{- end }}
            {{- if .Values.metrics.enabled }}
            - name: metrics-configuration
              mountPath: /opt/bitnami/dremio/conf/dremio-telemetry.yaml
              subPath: dremio-telemetry.yaml
            {{- end }}
          {{- if .Values.coordinator.extraVolumeMounts }}
          {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.extraVolumeMounts "context" $) | nindent 12 }}
          {{- end }}
        {{- if .Values.metrics.enabled }}
        - name: metrics
          image: {{ include "dremio.metrics.image" . }}
          imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
          {{- if .Values.metrics.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.metrics.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }}
          {{- else }}
          command:
            - java
          args:
            - -XX:MaxRAMPercentage=100
            - -XshowSettings:vm
            - -jar
            - jmx_prometheus_standalone.jar
            - {{ .Values.metrics.containerPorts.metrics | quote }}
            - /etc/jmx-dremio/jmx-prometheus.yml
            {{- if .Values.metrics.extraArgs }}
            {{- include "common.tplvalues.render" ( dict "value" .Values.metrics.extraArgs "context" $) | nindent 12 }}
            {{- end -}}
          {{- end }}
          ports:
            - name: metrics
              containerPort: {{ .Values.metrics.containerPorts.metrics }}
          {{- if .Values.metrics.resources }}
          resources: {{- toYaml .Values.metrics.resources | nindent 12 }}
          {{- else if ne .Values.metrics.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.metrics.resourcesPreset) | nindent 12 }}
          {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.metrics.livenessProbe.enabled }}
          livenessProbe: {{- omit .Values.metrics.livenessProbe "enabled" | toYaml | nindent 12 }}
            tcpSocket:
              port: metrics
          {{- end }}
          {{- if .Values.metrics.readinessProbe.enabled }}
          readinessProbe: {{- omit .Values.metrics.readinessProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /
              port: metrics
          {{- end }}
          {{- if .Values.metrics.startupProbe.enabled }}
          startupProbe: {{- omit .Values.metrics.startupProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /
              port: metrics
          {{- end }}
          {{- end }}
          volumeMounts:
            - name: metrics-configuration
              mountPath: /etc/jmx-dremio/jmx-prometheus.yml
              subPath: jmx-prometheus.yml
        {{- end }}
        {{- if .Values.coordinator.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.coordinator.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if .Values.usePasswordFiles }}
        {{- if or .Values.dremio.tls.passwordSecret .Values.dremio.tls.password .Values.dremio.tls.autoGenerated.enabled .Values.dremio.tls.usePemCerts }}
        - name: keystore-password
          secret:
            secretName: {{ include "dremio.tls.passwordSecretName" . }}
            items:
              - key: keystore-password
                path: DREMIO_KEYSTORE_PASSWORD
        {{- end }}
        {{- if or (eq .Values.dremio.distStorageType "minio") (eq .Values.dremio.distStorageType "aws") }}
        - name: s3-credentials
          secret:
            secretName: {{ include "dremio.s3.secretName" . }}
            items:
              - key: {{ include "dremio.s3.accessKeyIDKey" . }}
                path: DREMIO_AWS_ACCESS_KEY_ID
              - key: {{ include "dremio.s3.secretAccessKeyKey" . }}
                path: DREMIO_AWS_SECRET_ACCESS_KEY
        {{- end }}
        {{- end }}
        - name: input-dremio-conf-cm
          configMap:
            name: {{ include "dremio.coordinator.dremio-conf.configmapName" . }}
        {{- if (include "dremio.coordinator.dremio-conf.useSecret" .) }}
        - name: input-dremio-conf-secret
          secret:
            secretName: {{ include "dremio.coordinator.dremio-conf.secretName" . }}
        {{- end }}
        - name: input-core-site
          secret:
            secretName: {{ include "dremio.core-site.secretName" . }}
        {{- if .Values.metrics.enabled }}
        - name: metrics-configuration
          configMap:
            name: {{ include "dremio.metrics.configmapName" . }}
        {{- end }}
        {{- if .Values.dremio.tls.enabled }}
        - name: input-tls-certs
          secret:
            secretName: {{ include "dremio.tls.secretName" . }}
            items:
              {{- if .Values.dremio.tls.usePemCerts }}
              - key: {{ .Values.dremio.tls.certFilename }}
                path: tls.crt
              - key: {{ .Values.dremio.tls.certKeyFilename }}
                path: tls.key
              {{- else }}
              - key: {{ .Values.dremio.tls.keystoreFilename }}
                path: dremio.jks
              {{- end }}
        {{- end }}
        {{- if and .Values.coordinator.persistence.enabled .Values.coordinator.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ .Values.coordinator.persistence.existingClaim }}
        {{- else if (not .Values.coordinator.persistence.enabled)}}
        - name: data
          emptyDir: {}
        {{- end }}
        {{- if and (eq .Values.dremio.distStorageType "minio") .Values.minio.enabled .Values.minio.tls.enabled }}
        - name: minio-public-cert
          secret:
            secretName: {{ printf "%s-crt" ( include "dremio.minio.fullname" . ) }}
            items:
            - key: {{ ternary "tls.crt" .Values.minio.tls.server.certFilename .Values.minio.tls.autoGenerated.enabled }}
              path: public.crt
        {{- end }}
        {{- if .Values.coordinator.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
  {{- if .Values.coordinator.persistence.enabled }}
  volumeClaimTemplates:
    - metadata:
        name: data
        {{- if or .Values.coordinator.persistence.annotations .Values.commonAnnotations }}
        {{- $claimAnnotations := include "common.tplvalues.merge" (dict "values" .Values.coordinator.persistence.annotations .Values.commonAnnotations "context" .) | fromYaml }}
        annotations: {{- include "common.tplvalues.render" ( dict "value" $claimAnnotations "context" $ ) | nindent 10 }}
        {{- end }}
        {{- if .Values.commonLabels }}
        labels: {{- include "common.labels.matchLabels" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.coordinator.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        {{- if .Values.coordinator.persistence.dataSource }}
        dataSource: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.persistence.dataSource "context" $) | nindent 10 }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.coordinator.persistence.size | quote }}
        {{- if .Values.coordinator.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.coordinator.persistence.selector "context" $) | nindent 10 }}
        {{- end }}
        {{- include "common.storage.class" (dict "persistence" .Values.coordinator.persistence "global" .Values.global) | nindent 8 }}
  {{- end }}
