apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ template "cp-kafka.fullname" . }}
  labels:
    app: {{ template "cp-kafka.name" . }}
    chart: {{ template "cp-kafka.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  selector:
    matchLabels:
      app: {{ template "cp-kafka.name" . }}
      release: {{ .Release.Name }}
  serviceName: {{ template "cp-kafka.fullname" . }}-headless
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ default 3 .Values.brokers }}
  updateStrategy:
    type: {{ .Values.updateStrategy }}
  template:
    metadata:
      labels:
        app: {{ template "cp-kafka.name" . }}
        release: {{ .Release.Name }}
      {{- if or .Values.podAnnotations .Values.prometheus.jmx.enabled }}
      annotations:
      {{- range $key, $value := .Values.podAnnotations }}
        {{ $key }}: {{ $value | quote }}
      {{- end }}
      {{- if .Values.prometheus.jmx.enabled }}
        prometheus.io/scrape: "true"
        prometheus.io/port: {{ .Values.prometheus.jmx.port | quote }}
      {{- end }}
      {{- end }}
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                  - key: "app"
                    operator: In
                    values:
                    - {{ template "cp-kafka.name" . }}
                  - key: "release"
                    operator: In
                    values:
                    - {{ .Release.Name }}
              topologyKey: "kubernetes.io/hostname"
      containers:
      {{- if .Values.prometheus.jmx.enabled }}
      - name: prometheus-jmx-exporter
        image: "{{ .Values.prometheus.jmx.image }}:{{ .Values.prometheus.jmx.imageTag }}"
        imagePullPolicy: "{{ .Values.prometheus.jmx.imagePullPolicy }}"
        command:
        - java
        - -XX:+UnlockExperimentalVMOptions
        - -XX:+UseCGroupMemoryLimitForHeap
        - -XX:MaxRAMFraction=1
        - -XshowSettings:vm
        - -jar
        - jmx_prometheus_httpserver.jar
        - {{ .Values.prometheus.jmx.port | quote }}
        - /etc/jmx-kafka/jmx-kafka-prometheus.yml
        ports:
        - containerPort: {{ .Values.prometheus.jmx.port }}
        resources:
{{ toYaml .Values.prometheus.jmx.resources | indent 10 }}
        volumeMounts:
        - name: jmx-config
          mountPath: /etc/jmx-kafka
      {{- end }}
      - name: {{ template "cp-kafka.name" . }}-broker
{{- if .Values.global.enterprise }}
        image: "{{ .Values.enterpriseImage }}:{{ .Values.imageTag }}"
{{- else }}
        image: "{{ .Values.image }}:{{ .Values.imageTag }}"
{{- end }}
        imagePullPolicy: "{{ .Values.imagePullPolicy }}"
        ports:
        - containerPort: 9092
          name: kafka
        {{- if .Values.prometheus.jmx.enabled }}
        - containerPort: {{ .Values.jmx.port }}
          name: jmx
        {{- end }}
        {{- if .Values.nodeport.enabled }}
          {{- $brokers := .Values.brokers | int }}
          {{- $root := . }}
          {{- range $i, $e := until $brokers }}
        - containerPort: {{ add $root.Values.nodeport.firstListenerPort $i }}
          name: nodeport-{{ $i }}
          {{- end }}
        {{- end }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        env:
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: HOST_IP
          valueFrom:
            fieldRef:
              fieldPath: status.hostIP
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: KAFKA_HEAP_OPTS
          value: {{ .Values.heapOptions }}
        - name: KAFKA_ZOOKEEPER_CONNECT
          value: {{ include "cp-kafka.cp-zookeeper.service-name" . | quote }}
        - name: KAFKA_LOG_DIRS
          value: {{ include "cp-kafka.log.dirs" . | quote }}
        {{- if .Values.global.enterprise }}
        - name: KAFKA_METRIC_REPORTERS
          value: "io.confluent.metrics.reporter.ConfluentMetricsReporter"
        - name: CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS
          value: {{ printf "PLAINTEXT://%s:9092" (include "cp-kafka.cp-kafka-headless.fullname" .) | quote }}
        {{- end }}
        {{- range $key, $value := .Values.configurationOverrides }}
        - name: {{ printf "KAFKA_%s" $key | replace "." "_" | upper | quote }}
          value: {{ $value | quote }}
        {{- end }}
        {{- range $key, $value := .Values.customEnv }}
        - name: {{ $key | quote }}
          value: {{ $value | quote }}
        {{- end }}
        {{- if .Values.jmx.port }}
        - name: KAFKA_JMX_PORT
          value: "{{ .Values.jmx.port }}"
        {{- end }}
        # This is required because the Downward API does not yet support identification of
        # pod numbering in statefulsets. Thus, we are required to specify a command which
        # allows us to extract the pod ID for usage as the Kafka Broker ID.
        # See: https://github.com/kubernetes/kubernetes/issues/31218
        command:
        - sh
        - -exc
        - |
          export KAFKA_BROKER_ID=${HOSTNAME##*-} && \
          export KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://${POD_NAME}.{{ template "cp-kafka.fullname" . }}-headless.${POD_NAMESPACE}:9092{{ include "cp-kafka.configuration.advertised.listeners" . }} && \
          exec /etc/confluent/docker/run
        volumeMounts:
        {{- $disksPerBroker := .Values.persistence.disksPerBroker | int }}
        {{- range $k, $e := until $disksPerBroker }}
        - name: datadir-{{$k}}
          mountPath: /opt/kafka/data-{{$k}}
        {{- end }}
      {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.imagePullSecrets | indent 8 }}
      {{- end }}
      volumes:
      {{- if not .Values.persistence.enabled }}
      - name: datadir-0
        emptyDir: {}
      {{- end }}
      {{- if .Values.prometheus.jmx.enabled }}
      - name: jmx-config
        configMap:
          name: {{ template "cp-kafka.fullname" . }}-jmx-configmap
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
      {{- end }}
  {{- if .Values.persistence.enabled }}
  volumeClaimTemplates:
  {{- $disksPerBroker := .Values.persistence.disksPerBroker | int }}
  {{- $root := . }}
  {{- range $k, $e := until $disksPerBroker }}
  - metadata:
      name: datadir-{{$k}}
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: "{{ $root.Values.persistence.size }}"
      {{- if $root.Values.persistence.storageClass }}
      {{- if (eq "-" $root.Values.persistence.storageClass) }}
      storageClassName: ""
      {{- else }}
      storageClassName: "{{ $root.Values.persistence.storageClass }}"
      {{- end }}
      {{- end }}
{{- end }}
{{- end }}
