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

{{- $replicaCount := int .Values.broker.replicaCount }}
{{- if or (gt $replicaCount 0) .Values.broker.autoscaling.hpa.enabled }}
apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ template "kafka.broker.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: broker
    app.kubernetes.io/part-of: kafka
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  podManagementPolicy: {{ .Values.broker.podManagementPolicy }}
  {{- if not .Values.broker.autoscaling.hpa.enabled }}
  replicas: {{ .Values.broker.replicaCount }}
  {{- end }}
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.broker.podLabels .Values.commonLabels ) "context" . ) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/component: broker
      app.kubernetes.io/part-of: kafka
  serviceName: {{ printf "%s-headless" (include "kafka.broker.fullname" .) | trunc 63 | trimSuffix "-" }}
  updateStrategy: {{- include "common.tplvalues.render" (dict "value" .Values.broker.updateStrategy "context" $ ) | nindent 4 }}
  {{- if .Values.broker.minReadySeconds }}
  minReadySeconds: {{ .Values.broker.minReadySeconds }}
  {{- end }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: broker
        app.kubernetes.io/part-of: kafka
      annotations:
        {{- if include "kafka.broker.createConfigmap" . }}
        checksum/configuration: {{ include (print $.Template.BasePath "/broker/configmap.yaml") . | sha256sum }}
        {{- end }}
        {{- if or (include "kafka.createSaslSecret" .) (not .Values.existingKraftSecret) }}
        checksum/secret: {{ include (print $.Template.BasePath "/secrets.yaml") . | sha256sum }}
        {{- end }}
         {{- if include "kafka.createTlsSecret" . }}
        checksum/tls-secret: {{ include (print $.Template.BasePath "/tls-secret.yaml") . | sha256sum }}
        {{- end }}
        {{- if include "kafka.metrics.jmx.createConfigmap" . }}
        checksum/jmx-configuration: {{ include (print $.Template.BasePath "/metrics/jmx-configmap.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.broker.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.broker.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
    spec:
      {{- include "kafka.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.broker.automountServiceAccountToken }}
      {{- if .Values.broker.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.broker.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      hostNetwork: {{ .Values.broker.hostNetwork }}
      hostIPC: {{ .Values.broker.hostIPC }}
      {{- if .Values.broker.schedulerName }}
      schedulerName: {{ .Values.broker.schedulerName | quote }}
      {{- end }}
      {{- if .Values.broker.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.broker.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.broker.podAffinityPreset "component" "broker" "customLabels" $podLabels "topologyKey" .Values.broker.topologyKey "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.broker.podAntiAffinityPreset "component" "broker" "customLabels" $podLabels "topologyKey" .Values.broker.topologyKey "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.broker.nodeAffinityPreset.type "key" .Values.broker.nodeAffinityPreset.key "values" .Values.broker.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.broker.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.broker.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.broker.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.broker.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.broker.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.broker.topologySpreadConstraints "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.broker.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.broker.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if .Values.broker.priorityClassName }}
      priorityClassName: {{ .Values.broker.priorityClassName }}
      {{- end }}
      {{- if .Values.controller.runtimeClassName }}
      runtimeClassName: {{ .Values.controller.runtimeClassName }}
      {{- end }}
      {{- if .Values.broker.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.broker.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "kafka.serviceAccountName" . }}
      enableServiceLinks: {{ .Values.broker.enableServiceLinks }}
      initContainers:
        {{- if and .Values.defaultInitContainers.volumePermissions.enabled .Values.broker.persistence.enabled }}
        {{- include "kafka.defaultInitContainers.volumePermissions" (dict "context" . "role" "broker") | nindent 8 }}
        {{- end }}
        {{- if and .Values.externalAccess.enabled .Values.defaultInitContainers.autoDiscovery.enabled }}
        {{- include "kafka.defaultInitContainers.autoDiscovery" (dict "context" . "role" "broker") | nindent 8 }}
        {{- end }}
        {{- include "kafka.defaultInitContainers.prepareConfig" (dict "context" . "role" "broker") | nindent 8 }}
        {{- if .Values.broker.initContainers }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.broker.initContainers "context" $ ) | nindent 8 }}
        {{- end }}
        {{- if .Values.initContainers }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.initContainers "context" $ ) | nindent 8 }}
        {{- end }}
      containers:
        - name: kafka
          image: {{ include "kafka.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.broker.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.broker.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.broker.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.broker.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.broker.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.broker.args "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: KAFKA_HEAP_OPTS
              value: {{ coalesce .Values.broker.heapOpts .Values.heapOpts | quote }}
            - name: KAFKA_CFG_PROCESS_ROLES
              value: broker
            {{- include "kafka.commonEnv" . | nindent 12 }}
            {{- if .Values.broker.extraEnvVars }}
            {{- include "common.tplvalues.render" ( dict "value" .Values.broker.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" ( dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          {{- if or .Values.broker.extraEnvVarsCM .Values.extraEnvVarsCM .Values.broker.extraEnvVarsSecret .Values.extraEnvVarsSecret }}
          envFrom:
            {{- if .Values.broker.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.broker.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.broker.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.broker.extraEnvVarsSecret "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- end }}
          ports:
            - name: client
              containerPort: {{ .Values.listeners.client.containerPort }}
            - name: interbroker
              containerPort: {{ .Values.listeners.interbroker.containerPort }}
            {{- if .Values.externalAccess.enabled }}
            - name: external
              containerPort: {{ .Values.listeners.external.containerPort }}
            {{- end }}
            {{- if .Values.listeners.extraListeners }}
            {{- include "kafka.extraListeners.containerPorts" . | nindent 12 }}
            {{- end }}
            {{- if .Values.broker.extraContainerPorts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.broker.extraContainerPorts "context" $) | nindent 12 }}
            {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.broker.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.broker.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.broker.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.broker.livenessProbe "enabled") "context" $) | nindent 12 }}
            exec:
              command:
                - pgrep
                - -f
                - kafka
          {{- end }}
          {{- if .Values.broker.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.broker.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.broker.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.broker.readinessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: "client"
          {{- end }}
          {{- if .Values.broker.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.broker.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.broker.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.broker.startupProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: "client"
          {{- end }}
          {{- end }}
          {{- if .Values.broker.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.broker.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.broker.resources }}
          resources: {{- toYaml .Values.broker.resources | nindent 12 }}
          {{- else if ne .Values.broker.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.broker.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.broker.persistence.mountPath }}
            - name: logs
              mountPath: {{ .Values.broker.logPersistence.mountPath }}
            - name: kafka-config
              mountPath: /opt/bitnami/kafka/config/server.properties
              subPath: server.properties
            - name: tmp
              mountPath: /tmp
            {{- if or .Values.log4j2 .Values.existingLog4j2ConfigMap }}
            - name: log4j2-config
              mountPath: /opt/bitnami/kafka/config/log4j2.yaml
              subPath: log4j2.yaml
            {{- end }}
            {{- if include "kafka.sslEnabled" . }}
            - name: kafka-shared-certs
              mountPath: /opt/bitnami/kafka/config/certs
              readOnly: true
            {{- end }}
            {{- if and .Values.usePasswordFiles (include "kafka.saslEnabled" .) }}
            - name: kafka-sasl
              mountPath: /opt/bitnami/kafka/config/secrets
              readOnly: true
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
            {{- if .Values.broker.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.broker.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        {{- if .Values.metrics.jmx.enabled }}
        - name: jmx-exporter
          image: {{ include "kafka.metrics.jmx.image" . }}
          imagePullPolicy: {{ .Values.metrics.jmx.image.pullPolicy | quote }}
          {{- if .Values.metrics.jmx.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.metrics.jmx.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.jmx.containerPorts.metrics | quote }}
            - /etc/jmx-kafka/jmx-kafka-prometheus.yml
          {{- end }}
          ports:
            - name: metrics
              containerPort: {{ .Values.metrics.jmx.containerPorts.metrics }}
          {{- if .Values.metrics.jmx.resources }}
          resources: {{- toYaml .Values.metrics.jmx.resources | nindent 12 }}
          {{- else if ne .Values.metrics.jmx.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.metrics.jmx.resourcesPreset) | nindent 12 }}
          {{- end }}
          {{- if .Values.metrics.jmx.livenessProbe.enabled }}
          livenessProbe: {{- omit .Values.metrics.jmx.livenessProbe "enabled" | toYaml | nindent 12 }}
            tcpSocket:
              port: metrics
          {{- end }}
          {{- if .Values.metrics.jmx.readinessProbe.enabled }}
          readinessProbe: {{- omit .Values.metrics.jmx.readinessProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /
              port: metrics
          {{- end }}
          volumeMounts:
            - name: jmx-config
              mountPath: /etc/jmx-kafka
        {{- end }}
        {{- if .Values.broker.sidecars }}
        {{- include "common.tplvalues.render" (dict "value" .Values.broker.sidecars "context" $) | nindent 8 }}
        {{- end }}
        {{- if .Values.sidecars }}
        {{- include "common.tplvalues.render" (dict "value" .Values.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: kafka-configmaps
          configMap:
            name: {{ include "kafka.broker.configmapName" . }}
        - name: kafka-secret-config
        {{- if (include "kafka.broker.secretConfigExists" .) }}
          secret:
            secretName: {{ include "kafka.broker.secretConfigName" . }}
        {{- else }}
          emptyDir: {}
        {{- end }}
        - name: kafka-config
          emptyDir: {}
        - name: tmp
          emptyDir: {}
        - name: init-shared
          emptyDir: {}
        {{- if or .Values.log4j2 .Values.existingLog4j2ConfigMap }}
        - name: log4j2-config
          configMap:
            name: {{ include "kafka.log4j2.configMapName" . }}
        {{- end }}
        {{- if .Values.metrics.jmx.enabled }}
        - name: jmx-config
          configMap:
            name: {{ include "kafka.metrics.jmx.configmapName" . }}
        {{- end }}
        {{- if include "kafka.sslEnabled" . }}
        - name: kafka-shared-certs
          emptyDir: {}
        {{- if or .Values.tls.existingSecret .Values.tls.autoGenerated.enabled }}
        - name: kafka-certs
          projected:
            defaultMode: 256
            sources:
              - secret:
                  name: {{ include "kafka.tlsSecretName" . }}
              {{- if .Values.tls.jksTruststoreSecret }}
              - secret:
                  name: {{ .Values.tls.jksTruststoreSecret }}
              {{- end }}
        {{- end }}
        {{- end }}
        {{- if and .Values.usePasswordFiles (include "kafka.saslEnabled" .) }}
        - name: kafka-sasl
          projected:
            sources:
              - secret:
                  name:  {{ include "kafka.saslSecretName" . }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
        {{- if .Values.broker.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.broker.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
        {{- if not .Values.broker.persistence.enabled }}
        - name: data
          emptyDir: {}
        {{- else if .Values.broker.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ printf "%s" (tpl .Values.broker.persistence.existingClaim .) }}
        {{- end }}
        {{- if not .Values.broker.logPersistence.enabled }}
        - name: logs
          emptyDir: {}
        {{- else if .Values.broker.logPersistence.existingClaim }}
        - name: logs
          persistentVolumeClaim:
            claimName: {{ printf "%s" (tpl .Values.broker.logPersistence.existingClaim .) }}
        {{- end }}
  {{- if or (and .Values.broker.persistence.enabled (not .Values.broker.persistence.existingClaim)) (and .Values.broker.logPersistence.enabled (not .Values.broker.logPersistence.existingClaim)) }}
  {{- if .Values.broker.persistentVolumeClaimRetentionPolicy.enabled }}
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: {{ .Values.broker.persistentVolumeClaimRetentionPolicy.whenDeleted }}
    whenScaled: {{ .Values.broker.persistentVolumeClaimRetentionPolicy.whenScaled }}
  {{- end }}
  volumeClaimTemplates:
    {{- if and .Values.broker.persistence.enabled (not .Values.broker.persistence.existingClaim) }}
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: data
        {{- if .Values.broker.persistence.annotations }}
        annotations: {{- include "common.tplvalues.render" (dict "value" .Values.broker.persistence.annotations "context" $) | nindent 10 }}
        {{- end }}
        {{- if .Values.broker.persistence.labels }}
        labels: {{- include "common.tplvalues.render" (dict "value" .Values.broker.persistence.labels "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.broker.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.broker.persistence.size | quote }}
        {{- include "common.storage.class" (dict "persistence" .Values.broker.persistence "global" .Values.global) | nindent 8 }}
        {{- if .Values.broker.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.broker.persistence.selector "context" $) | nindent 10 }}
        {{- end -}}
    {{- end }}
    {{- if and .Values.broker.logPersistence.enabled (not .Values.broker.logPersistence.existingClaim) }}
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: logs
        {{- if .Values.broker.logPersistence.annotations }}
        annotations: {{- include "common.tplvalues.render" (dict "value" .Values.broker.logPersistence.annotations "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.broker.logPersistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.broker.logPersistence.size | quote }}
        {{- include "common.storage.class" (dict "persistence" .Values.broker.persistence "global" .Values.global) | nindent 8 }}
        {{- if .Values.broker.logPersistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.broker.logPersistence.selector "context" $) | nindent 10 }}
        {{- end -}}
    {{- end }}
  {{- end }}
{{- end }}
