apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ include "common.names.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    {{- if .Values.statefulsetLabels }}
    {{- include "common.tplvalues.render" (dict "value" .Values.statefulsetLabels "context" $) | nindent 4 }}
    {{- end }}
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  serviceName: {{ printf "%s-headless" (include "common.names.fullname" .) }}
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ .Values.replicaCount }}
  {{- if .Values.updateStrategy }}
  updateStrategy: {{- toYaml .Values.updateStrategy | nindent 4 }}
  {{- end }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" . | nindent 8 }}
        {{- if .Values.podLabels }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }}
        {{- end }}
      annotations:
        {{- if .Values.commonAnnotations }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 8 }}
        {{- end }}
        checksum/config: {{ include (print $.Template.BasePath "/config-secret.yaml") . | sha256sum }}
        {{- if or (not .Values.auth.existingErlangSecret) (not .Values.auth.existingPasswordSecret) .Values.extraSecrets }}
        checksum/secret: {{ include (print $.Template.BasePath "/secrets.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
        {{- if and .Values.metrics.enabled .Values.metrics.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.metrics.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
    spec:
      {{- include "rabbitmq.imagePullSecrets" . | nindent 6 }}
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName | quote }}
      {{- end }}
      serviceAccountName: {{ template "rabbitmq.serviceAccountName" . }}
      {{- if .Values.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.affinity "context" .) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.nodeSelector "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      {{- if .Values.podSecurityContext.enabled }}
      securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }}
      {{- end }}
      {{- if .Values.dnsPolicy }}
      dnsPolicy: {{ .Values.dnsPolicy }}
      {{- end }}
      {{- if .Values.dnsConfig }}
      dnsConfig: {{- include "common.tplvalues.render" (dict "value" .Values.dnsConfig "context" .) | nindent 8 }}
      {{- end }}
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      initContainers:
        {{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }}
        - name: volume-permissions
          image: {{ include "rabbitmq.volumePermissions.image" . }}
          imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              mkdir -p "{{ .Values.persistence.mountPath }}"
              chown "{{ .Values.containerSecurityContext.runAsUser }}:{{ .Values.podSecurityContext.fsGroup }}" "{{ .Values.persistence.mountPath }}"
              find "{{ .Values.persistence.mountPath }}" -mindepth 1 -maxdepth 1 -not -name ".snapshot" -not -name "lost+found" | xargs -r chown -R "{{ .Values.containerSecurityContext.runAsUser }}:{{ .Values.podSecurityContext.fsGroup }}"
          securityContext:
            runAsUser: 0
          {{- if .Values.volumePermissions.resources }}
          resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.persistence.mountPath }}
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
        {{- end }}
        {{- if .Values.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }}
        {{- end }}
      containers:
        - name: rabbitmq
          image: {{ template "rabbitmq.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.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.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.args "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.lifecycleHooks "context" $) | nindent 12 }}
          {{- else }}
          lifecycle:
            preStop:
              exec:
                command:
                  - /bin/bash
                  - -ec
                  - |
                    if [[ -f /opt/bitnami/scripts/rabbitmq/nodeshutdown.sh ]]; then
                        /opt/bitnami/scripts/rabbitmq/nodeshutdown.sh -t {{ .Values.terminationGracePeriodSeconds | quote }} -d {{ ternary "true" "false" .Values.image.debug | quote }}
                    else
                        rabbitmqctl stop_app
                    fi
          {{- end }}
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: MY_POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: MY_POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: K8S_SERVICE_NAME
              value: {{ printf "%s-headless" (include "common.names.fullname" .) }}
            - name: K8S_ADDRESS_TYPE
              value: {{ .Values.clustering.addressType }}
            - name: RABBITMQ_FORCE_BOOT
              value: {{ ternary "yes" "no" .Values.clustering.forceBoot | quote }}
            {{- if (eq "hostname" .Values.clustering.addressType) }}
            - name: RABBITMQ_NODE_NAME
              value: "rabbit@$(MY_POD_NAME).$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}"
            - name: K8S_HOSTNAME_SUFFIX
              value: ".$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.clusterDomain }}"
            {{- else }}
            - name: RABBITMQ_NODE_NAME
              value: "rabbit@$(MY_POD_NAME)"
            {{- end }}
            - name: RABBITMQ_MNESIA_DIR
              value: "{{ .Values.persistence.mountPath }}/$(RABBITMQ_NODE_NAME)"
            - name: RABBITMQ_LDAP_ENABLE
              value: {{ ternary "yes" "no" .Values.ldap.enabled | quote }}
            {{- if .Values.ldap.enabled }}
            - name: RABBITMQ_LDAP_TLS
              value: {{ ternary "yes" "no" .Values.ldap.tls.enabled | quote }}
            - name: RABBITMQ_LDAP_SERVERS
              value: {{ .Values.ldap.servers | join "," | quote }}
            - name: RABBITMQ_LDAP_SERVERS_PORT
              value: {{ .Values.ldap.port | quote }}
            - name: RABBITMQ_LDAP_USER_DN_PATTERN
              value: {{ .Values.ldap.user_dn_pattern }}
            {{- end }}
            - name: RABBITMQ_LOGS
              value: {{ .Values.logs | quote }}
            - name: RABBITMQ_ULIMIT_NOFILES
              value: {{ .Values.ulimitNofiles | quote }}
            {{- if and .Values.maxAvailableSchedulers }}
            - name: RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS
              value: {{ printf "+S %s:%s" (toString .Values.maxAvailableSchedulers) (toString .Values.onlineSchedulers) -}}
            {{- end }}
            - name: RABBITMQ_USE_LONGNAME
              value: "true"
            - name: RABBITMQ_ERL_COOKIE
              valueFrom:
                secretKeyRef:
                  name: {{ template "rabbitmq.secretErlangName" . }}
                  key: rabbitmq-erlang-cookie
            {{- if and .Values.clustering.rebalance (gt (.Values.replicaCount | int) 1) }}
            - name: RABBITMQ_CLUSTER_REBALANCE
              value: "true"
            {{- end }}
            - name: RABBITMQ_LOAD_DEFINITIONS
              value: {{ ternary "yes" "no" .Values.loadDefinition.enabled | quote }}
            - name: RABBITMQ_DEFINITIONS_FILE
              value: {{ .Values.loadDefinition.file | quote }}
            - name: RABBITMQ_SECURE_PASSWORD
              value: "yes"
            - name: RABBITMQ_USERNAME
              value: {{ .Values.auth.username | quote }}
            - name: RABBITMQ_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "rabbitmq.secretPasswordName" . }}
                  key: rabbitmq-password
            - name: RABBITMQ_PLUGINS
              value: {{ include "rabbitmq.plugins" . | quote }}
            {{- if .Values.communityPlugins }}
            - name: RABBITMQ_COMMUNITY_PLUGINS
              value: {{ .Values.communityPlugins | quote }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsSecret "context" $) }}
            {{- end }}
          ports:
            - name: amqp
              containerPort: {{ .Values.containerPorts.amqp }}
            - name: dist
              containerPort: {{ .Values.containerPorts.dist }}
            - name: stats
              containerPort: {{ .Values.containerPorts.manager }}
            - name: epmd
              containerPort: {{ .Values.containerPorts.epmd }}
            {{- if .Values.metrics.enabled }}
            - name: metrics
              containerPort: {{ .Values.containerPorts.metrics }}
            {{- end }}
            {{- if .Values.auth.tls.enabled }}
            - name: amqp-ssl
              containerPort: {{ .Values.containerPorts.amqpTls }}
            {{- end }}
            {{- if .Values.extraContainerPorts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraContainerPorts "context" $) | nindent 12 }}
            {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.livenessProbe "enabled") "context" $) | nindent 12 }}
            exec:
              command:
                - /bin/bash
                - -ec
                - rabbitmq-diagnostics -q ping
          {{- else if .Values.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customLivenessProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.readinessProbe "enabled") "context" $) | nindent 12 }}
            exec:
              command:
                - /bin/bash
                - -ec
                - rabbitmq-diagnostics -q check_running && rabbitmq-diagnostics -q check_local_alarms
          {{- else if .Values.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customReadinessProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.startupProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: {{ternary "amqp-ssl" "amqp" .Values.auth.tls.enabled }}
          {{- else if .Values.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customStartupProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- end }}
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: configuration
              mountPath: /bitnami/rabbitmq/conf
            - name: data
              mountPath: {{ .Values.persistence.mountPath }}
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
            {{- if .Values.auth.tls.enabled }}
            - name: certs
              mountPath: /opt/bitnami/rabbitmq/certs
            {{- end }}
            {{- if and .Values.ldap.tls.enabled .Values.ldap.tls.certificatesSecret }}
            - name: ldap-certs
              mountPath: {{ .Values.ldap.tls.certificatesMountPath }}
            {{- end }}
            {{- if .Values.loadDefinition.enabled }}
            - name: load-definition-volume
              mountPath: /app
              readOnly: true
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        {{- if .Values.sidecars }}
        {{- include "common.tplvalues.render" (dict "value" .Values.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        {{- if .Values.auth.tls.enabled }}
        - name: certs
          secret:
            secretName: {{ template "rabbitmq.tlsSecretName" . }}
            items:
              - key: {{ ternary "tls.crt" "ca.crt" .Values.auth.tls.existingSecretFullChain }}
                path: ca_certificate.pem
              - key: tls.crt
                path: server_certificate.pem
              - key: tls.key
                path: server_key.pem
        {{- end }}
        {{- if and .Values.ldap.tls.enabled .Values.ldap.tls.certificatesSecret }}
        - name: ldap-certs
          secret:
            secretName: {{ .Values.ldap.tls.certificatesSecret }}
        {{- end }}
        - name: configuration
          secret:
            secretName: {{ printf "%s-config" (include "common.names.fullname" .) }}
            items:
              - key: rabbitmq.conf
                path: rabbitmq.conf
              {{- if .Values.advancedConfiguration }}
              - key: advanced.config
                path: advanced.config
              {{- end }}
        {{- if .Values.loadDefinition.enabled }}
        - name: load-definition-volume
          secret:
            secretName: {{ tpl .Values.loadDefinition.existingSecret . | quote }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $)  | nindent 8 }}
        {{- end }}
  {{- if not .Values.persistence.enabled }}
        - name: data
          emptyDir: {}
  {{- else if .Values.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            {{- with .Values.persistence.existingClaim }}
            claimName: {{ tpl . $ }}
            {{- end }}
  {{- else }}
  volumeClaimTemplates:
    - metadata:
        name: data
        labels: {{- include "common.labels.matchLabels" . | nindent 10 }}
        {{- if .Values.persistence.annotations }}
        annotations:
          {{- include "common.tplvalues.render" ( dict "value" .Values.persistence.annotations "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
          {{- range .Values.persistence.accessModes }}
            - {{ . | quote }}
          {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.size | quote }}
        {{ include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) }}
        {{- if .Values.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.selector "context" $) | nindent 10 }}
        {{- end -}}
  {{- end }}
