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

{{- /*
  Dremio supports different executor groups called "engines".
  These are defined in executor.engines and all the executor-specific k8s objects are created per engine.
  Each engine contains an "overrides" section which allows replacing the common executor configuration
  set in executor.common. This logic is inspired in upstream Dremio chart.

  https://docs.dremio.com/cloud/sonar/workloads/engines/
 */}}
{{- range $engine := .Values.executor.engines }}
{{- $executorValues := deepCopy $.Values.executor.common }}
{{- $executorValues = mustMergeOverwrite $executorValues $engine.overrides }}

{{- if and (include "common.capabilities.apiVersions.has" ( dict "version" "autoscaling.k8s.io/v1/VerticalPodAutoscaler" "context" $ )) $executorValues.autoscaling.vpa.enabled }}
---
apiVersion: {{ include "common.capabilities.vpa.apiVersion" $ }}
kind: VerticalPodAutoscaler
metadata:
  name: {{ include "dremio.executor.fullname" (dict "context" $ "engine" $engine.name) }}
  namespace: {{ include "common.names.namespace" $ | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: dremio
    app.kubernetes.io/component: executor
    {{- /* We need an extra label for the engine */}}
    engine: {{ $engine.name }}
  {{- if or $executorValues.autoscaling.vpa.annotations .Values.commonAnnotations }}
  {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list $executorValues.autoscaling.vpa.annotations .Values.commonAnnotations ) "context" . ) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $) | nindent 4 }}
  {{- end }}
spec:
  resourcePolicy:
    containerPolicies:
    - containerName: dremio
      {{- with $executorValues.autoscaling.vpa.controlledResources }}
      controlledResources:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with $executorValues.autoscaling.vpa.maxAllowed }}
      maxAllowed:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with $executorValues.autoscaling.vpa.minAllowed }}
      minAllowed:
        {{- toYaml . | nindent 8 }}
      {{- end }}
  targetRef:
    apiVersion: {{ include "common.capabilities.statefulset.apiVersion" $ }}
    kind: StatefulSet
    name: {{ include "dremio.executor.fullname" (dict "context" $ "engine" $engine.name) }}
  {{- if $executorValues.autoscaling.vpa.updatePolicy }}
  updatePolicy:
    {{- with $executorValues.autoscaling.vpa.updatePolicy.updateMode }}
    updateMode: {{ . }}
    {{- end }}
  {{- end }}
{{- end }}
{{- end }}
