{{/* vim: set filetype=mustache: */}}

{{/*
Create the name of the pod name to use in prometheus queries
*/}}
{{- define "defaultTemplates.podname" -}}
{{ .Values.rolloutStrategy.deploymentName }}
{{- end -}}

{{/*
Define the address of the prometheus server to be used in the default AnalysisTemplates
*/}}
{{- define "defaultTemplates.basicTemplates.promServerAdress" -}}
{{ .Values.rolloutAnalysisTemplates.defaultTemplates.basicTemplates.promServerAddress }}
{{- end -}}

{{- define "promAuthSecretName" -}}
{{- include "defaultTemplates.podname" . }}-prom-auth
{{- end -}}

{{- define "defaultTemplates.basicTemplates.prometheusProvider" -}}
prometheus:
{{- if .Values.rolloutAnalysisTemplates.authToken }}
  headers:
  - key: Authorization
    value: {{ "Bearer {{" }} {{ "args.prom-auth-token" }} {{ "}}" }}
{{- end }}
  address: {{ include "defaultTemplates.basicTemplates.promServerAdress" . }}
{{- end -}}

{{- define "memoryUsageTemplate.name" -}}jfrog-memory-usage-analysis{{- end -}}

{{- define "memoryUsageTemplate.provider" -}}
{{ include "defaultTemplates.basicTemplates.prometheusProvider" . }}
  query: {{ include "memoryUsageTemplate.query" . | quote }}
{{- end -}}

{{- define "cpuUsageTemplate.name" -}}jfrog-cpu-usage-analysis{{- end -}}

{{- define "cpuUsageTemplate.provider" -}}
{{ include "defaultTemplates.basicTemplates.prometheusProvider" . }}
  query: {{ include "cpuUsageTemplate.query" . | quote }}
{{- end -}}

{{/*
Define the prometheus queries to be used in the default AnalysisTemplates
*/}}
{{- define "memoryUsageTemplate.query" -}}
avg( sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) by (pod) * on(pod) group_left kube_pod_labels{label_role="canary"} ) / avg(  sum(container_memory_working_set_bytes{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) by (pod) * on(pod) group_left kube_pod_labels{label_role="stable"} )
{{- end -}}
{{- define "cpuUsageTemplate.query" -}}
avg( sum(node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) by (pod) * on(pod) group_left kube_pod_labels{label_role="canary"} ) / avg( sum(node_namespace_pod_container:container_cpu_usage_seconds_total:sum_irate{container!="POD",container!="",pod=~"{{ include "defaultTemplates.podname" . }}.*"}) by (pod) * on(pod) group_left kube_pod_labels{label_role="stable"} )
{{- end -}}
