{{/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
*/}}

################################
## Airflow API Server Deployment
#################################
{{- if and .Values.apiServer.enabled (semverCompare ">=3.0.0" .Values.airflowVersion) }}
{{- $nodeSelector := or .Values.apiServer.nodeSelector .Values.nodeSelector }}
{{- $affinity := or .Values.apiServer.affinity .Values.affinity }}
{{- $tolerations := or .Values.apiServer.tolerations .Values.tolerations }}
{{- $topologySpreadConstraints := or .Values.apiServer.topologySpreadConstraints .Values.topologySpreadConstraints }}
{{- $revisionHistoryLimit := include "airflow.revisionHistoryLimit" (list .Values.apiServer.revisionHistoryLimit .Values.revisionHistoryLimit) }}
{{- $securityContext := include "airflowPodSecurityContext" (list .Values.apiServer .Values) }}
{{- $containerSecurityContext := include "containerSecurityContext" (list .Values.apiServer .Values) }}
{{- $containerSecurityContextWaitForMigrations := include "containerSecurityContext" (list .Values.apiServer.waitForMigrations .Values) }}
{{- $containerLifecycleHooks := or .Values.apiServer.containerLifecycleHooks .Values.containerLifecycleHooks }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "airflow.fullname" . }}-api-server
  labels:
    tier: airflow
    component: api-server
    release: {{ .Release.Name }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: {{ .Release.Service }}
    {{- with .Values.labels }}
      {{- toYaml . | nindent 4 }}
    {{- end }}
  {{- if .Values.apiServer.annotations }}
  annotations: {{- toYaml .Values.apiServer.annotations | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.apiServer.hpa.enabled }}
  replicas: {{ .Values.apiServer.replicas }}
  {{- end }}
  {{- if ne $revisionHistoryLimit "" }}
  revisionHistoryLimit: {{ $revisionHistoryLimit }}
  {{- end }}
  strategy:
    {{- if .Values.apiServer.strategy }}
      {{- toYaml .Values.apiServer.strategy | nindent 4 }}
    {{- else }}
    # Here we define the rolling update strategy
    # - maxSurge define how many pod we can add at a time
    # - maxUnavailable define how many pod can be unavailable
    #   during the rolling update
    # Setting maxUnavailable to 0 would make sure we have the appropriate
    # capacity during the rolling update.
    # You can also use percentage based value instead of integer.
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    {{- end }}
  selector:
    matchLabels:
      tier: airflow
      component: api-server
      release: {{ .Release.Name }}
  template:
    metadata:
      labels:
        tier: airflow
        component: api-server
        release: {{ .Release.Name }}
        {{- if or .Values.labels .Values.apiServer.labels }}
          {{- mustMerge .Values.apiServer.labels .Values.labels | toYaml | nindent 8 }}
        {{- end }}
      annotations:
        checksum/metadata-secret: {{ include (print $.Template.BasePath "/secrets/metadata-connection-secret.yaml") . | sha256sum }}
        checksum/pgbouncer-config-secret: {{ include (print $.Template.BasePath "/secrets/pgbouncer-config-secret.yaml") . | sha256sum }}
        checksum/airflow-config: {{ include (print $.Template.BasePath "/configmaps/configmap.yaml") . | sha256sum }}
        {{- if and .Values.apiServer.apiServerConfig (not .Values.apiServer.apiServerConfigConfigMapName) }}
        checksum/api-server-config: {{ include (print $.Template.BasePath "/configmaps/api-server-configmap.yaml") . | sha256sum }}
        {{- end }}
        checksum/extra-configmaps: {{ include (print $.Template.BasePath "/configmaps/extra-configmaps.yaml") . | sha256sum }}
        checksum/extra-secrets: {{ include (print $.Template.BasePath "/secrets/extra-secrets.yaml") . | sha256sum }}
        {{- if not .Values.jwtSecretName }}
        checksum/jwt-secret: {{ include (print $.Template.BasePath "/secrets/jwt-secret.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.airflowPodAnnotations }}
          {{- tpl (toYaml .Values.airflowPodAnnotations) . | nindent 8 }}
        {{- end }}
        {{- if .Values.apiServer.podAnnotations }}
          {{- tpl (toYaml .Values.apiServer.podAnnotations) . | nindent 8 }}
        {{- end }}
    spec:
      {{- if .Values.apiServer.hostAliases }}
      hostAliases: {{- toYaml .Values.apiServer.hostAliases | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "apiServer.serviceAccountName" . }}
      {{- include "serviceLinks" . | nindent 6 }}
      {{- if .Values.apiServer.priorityClassName }}
      priorityClassName: {{ .Values.apiServer.priorityClassName }}
      {{- end }}
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName }}
      {{- end }}
      nodeSelector: {{- toYaml $nodeSelector | nindent 8 }}
      affinity:
        {{- if $affinity }}
          {{- toYaml $affinity | nindent 8 }}
        {{- else }}
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - podAffinityTerm:
              labelSelector:
                matchLabels:
                  component: api-server
              topologyKey: kubernetes.io/hostname
            weight: 100
        {{- end }}
      tolerations: {{- toYaml $tolerations | nindent 8 }}
      topologySpreadConstraints: {{- toYaml $topologySpreadConstraints | nindent 8 }}
      restartPolicy: Always
      securityContext: {{ $securityContext | nindent 8 }}
      imagePullSecrets: {{- include "image_pull_secrets" . | nindent 8 }}
      initContainers:
        {{- if .Values.apiServer.waitForMigrations.enabled }}
        - name: wait-for-airflow-migrations
          resources: {{- toYaml .Values.apiServer.resources | nindent 12 }}
          image: {{ template "airflow_image_for_migrations" . }}
          imagePullPolicy: {{ .Values.images.airflow.pullPolicy }}
          securityContext: {{ $containerSecurityContextWaitForMigrations | nindent 12 }}
          volumeMounts:
            {{- include "airflow_config_mount" . | nindent 12 }}
            {{- if .Values.volumeMounts }}
              {{- toYaml .Values.volumeMounts | nindent 12 }}
            {{- end }}
            {{- if .Values.apiServer.extraVolumeMounts }}
              {{- tpl (toYaml .Values.apiServer.extraVolumeMounts) . | nindent 12 }}
            {{- end }}
          args: {{- include "wait-for-migrations-command" . | indent 10 }}
          envFrom: {{- include "custom_airflow_environment_from" . | default "\n  []" | indent 10 }}
          env:
            {{- include "custom_airflow_environment" . | indent 10 }}
            {{- include "standard_airflow_environment" (merge (dict "IncludeJwtSecret" false) .) | indent 10 }}
            {{- if .Values.apiServer.waitForMigrations.env }}
              {{- tpl (toYaml .Values.apiServer.waitForMigrations.env) $ | nindent 12 }}
            {{- end }}
        {{- end }}
        {{- if .Values.apiServer.extraInitContainers }}
          {{- tpl (toYaml .Values.apiServer.extraInitContainers) . | nindent 8 }}
        {{- end }}
      containers:
        - name: api-server
          image: {{ template "airflow_image" . }}
          imagePullPolicy: {{ .Values.images.airflow.pullPolicy }}
          securityContext: {{ $containerSecurityContext | nindent 12 }}
          {{- if $containerLifecycleHooks  }}
          lifecycle: {{- tpl (toYaml $containerLifecycleHooks) . | nindent 12 }}
          {{- end }}
          {{- if .Values.apiServer.command }}
          command: {{ tpl (toYaml .Values.apiServer.command) . | nindent 12 }}
          {{- end }}
          {{- if .Values.apiServer.args }}
          args: {{- tpl (toYaml .Values.apiServer.args) . | nindent 12 }}
          {{- end }}
          resources: {{- toYaml .Values.apiServer.resources | nindent 12 }}
          volumeMounts:
            {{- include "airflow_config_mount" . | nindent 12 }}
            {{- if or .Values.apiServer.apiServerConfig .Values.apiServer.apiServerConfigConfigMapName }}
              {{- include "airflow_api_server_config_mount" . | nindent 12 }}
            {{- end }}
            {{- if .Values.logs.persistence.enabled }}
            - name: logs
              mountPath: {{ template "airflow_logs" . }}
              {{- if .Values.logs.persistence.subPath }}
              subPath: {{ .Values.logs.persistence.subPath }}
              {{- end }}
            {{- end }}
            {{- if .Values.volumeMounts }}
              {{- toYaml .Values.volumeMounts | nindent 12 }}
            {{- end }}
            {{- if .Values.apiServer.extraVolumeMounts }}
              {{- tpl (toYaml .Values.apiServer.extraVolumeMounts) . | nindent 12 }}
            {{- end }}
          ports:
            - name: api-server
              containerPort: {{ .Values.ports.apiServer }}
          livenessProbe:
            httpGet:
              path: /api/v2/monitor/health
              port: {{ .Values.ports.apiServer }}
              scheme: {{ .Values.apiServer.livenessProbe.scheme | default "http" }}
            initialDelaySeconds: {{ .Values.apiServer.livenessProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.apiServer.livenessProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.apiServer.livenessProbe.failureThreshold }}
            periodSeconds: {{ .Values.apiServer.livenessProbe.periodSeconds }}
          readinessProbe:
            httpGet:
              path: /api/v2/monitor/health
              port: {{ .Values.ports.apiServer }}
              scheme: {{ .Values.apiServer.readinessProbe.scheme | default "http" }}
            initialDelaySeconds: {{ .Values.apiServer.readinessProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.apiServer.readinessProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.apiServer.readinessProbe.failureThreshold }}
            periodSeconds: {{ .Values.apiServer.readinessProbe.periodSeconds }}
          startupProbe:
            httpGet:
              path: /api/v2/monitor/health
              port: {{ .Values.ports.apiServer }}
              scheme: {{ .Values.apiServer.startupProbe.scheme | default "http" }}
            initialDelaySeconds: {{ .Values.apiServer.startupProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.apiServer.startupProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.apiServer.startupProbe.failureThreshold }}
            periodSeconds: {{ .Values.apiServer.startupProbe.periodSeconds }}
          envFrom: {{- include "custom_airflow_environment_from" . | default "\n  []" | indent 10 }}
          env:
            {{- include "custom_airflow_environment" . | indent 10 }}
            {{- include "standard_airflow_environment" (merge (dict "IncludeJwtSecret" true) .) | indent 10 }}
            {{- include "container_extra_envs" (list . .Values.apiServer.env) | indent 10 }}
        {{- if .Values.apiServer.extraContainers }}
          {{- tpl (toYaml .Values.apiServer.extraContainers) . | nindent 8 }}
        {{- end }}
      volumes:
        - name: config
          configMap:
            name: {{ template "airflow_config" . }}
        {{- if or .Values.apiServer.apiServerConfig .Values.apiServer.apiServerConfigConfigMapName }}
        - name: api-server-config
          configMap:
            name: {{ template "airflow_api_server_config_configmap_name" . }}
        {{- end }}
        {{- if .Values.logs.persistence.enabled }}
        - name: logs
          persistentVolumeClaim:
            claimName: {{ template "airflow_logs_volume_claim" . }}
        {{- end }}
        {{- if .Values.volumes }}
          {{- toYaml .Values.volumes | nindent 8 }}
        {{- end }}
        {{- if .Values.apiServer.extraVolumes }}
          {{- tpl (toYaml .Values.apiServer.extraVolumes) . | nindent 8 }}
        {{- end }}
{{- end }}
