# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "apm-server.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 "apm-server.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 chart name and version as used by the chart label.
*/}}
{{- define "apm-server.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "apm-server.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "apm-server.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
 # clusterrole.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
rules:
- apiGroups: [""]
  resources:
  - namespaces
  - pods
  verbs: ["get", "list", "watch"]
{{- end -}}
 # clusterrolebinding.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ template "apm-server.fullname" . }}
subjects:
- kind: ServiceAccount
  name: {{ template "apm-server.serviceAccountName" . }}
  namespace: {{ .Release.Namespace }}
{{- end -}}
 # daemonset.yaml
{{- if eq .Values.kind "DaemonSet" }}
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "apm-server.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  minReadySeconds: 10
  updateStrategy:
{{ toYaml .Values.updateStrategy | indent 4 }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "apm-server.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        {{-  range $key, $value := .Values.podLabels }}
        {{ $key }}: {{ $value }}
        {{- end }}
      annotations:
        checksum/secret: {{ toYaml .Values.config | sha256sum }}
        {{-  range $key, $value := .Values.podAnnotations }}
        {{ $key }}: {{ $value }}
        {{- end }}
    spec:      
{{- if .Values.runAsUser }}
      initContainers:
      - name: busybox
        image: busybox:1.31.0
        command: ['sh','-c']
        args: 
        - chown {{.Values.runAsUser}}:{{default 1000 .Values.runAsGroup}} -R /usr/share/apm-server
        volumeMounts:
        - name: data
          mountPath: /usr/share/apm-server/data
{{- end }}
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
        args:
        - "-e"
{{- if .Values.plugins }}
        - "--plugin"
        - {{ .Values.plugins | join "," | quote }}
{{- end }}
{{- if .Values.extraArgs }}
{{ toYaml .Values.extraArgs | indent 8 }}
{{- end }}
        env:
{{- range $key, $value := .Values.extraVars }}
        - name: {{ $key }}
          value: {{ $value }}
{{- end }}
        ports:
          - name: http
            containerPort: 8200
        livenessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 60
        readinessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 60
        securityContext:
          runAsUser: {{ default 1000 .Values.runAsUser }}
          runAsGroup: {{ default 1000 .Values.runAsGroup }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        volumeMounts:
        - name: apm-server-config
          mountPath: /usr/share/apm-server/apm-server.yml
          readOnly: true
          subPath: apm-server.yml
        - name: data
          mountPath: /usr/share/apm-server/data
{{- if .Values.extraVolumeMounts }}
{{ toYaml .Values.extraVolumeMounts | indent 8 }}
{{- end }}
      volumes:
      - name: apm-server-config
        secret:
          secretName: {{ template "apm-server.fullname" . }}
      - name: data
        hostPath:
          path: /var/lib/apm-server
          type: DirectoryOrCreate
{{- if .Values.extraVolumes }}
{{ toYaml .Values.extraVolumes | indent 6 }}
{{- end }}
      terminationGracePeriodSeconds: 60
      serviceAccountName: {{ template "apm-server.serviceAccountName" . }}
{{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
    {{- end }}
    {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
    {{- end }}
    {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
    {{- end }}
{{- end }}
 # deployment.yaml
{{- if eq .Values.kind "Deployment" }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "apm-server.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  minReadySeconds: 10
  strategy:
{{ toYaml .Values.updateStrategy | indent 4 }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "apm-server.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
        {{-  range $key, $value := .Values.podLabels }}
        {{ $key }}: {{ $value }}
        {{- end }}
      annotations:
        checksum/secret: {{ toYaml .Values.config | sha256sum }}
        {{-  range $key, $value := .Values.podAnnotations }}
        {{ $key }}: {{ $value }}
        {{- end }}
    spec:
{{- if .Values.runAsUser }}
      initContainers:
      - name: busybox
        image: busybox:1.31.0
        command: ['sh','-c']
        args: 
        - chown {{.Values.runAsUser}}:{{default 1000 .Values.runAsGroup}} -R /usr/share/apm-server
        volumeMounts:
        - name: data
          mountPath: /usr/share/apm-server/data
{{- end }}
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
        args:
        - "-e"
{{- if .Values.plugins }}
        - "--plugin"
        - {{ .Values.plugins | join "," | quote }}
{{- end }}
{{- if .Values.extraArgs }}
{{ toYaml .Values.extraArgs | indent 8 }}
{{- end }}
        env:
{{- range $key, $value := .Values.extraVars }}
        - name: {{ $key }}
          value: {{ $value }}
{{- end }}
        ports:
          - name: http
            containerPort: 8200
            protocol: TCP
        livenessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 60
        readinessProbe:
          httpGet:
            path: /
            port: http
          initialDelaySeconds: 60
        securityContext:
          runAsUser: {{ default 1000 .Values.runAsUser }}
          runAsGroup: {{ default 1000 .Values.runAsGroup }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        volumeMounts:
        - name: apm-server-config
          mountPath: /usr/share/apm-server/apm-server.yml
          readOnly: true
          subPath: apm-server.yml
        - name: data
          mountPath: /usr/share/apm-server/data
{{- if .Values.extraVolumeMounts }}
{{ toYaml .Values.extraVolumeMounts | indent 8 }}
{{- end }}
      volumes:
      - name: apm-server-config
        secret:
          secretName: {{ template "apm-server.fullname" . }}
      - name: data
        hostPath:
          path: /var/lib/apm-server
          type: DirectoryOrCreate
{{- if .Values.extraVolumes }}
{{ toYaml .Values.extraVolumes | indent 6 }}
{{- end }}
      terminationGracePeriodSeconds: 60
      serviceAccountName: {{ template "apm-server.serviceAccountName" . }}
{{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
    {{- end }}
    {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
    {{- end }}
    {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
    {{- end }}
{{- end }}
 # hpa.yaml
{{- if and (eq .Values.kind "Deployment") .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app: {{ template "apm-server.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: {{ .Release.Name | quote }}
    heritage: {{ .Release.Service | quote }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ template "apm-server.fullname" . }}
{{ (unset .Values.autoscaling "enabled") | toYaml | indent 2 }} 
{{- end }} # ingress.yaml
{{- if .Values.ingress.enabled }}
{{- if .Values.service.enabled }}
{{- $serviceName := include "apm-server.fullname" . -}}
{{- $servicePort := .Values.service.port -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- range $key, $value := .Values.ingress.labels }}
    {{ $key }}: {{ $value | quote }}
  {{- end }}
  name: {{ template "apm-server.fullname" . }}
  {{- with .Values.ingress.annotations }}
  annotations:
    {{- range $key, $value := . }}
      {{ $key }}: {{ $value | quote }}
    {{- end }}
  {{- end }}
spec:
{{- if .Values.ingress.tls }}
  tls:
  {{- range .Values.ingress.tls }}
    - hosts:
      {{- range .hosts }}
        - {{ . | quote }}
      {{- end }}
      secretName: {{ .secretName }}
  {{- end }}
{{- end }}
  backend:
    serviceName: {{ $serviceName }}
    servicePort: {{ $servicePort }}
{{- if .Values.ingress.hosts }}
  rules:
  {{- range $host := .Values.ingress.hosts }}
  - host: {{ $host }}
    http:
      paths:
        - path: /
          backend:
            serviceName: {{ $serviceName }}
            servicePort: {{ $servicePort }}
  {{- end -}}
{{- end -}}
{{- end }}
{{- end }}
 # secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "apm-server.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
type: Opaque
data:
  apm-server.yml: {{ toYaml .Values.config | indent 4 | b64enc }}
 # service.yaml
{{- if .Values.service.enabled }}
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
  {{- range $key, $value := .Values.service.labels }}
    {{ $key }}: {{ $value | quote }}
  {{- end }}
  name: {{ template "apm-server.fullname" . }}
  {{- with .Values.service.annotations }}
  annotations:
    {{- range $key, $value := . }}
      {{ $key }}: {{ $value | quote }}
    {{- end }}
  {{- end }}
spec:
  {{- if .Values.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
    {{- range $cidr := .Values.service.loadBalancerSourceRanges }}
    - {{ $cidr }}
    {{- end }}
  {{- end }}
  type: {{ .Values.service.type }}
  {{- if and (eq .Values.service.type "ClusterIP") .Values.service.clusterIP }}
  clusterIP: {{ .Values.service.clusterIP }}
  {{- end }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: http
      protocol: TCP
{{ if (and (eq .Values.service.type "NodePort") (not (empty .Values.service.nodePort))) }}
      nodePort: {{ .Values.service.nodePort }}
{{ end }}
{{- if .Values.service.portName }}
      name: {{ .Values.service.portName }}
{{- end }}
{{- if .Values.service.externalIPs }}
  externalIPs:
{{ toYaml .Values.service.externalIPs | indent 4 }}
{{- end }}
  selector:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
{{- if .Values.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.service.loadBalancerIP }}
{{- end }}
{{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "apm-server.serviceAccountName" . }}
  labels:
    app.kubernetes.io/name: {{ include "apm-server.name" . }}
    helm.sh/chart: {{ include "apm-server.chart" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}

image:
  repository: docker.elastic.co/apm/apm-server
  tag: 7.0.0
  pullPolicy: IfNotPresent

# DaemonSet or Deployment
kind: DaemonSet

# Number of replicas when kind is Deployment
replicaCount: 1

# Create HorizontalPodAutoscaler object when kind is Deployment
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      targetAverageUtilization: 60
  - type: Resource
    resource:
      name: memory
      targetAverageUtilization: 60

# The update strategy to apply to the Deployment or DaemonSet
updateStrategy: {}
  # rollingUpdate:
  #   maxUnavailable: 1
  # type: RollingUpdate

service:
  enabled: false
  type: ClusterIP
  port: 8200
  # portName: apm-server-svc
  # clusterIP: None
  ## External IP addresses of service
  ## Default: nil
  # externalIPs:
  # - 192.168.0.1
  #
  ## LoadBalancer IP if service.type is LoadBalancer
  ## Default: nil
  # loadBalancerIP: 10.2.2.2
  ## Limit load balancer source ips to list of CIDRs (where available)
  # loadBalancerSourceRanges: []

  annotations: {}
    # Annotation example: setup ssl with aws cert when service.type is LoadBalancer
    # service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn:aws:acm:us-east-1:EXAMPLE_CERT
  labels: {}
    ## Label example: show service URL in `kubectl cluster-info`
    # kubernetes.io/cluster-service: "true"

ingress:
  enabled: false
  annotations: {}
    # Annotation example: set nginx ingress type
    # kubernetes.io/ingress.class: nginx-public
  labels: {}
  hosts:
    - apm-server-ingress.example.com
  tls: []
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

config:
  apm-server:
    ### Defines the host and port the server is listening on
    host: "0.0.0.0:8200"

    ## Maximum permitted size in bytes of an unzipped request accepted by the server to be processed.
    # max_unzipped_size: 52428800
    ## Maximum permitted size in bytes of a request's header accepted by the server to be processed.
    # max_header_size: 1048576

    ## Maximum permitted duration in seconds for reading an entire request.
    # read_timeout: 2s
    ## Maximum permitted duration in seconds for writing a response.
    # write_timeout: 2s

    ## Maximum duration in seconds before releasing resources when shutting down the server.
    # shutdown_timeout: 5s

    ## Maximum number of requests permitted to be sent to the server concurrently.
    # concurrent_requests: 40

    ## Authorization token to be checked. If a token is set here the agents must
    ## send their token in the following format: Authorization: Bearer <secret-token>.
    ## It is recommended to use an authorization token in combination with SSL enabled.
    # secret_token:
    # ssl.enabled: false
    # ssl.certificate : "path/to/cert"
    # ssl.key : "path/to/private_key"

  queue: {}
    ## Queue type by name (default 'mem')
    ## The memory queue will present all available events (up to the outputs
    ## bulk_max_size) to the output, the moment the output is ready to server
    ## another batch of events.
    # mem:
      ## Max number of events the queue can buffer.
      # events: 4096

      ## Hints the minimum number of events stored in the queue,
      ## before providing a batch of events to the outputs.
      ## A value of 0 (the default) ensures events are immediately available
      ## to be sent to the outputs.
      # flush.min_events: 2048

      ## Maximum duration after which events are available to the outputs,
      ## if the number of events stored in the queue is < min_flush_events.
      # flush.timeout: 1s

  # When a key contains a period, use this format for setting values on the command line:
  # --set config."output\.file".enabled=false
  output.file:
    # enabled: false
    path: "/usr/share/apm-server/data"
    filename: apm-server
    rotate_every_kb: 10000
    number_of_files: 5

  ## Set output.file.enabled to false to enable elasticsearch
  # output.elasticsearch:
  #  hosts: ["elasticsearch:9200"]
  #  protocol: "https"
  #  username: "elastic"
  #  password: "changeme"

# List of beat plugins
plugins: []
  # - kinesis.so

# User used to run the container. 1000 = apm-server
runAsUser: 1000
runAsGroup: 1000

# Additional container arguments
extraArgs: []
  # - -d
  # - *

# A map of additional environment variables
extraVars: {}
  # test1: "test2"

# Add additional volumes and mounts, for example to read other log files on the host
extraVolumes: []
  # - hostPath:
  #     path: /var/log
  #   name: varlog
extraVolumeMounts: []
  # - name: varlog
  #   mountPath: /host/var/log
  #   readOnly: true

## Labels to be added to pods
podLabels: {}

## Annotations to be added to pods
podAnnotations: {}

resources: {}
  ## We usually recommend not to specify default resources and to leave this as a conscious
  ## choice for the user. This also increases chances charts run on environments with little
  ## resources, such as Minikube. If you do want to specify resources, uncomment the following
  ## lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #  cpu: 100m
  #  memory: 200Mi
  # requests:
  #  cpu: 100m
  #  memory: 100Mi

## Node labels for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
nodeSelector: {}

# Tolerations for pod assignment
# Ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
tolerations: []

## Affinity configuration for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
affinity: {}

rbac:
  # Specifies whether RBAC resources should be created
  create: true

serviceAccount:
  # Specifies whether a ServiceAccount should be created
  create: true
  # The name of the ServiceAccount to use.
  # If not set and create is true, a name is generated using the fullname template
  name:
