# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "elastalert.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "elastalert.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "elastalert.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "elastalert.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
 # config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "elastalert.fullname" . }}-config
  labels:
    app: {{ template "elastalert.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  elastalert_config: |-
    ---
    rules_folder: /opt/rules
    scan_subdirectories: false
    run_every:
      minutes: {{ .Values.runIntervalMins }}
{{- if .Values.realertIntervalMins }}
    realert:
      minutes: {{ .Values.realertIntervalMins }}
{{- end }}
    buffer_time:
      minutes: {{ .Values.bufferTimeMins }}
    es_host: {{ .Values.elasticsearch.host }}
    es_port: {{ .Values.elasticsearch.port }}
{{- if .Values.elasticsearch.username }}
    es_username: {{ .Values.elasticsearch.username }}
{{- end }}
{{- if .Values.elasticsearch.password }}
    es_password: {{ .Values.elasticsearch.password }}
{{- end }}
    writeback_index: {{ .Values.writebackIndex }}
    use_ssl: {{ .Values.elasticsearch.useSsl }}
    verify_certs: {{ .Values.elasticsearch.verifyCerts }}
{{- if .Values.elasticsearch.clientCert }}
    client_cert: {{ .Values.elasticsearch.clientCert }}
{{- end }}
{{- if .Values.elasticsearch.clientKey }}
    client_key: {{ .Values.elasticsearch.clientKey }}
{{- end }}
{{- if .Values.elasticsearch.caCerts }}
    ca_certs: {{ .Values.elasticsearch.caCerts }}
{{- end }}
    alert_time_limit:
      minutes: {{ .Values.alertRetryLimitMins }}
{{- if .Values.extraConfigOptions }}
{{ toYaml .Values.extraConfigOptions | indent 4 }}
{{- end }}
 # deployment.yaml
{{ if .Values.elasticsearch.host }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ template "elastalert.fullname" . }}
  labels:
    app: {{ template "elastalert.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  selector:
    matchLabels:
      app: {{ template "elastalert.name" . }}
      release: {{ .Release.Name }}
  replicas: {{ .Values.replicaCount }}
  revisionHistoryLimit: {{ .Values.revisionHistoryLimit }}
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}
        checksum/rules: {{ include (print $.Template.BasePath "/rules.yaml") . | sha256sum }}
{{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
{{- end }}
      labels:
        name: {{ template "elastalert.fullname" . }}-elastalert
        app: {{ template "elastalert.name" . }}
        release: {{ .Release.Name }}
    spec:
      serviceAccountName: {{ include "elastalert.serviceAccountName" . }}
      containers:
      - name: elastalert
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.command }}
        command:
{{ toYaml .Values.command | indent 10 }}
{{- end }}
{{- if .Values.args }}
        args:
{{ toYaml .Values.args | indent 10 }}
{{- end }}
        volumeMounts:
          - name: config
            mountPath: '/opt/config'
          - name: rules
            mountPath: '/opt/rules'
{{- if .Values.elasticsearch.certsVolumeMounts }}
{{ toYaml .Values.elasticsearch.certsVolumeMounts | indent 10 }}
{{- end }}
{{- if .Values.extraVolumeMounts }}
{{ toYaml .Values.extraVolumeMounts | indent 10 }}
{{- end }}
        resources:
{{ toYaml .Values.resources | indent 12 }}
        env:
{{- if .Values.elasticsearch.credentialsSecret }}
{{- if .Values.elasticsearch.credentialsSecretUsernameKey }}
          - name: ES_USERNAME
            valueFrom:
              secretKeyRef:
                name: {{ .Values.elasticsearch.credentialsSecret }}
                key: {{ .Values.elasticsearch.credentialsSecretUsernameKey }}
{{- end }}
{{- if .Values.elasticsearch.credentialsSecretPasswordKey }}
          - name: ES_PASSWORD
            valueFrom:
              secretKeyRef:
                name: {{ .Values.elasticsearch.credentialsSecret }}
                key: {{ .Values.elasticsearch.credentialsSecretPasswordKey }}
{{- end }}
{{- end }}
{{- if .Values.optEnv }}
{{ .Values.optEnv | toYaml | indent 10}}
{{- end }}
      restartPolicy: Always
{{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
{{- end }}
{{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
{{- end }}
      volumes:
        - name: rules
          configMap:
            name: {{ template "elastalert.fullname" . }}-rules
            items:
{{- range $key, $value := .Values.rules }}
            - key: {{ $key }}
              path: {{ $key}}.yaml
{{- end }}
        - name: config
          configMap:
            name: {{ template "elastalert.fullname" . }}-config
            items:
            - key: elastalert_config
              path: elastalert_config.yaml
{{- if .Values.elasticsearch.certsVolumes }}
{{ toYaml .Values.elasticsearch.certsVolumes | indent 8 }}
{{- end }}
{{- if .Values.extraVolumes }}
{{ toYaml .Values.extraVolumes | indent 8 }}
{{- end }}
{{- end }}
 # podsecuritypolicy.yaml
{{- if .Values.podSecurityPolicy.create }}
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: {{ template "elastalert.fullname" . }}
  labels:
    app: {{ template "elastalert.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
spec:
  # Prevents running in privileged mode
  privileged: false
  # Required to prevent escalations to root.
  allowPrivilegeEscalation: false
  volumes:
    - configMap
    - secret
  hostNetwork: false
  hostIPC: false
  hostPID: false
  runAsUser:
    rule: RunAsAny
  seLinux:
    rule: RunAsAny
  supplementalGroups:
    rule: MustRunAs
    ranges:
      # Forbid adding the root group.
      - min: 1
        max: 65535
  fsGroup:
    rule: MustRunAs
    ranges:
      # Forbid adding the root group.
      - min: 1
        max: 65535
  readOnlyRootFilesystem: false
{{- end }}
 # role.yaml
{{- if .Values.podSecurityPolicy.create }}
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: {{ template "elastalert.fullname" . }}
  labels:
    app: {{ template "elastalert.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
rules:
  - apiGroups:
    - policy
    resources:
    - podsecuritypolicies
    resourceNames:
    - {{ template "elastalert.fullname" . }}
    verbs:
    - use
{{- end -}}
 # rolebinding.yaml
{{- if .Values.podSecurityPolicy.create }}
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: {{ template "elastalert.fullname" . }}
  labels:
    app: {{ template "elastalert.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "elastalert.fullname" . }}
subjects:
  - kind: ServiceAccount
    name: {{ template "elastalert.serviceAccountName" . }}
{{- end -}}
 # rules.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "elastalert.fullname" . }}-rules
  labels:
    app: {{ template "elastalert.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
{{- range $key, $value := .Values.rules }}
{{ $key | indent 2}}: |-
{{ $value | indent 4}}
{{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ include "elastalert.serviceAccountName" . }}
  labels:
    app: {{ template "elastalert.name" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
{{- end -}}

# number of replicas to run
replicaCount: 1

# number of helm release revisions to retain
revisionHistoryLimit: 5

# Default internal between alert checks against the elasticsearch datasource, in minutes
runIntervalMins: 1

# Default rule buffer duration, in minutes
bufferTimeMins: 15

# Amount of time to retry and deliver failed alerts (1440 minutes per day)
alertRetryLimitMins: 2880

# Default time before realerting, in minutes
realertIntervalMins: ""

# For ES 5: The name of the index which stores elastalert's statuses
# For ES 6: The prefix of the names of indices which store elastalert's statuses.
#
# See https://github.com/Yelp/elastalert/commit/c250100b7be07c68a53789569a86f87193ec37f4 for more details about this differentiation.
#
# CAUTION: It is recommended to set this to `elastalert` for ES6+. Otherwise elastalert produces confusing index names due to https://github.com/Yelp/elastalert/issues/1479#issuecomment-356380179
writebackIndex: elastalert_status

image:
  # docker image
  repository: jertel/elastalert-docker
  # docker image tag
  tag: 0.2.4
  pullPolicy: IfNotPresent

resources: {}

# Annotations to be added to pods
podAnnotations: {}

elasticsearch:
  # elasticsearch endpoint e.g. (svc.namespace||svc)
  host: ""
  # elasticsearch port
  port: 80
  # whether or not to connect to es_host using TLS
  useSsl: "False"
  # Username if authenticating to ES with basic auth
  username: ""
  # Password if authenticating to ES with basic auth
  password: ""
  # Specifies an existing secret to be used for the ES username/password
  credentialsSecret: ""
  # The key in elasticsearch.credentialsSecret that stores the ES password
  credentialsSecretUsernameKey: ""
  # The key in elasticsearch.credentialsSecret that stores the ES username
  credentialsSecretPasswordKey: ""
  # whether or not to verify TLS certificates
  verifyCerts: "True"
  # Enable certificate based authentication
  # path to a PEM certificate to use as the client certificate
  # clientCert: "/certs/client.pem"
  # path to a private key file to use as the client key
  # clientKey: "/certs/client-key.pem"
  # path to a CA cert bundle to use to verify SSL connections
  # caCerts: "/certs/ca.pem"
  # # certs volumes, required to mount ssl certificates when elasticsearch has tls enabled
  # certsVolumes:
  #   - name: es-certs
  #     secret:
  #       defaultMode: 420
  #       secretName: es-certs
  # # mount certs volumes, required to mount ssl certificates when elasticsearch has tls enabled
  # certsVolumeMounts:
  #   - name: es-certs
  #     mountPath: /certs
  #     readOnly: true

# Optional env variables for the pod
optEnv: []

extraConfigOptions: {}
  # # Options to propagate to all rules, e.g. a common slack_webhook_url or kibana_url
  # # Please note at the time of implementing this value, it will not work for required_locals
  # # Which MUST be set at the rule level, these are: ['alert', 'type', 'name', 'index']
  # generate_kibana_link: true
  # kibana_url: https://kibana.yourdomain.com
  # slack_webhook_url: dummy

# Command and args override for container e.g. (https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/)
# command: ["YOUR_CUSTOM_COMMAND"]
# args: ["YOUR", "CUSTOM", "ARGS"]

# rule configurations e.g. (http://elastalert.readthedocs.io/en/latest/)
rules: {}
  # deadman_slack: |-
  #   ---
  #   name: Deadman Switch Slack
  #   type: frequency
  #   index: containers-*
  #   num_events: 3
  #   timeframe:
  #     minutes: 3
  #   filter:
  #   - term:
  #       message: "deadmanslack"
  #   alert:
  #   - "slack"
  #   slack:
  #   slack_webhook_url: dummy
  # deadman_pagerduty: |-
  #   ---
  #   name: Deadman Switch PagerDuty
  #   type: frequency
  #   index: containers-*
  #   num_events: 3
  #   timeframe:
  #     minutes: 3
  #   filter:
  #   - term:
  #       message: "deadmanpd"
  #   alert:
  #   - "pagerduty"
  #   pagerduty:
  #   pagerduty_service_key: dummy
  #   pagerduty_client_name: Elastalert Deadman Switch

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # Annotations to add to the service account
  annotations: {}
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name:

# Enable pod security policy
# https://kubernetes.io/docs/concepts/policy/pod-security-policy/
podSecurityPolicy:
  create: false

# Support using node selectors and tolerations
# nodeSelector:
#   "node-role.kubernetes.io/infra_worker": "true"
nodeSelector: {}
# tolerations:
#   - key: "node_role"
#     operator: "Equal"
#     value: "infra_worker"
#     effect: "NoSchedule"
tolerations: []

extraVolumes: []
  # - name: smtp-auth
  #   secret:
  #     secretName: elastalert-smtp-auth
  #     items:
  #       - key: smtp_auth.yaml
  #         path: smtp_auth.yaml
  #         mode: 0400

extraVolumeMounts: []
  # - name: smtp-auth
  #   mountPath: /opt/config-smtp/smtp_auth.yaml
  #   subPath: smtp_auth.yaml
  #   readOnly: true
