apiVersion: apps/v1beta2
kind: StatefulSet
metadata:
  name: {{ template "rabbitmq.fullname" . }}
  labels:
    app: {{ template "rabbitmq.name" . }}
    chart: {{ template "rabbitmq.chart" .  }}
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
spec:
  serviceName: {{ template "rabbitmq.fullname" . }}-headless
  replicas: {{ .Values.replicas }}
  selector:
    matchLabels:
      app: {{ template "rabbitmq.name" . }}
      release: "{{ .Release.Name }}"
  template:
    metadata:
      labels:
        app: {{ template "rabbitmq.name" . }}
        release: "{{ .Release.Name }}"
        chart: {{ template "rabbitmq.chart" .  }}
      {{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
      {{- end }}
      {{- if .Values.podAnnotations }}
      annotations:
{{ toYaml .Values.podAnnotations | indent 8 }}
      {{- end }}
    spec:
      {{- if .Values.image.pullSecrets }}
      imagePullSecrets:
      {{- range .Values.image.pullSecrets }}
        - name: {{ . }}
      {{- end}}
      {{- end }}
      {{- if .Values.rbacEnabled}}
      serviceAccountName: {{ template "rabbitmq.fullname" . }}
      {{- end }}
      {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
      {{- end }}
      terminationGracePeriodSeconds: 10
      containers:
      - name: rabbitmq
        image: {{ template "rabbitmq.image" . }}
        imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
        command:
         - bash
         - -ec
         - |
            mkdir -p /opt/bitnami/rabbitmq/.rabbitmq/
            mkdir -p /opt/bitnami/rabbitmq/etc/rabbitmq/
            #persist the erlang cookie in both places for server and cli tools
            echo $RABBITMQ_ERL_COOKIE > /opt/bitnami/rabbitmq/var/lib/rabbitmq/.erlang.cookie
            cp /opt/bitnami/rabbitmq/var/lib/rabbitmq/.erlang.cookie /opt/bitnami/rabbitmq/.rabbitmq/
            #change permission so only the user has access to the cookie file
            chmod 600 /opt/bitnami/rabbitmq/.rabbitmq/.erlang.cookie /opt/bitnami/rabbitmq/var/lib/rabbitmq/.erlang.cookie
            #copy the mounted configuration to both places
            cp  /opt/bitnami/rabbitmq/conf/* /opt/bitnami/rabbitmq/etc/rabbitmq
            # Apply resources limits
            ulimit -n "${RABBITMQ_ULIMIT_NOFILES}"
            #replace the default password that is generated
            sed -i "s/CHANGEME/$RABBITMQ_PASSWORD/g" /opt/bitnami/rabbitmq/etc/rabbitmq/rabbitmq.conf
            # Move logs to stdout
            ln -sF /dev/stdout /opt/bitnami/rabbitmq/var/log/rabbitmq/rabbit@${MY_POD_IP}.log
            ln -sF /dev/stdout /opt/bitnami/rabbitmq/var/log/rabbitmq/rabbit@${MY_POD_IP}_upgrade.log
            exec rabbitmq-server
        {{- if .Values.resources }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        {{- end }}
        volumeMounts:
          - name: config-volume
            mountPath: /opt/bitnami/rabbitmq/conf
          - name: data
            mountPath: /opt/bitnami/rabbitmq/var/lib/rabbitmq/
        ports:
        - name: epmd
          containerPort: 4369
        - name: amqp
          containerPort: {{ .Values.service.port }}
        - name: dist
          containerPort: {{ .Values.service.distPort }}
        - name: stats
          containerPort: {{ .Values.service.managerPort }}
        {{- if .Values.livenessProbe.enabled }}
        livenessProbe:
          exec:
            command: ["sh", "-c", "test \"$(curl -sS -f --user {{ .Values.rabbitmq.username }}:$RABBITMQ_PASSWORD 127.0.0.1:{{ .Values.service.managerPort }}/api/healthchecks/node)\" = '{\"status\":\"ok\"}'"]
          initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
          periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
          failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
          successThreshold: {{ .Values.livenessProbe.successThreshold }}
        {{- end }}
        {{- if .Values.readinessProbe.enabled }}
        readinessProbe:
          exec:
            command: ["sh", "-c", "test \"$(curl -sS -f --user {{ .Values.rabbitmq.username }}:$RABBITMQ_PASSWORD 127.0.0.1:{{ .Values.service.managerPort }}/api/healthchecks/node)\" = '{\"status\":\"ok\"}'"]
          initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
          periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
          failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
          successThreshold: {{ .Values.readinessProbe.successThreshold }}
        {{- end }}
        env:
        {{- if .Values.image.debug}}
          - name: BASH_DEBUG
            value: "1"
          - name: NAMI_DEBUG
            value: "1"
        {{- end }}
          - 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: "{{ template "rabbitmq.fullname" . }}-headless"
          - name: K8S_ADDRESS_TYPE
            value: {{ .Values.rabbitmq.clustering.address_type }}
          {{- if (eq "hostname" .Values.rabbitmq.clustering.address_type) }}
          - name: RABBITMQ_NODENAME
            value: "rabbit@$(MY_POD_NAME).$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.rabbitmq.clustering.k8s_domain }}"
          - name: K8S_HOSTNAME_SUFFIX
            value: ".$(K8S_SERVICE_NAME).$(MY_POD_NAMESPACE).svc.{{ .Values.rabbitmq.clustering.k8s_domain }}"
          {{- else }}
          - name: RABBITMQ_NODENAME
            value: "rabbit@$(MY_POD_IP)"
          {{- end }}
          - name: RABBITMQ_ULIMIT_NOFILES
            value: {{ .Values.rabbitmq.ulimitNofiles | quote }}
          - name: RABBITMQ_USE_LONGNAME
            value: "true"
          - name: RABBITMQ_ERL_COOKIE
            valueFrom:
              secretKeyRef:
                name: {{ template "rabbitmq.secretErlangName" . }}
                key: rabbitmq-erlang-cookie
          - name: RABBITMQ_PASSWORD
            valueFrom:
              secretKeyRef:
                name: {{ template "rabbitmq.secretPasswordName" . }}
                key: rabbitmq-password
{{- if .Values.metrics.enabled }}
      - name: metrics
        image: {{ template "metrics.image" . }}
        imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
        env:
        - name: RABBIT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ template "rabbitmq.secretPasswordName" . }}
              key: rabbitmq-password
        - name: RABBIT_URL
          value: "http://localhost:{{ .Values.service.managerPort }}"
        - name: RABBIT_USER
          value: {{ .Values.rabbitmq.username }}
        ports:
        - name: metrics
          containerPort: 9090
        livenessProbe:
          httpGet:
            path: /metrics
            port: metrics
          initialDelaySeconds: 15
          timeoutSeconds: 5
        readinessProbe:
          httpGet:
            path: /metrics
            port: metrics
          initialDelaySeconds: 5
          timeoutSeconds: 5
        resources:
{{ toYaml .Values.metrics.resources | indent 10 }}
{{- end }}

      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      volumes:
        - name: config-volume
          configMap:
            name: {{ template "rabbitmq.fullname" . }}-config
            items:
            - key: rabbitmq.conf
              path: rabbitmq.conf
            - key: enabled_plugins
              path: enabled_plugins
      {{- if not .Values.persistence.enabled }}
        - name: data
          emptyDir: {}
  {{- else }}
  volumeClaimTemplates:
    - metadata:
        name: data
        labels:
          app: {{ template "rabbitmq.name" . }}
          release: "{{ .Release.Name }}"
          heritage: "{{ .Release.Service }}"
      spec:
        accessModes:
          - {{ .Values.persistence.accessMode | quote }}
        resources:
            requests:
              storage: {{ .Values.persistence.size | quote }}
      {{- if .Values.persistence.storageClass }}
      {{- if (eq "-" .Values.persistence.storageClass) }}
        storageClassName: ""
      {{- else }}
        storageClassName: "{{ .Values.persistence.storageClass }}"
      {{- end }}
      {{- end }}
  {{- end }}
