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

apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ template "seaweedfs.master.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: master
  {{- if or .Values.master.statefulsetAnnotations .Values.commonAnnotations }}
  {{- $annotations := include "common.tplvalues.merge" (dict "values" (list .Values.master.statefulsetAnnotations .Values.commonAnnotations) "context" .) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.master.autoscaling.enabled }}
  replicas: {{ .Values.master.replicaCount }}
  {{- end }}
  podManagementPolicy: {{ .Values.master.podManagementPolicy | quote }}
  {{- $podLabels := include "common.tplvalues.merge" (dict "values" (list .Values.master.podLabels .Values.commonLabels) "context" .) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/component: master
  serviceName: {{ printf "%s-headless" (include "seaweedfs.master.fullname" .) }}
  {{- if .Values.master.updateStrategy }}
  updateStrategy: {{- toYaml .Values.master.updateStrategy | nindent 4 }}
  {{- end }}
  template:
    metadata:
      annotations:
        {{- if and .Values.master.config (empty .Values.master.existingConfigmap) }}
        checksum/config: {{ include (print $.Template.BasePath "/master/configmap.yaml") . | sha256sum }}
        {{- end }}
        checksum/security-config: {{ include (print $.Template.BasePath "/security-configmap.yaml") . | sha256sum }}
        {{- if .Values.master.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: master
    spec:
      {{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
      serviceAccountName: {{ template "seaweedfs.serviceAccountName" . }}    
      automountServiceAccountToken: {{ .Values.master.automountServiceAccountToken }}
      {{- if .Values.master.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.master.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.affinity }}
      affinity: {{- include "common.tplvalues.render" ( dict "value" .Values.master.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        {{- if not (empty .Values.master.podAffinityPreset) }}
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.master.podAffinityPreset "component" "master" "customLabels" $podLabels "context" $) | nindent 10 }}
        {{- end }}
        {{- if not (empty .Values.master.podAntiAffinityPreset) }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.master.podAntiAffinityPreset "component" "master" "customLabels" $podLabels "context" $) | nindent 10 }}
        {{- end }}
        {{- if not (empty .Values.master.nodeAffinityPreset.type) }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.master.nodeAffinityPreset.type "key" .Values.master.nodeAffinityPreset.key "values" .Values.master.nodeAffinityPreset.values) | nindent 10 }}
        {{- end }}
      {{- end }}
      {{- if .Values.master.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" ( dict "value" .Values.master.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.master.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.priorityClassName }}
      priorityClassName: {{ .Values.master.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.master.schedulerName }}
      schedulerName: {{ .Values.master.schedulerName | quote }}
      {{- end }}
      {{- if .Values.master.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.master.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.master.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.master.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.master.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if or (and .Values.volumePermissions.enabled .Values.master.persistence.enabled) .Values.master.initContainers }}
      initContainers:
        {{- if and .Values.volumePermissions.enabled .Values.master.persistence.enabled }}
        - name: volume-permissions
          image: {{ include "seaweedfs.volumePermissions.image" . }}
          imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - bash
          args:
            - -ec
            - |
              find {{ .Values.master.persistence.mountPath }} -mindepth 1 -maxdepth 1 -not -name ".snapshot" -not -name "lost+found" | xargs chown -R {{ .Values.master.containerSecurityContext.runAsUser }}:{{ .Values.master.podSecurityContext.fsGroup }}
          {{- if .Values.volumePermissions.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.volumePermissions.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.volumePermissions.resources }}
          resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }}
          {{- else if ne .Values.volumePermissions.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.volumePermissions.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.master.persistence.mountPath }}
              {{- if .Values.master.persistence.subPath }}
              subPath: {{ .Values.master.persistence.subPath }}
              {{- end }}
        {{- end }}
        {{- if .Values.master.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.initContainers "context" $) | nindent 8 }}
        {{- end }}
      {{- end }}
      containers:
        - name: seaweedfs
          image: {{ template "seaweedfs.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.master.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.master.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.master.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.master.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.master.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.master.args "context" $) | nindent 12 }}
          {{- else }}
          args:
            {{- if .Values.master.logPersistence.enabled }}
            - -logdir={{ .Values.master.logPersistence.mountPath }}
            {{- else }}
            - -logtostderr=true
            {{- end }}
            - -v={{ .Values.master.logLevel }}
            - -config_dir=/etc/seaweedfs
            - master
            - -mdir={{ .Values.master.persistence.mountPath }}
            - -ip.bind={{ .Values.master.bindAddress }}
            - -ip=$(POD_NAME).{{ printf "%s-headless" (include "seaweedfs.master.fullname" .) }}.$(NAMESPACE).svc.{{ .Values.clusterDomain }}
            - -port={{ .Values.master.containerPorts.http }}
            - -port.grpc={{ .Values.master.containerPorts.grpc }}
            - -peers={{ include "seaweedfs.master.servers" . }}
            {{- if .Values.master.metrics.enabled }}
            - -metricsPort={{ .Values.master.containerPorts.metrics }}
            {{- end }}
            - -volumeSizeLimitMB={{ .Values.master.volumeSizeLimitMB }}
          {{- end }}
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: WEED_CLUSTER_DEFAULT
              value: {{ .Values.clusterDefault | quote }}
            {{- if .Values.master.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.master.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          {{- if or .Values.master.extraEnvVarsCM .Values.master.extraEnvVarsSecret }}
          envFrom:
            {{- if .Values.master.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.master.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.master.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.master.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- end }}
          {{- if .Values.master.resources }}
          resources: {{- toYaml .Values.master.resources | nindent 12 }}
          {{- else if ne .Values.master.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.master.resourcesPreset) | nindent 12 }}
          {{- end }}
          ports:
            - name: http
              containerPort: {{ .Values.master.containerPorts.http }}
            - name: grpc
              containerPort: {{ .Values.master.containerPorts.grpc }}
            {{- if .Values.master.metrics.enabled }}
            - name: metrics
              containerPort: {{ .Values.master.containerPorts.metrics }}
            {{- end }}
            {{- if .Values.master.extraContainerPorts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.master.extraContainerPorts "context" $) | nindent 12 }}
            {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.master.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: http
          {{- end }}
          {{- if .Values.master.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.readinessProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /cluster/status
              port: http
          {{- end }}
          {{- if .Values.master.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.master.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.master.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.master.startupProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /cluster/status
              port: http
          {{- end }}
          {{- end }}
          {{- if .Values.master.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.master.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.master.persistence.mountPath }}
              {{- if .Values.master.persistence.subPath }}
              subPath: {{ .Values.master.persistence.subPath }}
              {{- end }}
            {{- if .Values.master.logPersistence.enabled }}
            - name: logs
              mountPath: {{ .Values.master.logPersistence.mountPath }}
              {{- if .Values.master.logPersistence.subPath }}
              subPath: {{ .Values.master.logPersistence.subPath }}
              {{- end }}
            {{- end }}
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            {{- if or .Values.master.config .Values.master.existingConfigmap }}
            - name: config
              mountPath: /etc/seaweedfs/master.toml
              subPath: master.toml
              readOnly: true
            {{- end }}
            - name: security-config
              mountPath: /etc/seaweedfs/security.toml
              subPath: security.toml
              readOnly: true
            {{- if .Values.security.mTLS.enabled  }}
            - name: ca-cert
              readOnly: true
              mountPath: /certs/ca
            - name: master-cert
              readOnly: true
              mountPath: /certs/master
            - name: volume-cert
              readOnly: true
              mountPath: /certs/volume
            {{- if .Values.filer.enabled }}
            - name: filer-cert
              readOnly: true
              mountPath: /certs/filer
            {{- end }}
            - name: client-cert
              readOnly: true
              mountPath: /certs/client
            {{- end }}
          {{- if .Values.master.extraVolumeMounts }}
          {{- include "common.tplvalues.render" (dict "value" .Values.master.extraVolumeMounts "context" $) | nindent 12 }}
          {{- end }}
        {{- if .Values.master.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.master.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if or .Values.master.config .Values.master.existingConfigmap }}
        - name: config
          configMap:
            name: {{ template "seaweedfs.master.configmapName" . }}
        {{- end }}
        - name: security-config
          configMap:
            name: {{ printf "%s-security" (include "common.names.fullname" .) }}
        {{- if .Values.security.mTLS.enabled  }}
        - name: ca-cert
          secret:
            secretName: {{ template "seaweedfs.security.mTLS.caSecretName" . }}
            items:
              - key: tls.crt
                path: tls.crt
        - name: master-cert
          secret:
            secretName: {{ template "seaweedfs.security.mTLS.master.secretName" . }}
        - name: volume-cert
          secret:
            secretName: {{ template "seaweedfs.security.mTLS.volume.secretName" . }}
        {{- if .Values.filer.enabled }}
        - name: filer-cert
          secret:
            secretName: {{ template "seaweedfs.security.mTLS.filer.secretName" . }}
        {{- end }}
        - name: client-cert
          secret:
            secretName: {{ template "seaweedfs.security.mTLS.client.secretName" . }}
        {{- end }}
        {{- if .Values.master.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.master.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
        {{- if not .Values.master.persistence.enabled }}
        - name: data
          emptyDir: {}
        {{- else if .Values.master.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ tpl .Values.master.persistence.existingClaim . }}
        {{- end }}
        {{- if and .Values.master.logPersistence.enabled .Values.master.logPersistence.existingClaim }}
        - name: logs
          persistentVolumeClaim:
            claimName: {{ tpl .Values.master.logPersistence.existingClaim . }}
        {{- end }}
  {{- if or (and .Values.master.persistence.enabled (not .Values.master.persistence.existingClaim)) (and .Values.master.logPersistence.enabled (not .Values.master.logPersistence.existingClaim)) }}
  {{- if .Values.master.persistentVolumeClaimRetentionPolicy.enabled }}
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: {{ .Values.master.persistentVolumeClaimRetentionPolicy.whenDeleted }}
    whenScaled: {{ .Values.master.persistentVolumeClaimRetentionPolicy.whenScaled }}
  {{- end }}
  volumeClaimTemplates:
    {{- if and .Values.master.persistence.enabled (not .Values.master.persistence.existingClaim) }}
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: data
        {{- if or .Values.master.persistence.annotations .Values.commonAnnotations }}
        {{- $claimAnnotations := include "common.tplvalues.merge" (dict "values" .Values.master.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:
        {{- if .Values.master.persistence.dataSource }}
        dataSource: {{- include "common.tplvalues.render" (dict "value" .Values.master.persistence.dataSource "context" $) | nindent 10 }}
        {{- end }}
        accessModes:
        {{- range .Values.master.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.master.persistence.size | quote }}
        {{- if .Values.master.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.master.persistence.selector "context" $) | nindent 10 }}
        {{- end }}
        {{- include "common.storage.class" (dict "persistence" .Values.master.persistence "global" .Values.global) | nindent 8 }}
    {{- end }}
    {{- if and .Values.master.logPersistence.enabled (not .Values.master.logPersistence.existingClaim) }}
    - apiVersion: v1
      kind: PersistentVolumeClaim
      metadata:
        name: logs
        {{- if or .Values.master.logPersistence.annotations .Values.commonAnnotations }}
        {{- $claimAnnotations := include "common.tplvalues.merge" (dict "values" .Values.master.logPersistence.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:
        {{- if .Values.master.logPersistence.dataSource }}
        dataSource: {{- include "common.tplvalues.render" (dict "value" .Values.master.logPersistence.dataSource "context" $) | nindent 10 }}
        {{- end }}
        accessModes:
        {{- range .Values.master.logPersistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.master.logPersistence.size | quote }}
        {{- if .Values.master.logPersistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.master.logPersistence.selector "context" $) | nindent 10 }}
        {{- end }}
        {{- include "common.storage.class" (dict "persistence" .Values.master.logPersistence "global" .Values.global) | nindent 8 }}
    {{- end }}
  {{- end }}
