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


{{/*
Create the name of the service account to use
*/}}
{{- define "prometheus-pushgateway.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "prometheus-pushgateway.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

{{/*
Create default labels
*/}}
{{- define "prometheus-pushgateway.defaultLabels" -}}
{{- $labelChart := include "prometheus-pushgateway.chart" $ -}}
{{- $labelApp := include "prometheus-pushgateway.name" $ -}}
{{- $labels := dict "app" $labelApp "chart" $labelChart "release" .Release.Name "heritage" .Release.Service -}}
{{ merge .extraLabels $labels | toYaml | indent 4 }}
{{- end -}}

{{/*
Return the appropriate apiVersion for networkpolicy.
*/}}
{{- define "prometheus-pushgateway.networkPolicy.apiVersion" -}}
{{- if semverCompare ">=1.4-0, <1.7-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "extensions/v1beta1" -}}
{{- else if semverCompare "^1.7-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "networking.k8s.io/v1" -}}
{{- end -}}
{{- end -}}
 # deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ template "prometheus-pushgateway.fullname" . }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.podLabels) .  }}
spec:
  replicas: {{ .Values.replicaCount }}
  {{- if .Values.strategy }}
  strategy:
{{ toYaml .Values.strategy | indent 4 }}
  {{- end }}
  selector:
    matchLabels:
      app: {{ template "prometheus-pushgateway.name" . }}
      release: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app: {{ template "prometheus-pushgateway.name" . }}
        release: {{ .Release.Name }}
      annotations:
{{ toYaml .Values.podAnnotations | indent 8 }}
    spec:
      serviceAccountName: {{ template "prometheus-pushgateway.serviceAccountName" . }}
      containers:
        - name: pushgateway
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
        {{- if .Values.extraVars }}
          env:
{{ toYaml .Values.extraVars | indent 12 }}
        {{- end }}
        {{- if .Values.extraArgs }}
          args:
{{ toYaml .Values.extraArgs | indent 12 }}
        {{- end }}
          ports:
            - name: metrics
              containerPort: 9091
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /-/healthy
              port: 9091
            initialDelaySeconds: 10
            timeoutSeconds: 10
          readinessProbe:
            httpGet:
              path: /-/ready
              port: 9091
            initialDelaySeconds: 10
            timeoutSeconds: 10
          resources:
{{ toYaml .Values.resources | indent 12 }}
          {{- if .Values.persistentVolume.enabled }}
          volumeMounts:
            - name: storage-volume
              mountPath: "{{ .Values.persistentVolume.mountPath }}"
              subPath: "{{ .Values.persistentVolume.subPath }}"
          {{- end }}
    {{- 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 }}
      {{- if .Values.persistentVolume.enabled }}
    {{- if .Values.securityContext }}
      securityContext:
{{ toYaml .Values.securityContext | indent 8 }}
    {{- end }}
      volumes:
        - name: storage-volume
          persistentVolumeClaim:
            claimName: {{ if .Values.persistentVolume.existingClaim }}{{ .Values.persistentVolume.existingClaim }}{{- else }}{{ template "prometheus-pushgateway.fullname" . }}{{- end }}
      {{- end -}}
 # ingress.yaml
{{- if .Values.ingress.enabled -}}
{{- $serviceName := include "prometheus-pushgateway.fullname" . }}
{{- $servicePort := .Values.service.port -}}
{{- $ingressPath := .Values.ingress.path -}}
{{- if semverCompare ">=1.14.0-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: networking.k8s.io/v1beta1
{{- else }}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
{{- if .Values.ingress.annotations }}
  annotations:
{{ toYaml .Values.ingress.annotations | indent 4}}
{{- end }}
  labels:
    app: {{ template "prometheus-pushgateway.name" . }}
    chart: {{ template "prometheus-pushgateway.chart" . }}
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
  name: {{ template "prometheus-pushgateway.fullname" . }}
spec:
  rules:
    {{- range $host := .Values.ingress.hosts }}
    - host: {{ $host }}
      http:
        paths:
          - path: {{ $ingressPath }}
            backend:
              serviceName: {{ $serviceName }}
              servicePort: {{ $servicePort }}
    {{- end -}}
{{- if .Values.ingress.tls }}
  tls:
{{ toYaml .Values.ingress.tls | indent 4 }}
  {{- end -}}
{{- end -}}
 # networkpolicy.yaml
{{ if .Values.networkPolicy }}
apiVersion: {{ template "prometheus-pushgateway.networkPolicy.apiVersion" . }}
kind: NetworkPolicy
metadata:
{{- if .Values.networkPolicy.customSelectors }}
  name: ingress-allow-customselector-{{ template "prometheus-pushgateway.name" . }}
{{- else if .Values.networkPolicy.allowAll }}
  name: ingress-allow-all-{{ template "prometheus-pushgateway.name" . }}
{{- else -}}
{{- fail "One of `allowAll` or `customSelectors` must be specified." }}
{{- end }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.podLabels) .  }}
spec:
  podSelector:
    matchLabels:
      app: {{ template "prometheus-pushgateway.name" .}}
      release: {{ .Release.Name }}
  ingress:
    - ports:
      - port: {{ .Values.service.targetPort }}
{{- if .Values.networkPolicy.customSelectors }}
      from:
{{ toYaml .Values.networkPolicy.customSelectors | indent 8 }}
{{- end -}}
{{- end -}}
 # pdb.yaml
{{- if .Values.podDisruptionBudget -}}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: {{ template "prometheus-pushgateway.fullname" . }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.podLabels) .  }}
spec:
  selector:
    matchLabels:
      app: {{ template "prometheus-pushgateway.name" . }}
{{ toYaml .Values.podDisruptionBudget | indent 2 }}
{{- end -}} # pushgateway-pvc.yaml
{{- if .Values.persistentVolume.enabled -}}
{{- if not .Values.persistentVolume.existingClaim -}}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  {{- if .Values.persistentVolume.annotations }}
  annotations:
{{ toYaml .Values.persistentVolume.annotations | indent 4 }}
  {{- end }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.persistentVolumeLabels) .  }}
  name: {{ template "prometheus-pushgateway.fullname" . }}
spec:
  accessModes:
{{ toYaml .Values.persistentVolume.accessModes | indent 4 }}
{{- if .Values.persistentVolume.storageClass }}
{{- if (eq "-" .Values.persistentVolume.storageClass) }}
  storageClassName: ""
{{- else }}
  storageClassName: "{{ .Values.persistentVolume.storageClass }}"
{{- end }}
{{- end }}
  resources:
    requests:
      storage: "{{ .Values.persistentVolume.size }}"
{{- end -}}
{{- end -}}
 # service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "prometheus-pushgateway.fullname" . }}
  annotations:
{{ .Values.serviceAnnotations | toYaml | indent 4 }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.serviceLabels) .  }}
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: {{ .Values.service.targetPort }}
      {{- if and (eq .Values.service.type "NodePort") .Values.service.nodePort }}
      nodePort: {{ .Values.service.nodePort }}
      {{- end }}
      protocol: TCP
      name: http
  selector:
    app: {{ template "prometheus-pushgateway.name" . }}
    release: {{ .Release.Name }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "prometheus-pushgateway.serviceAccountName" . }}
  labels:
{{ template "prometheus-pushgateway.defaultLabels" merge (dict "extraLabels" .Values.serviceAccountLabels) .  }}
{{- end -}}
 # servicemonitor.yaml
{{- if .Values.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ template "prometheus-pushgateway.fullname" .  }}
  {{- if .Values.serviceMonitor.namespace }}
  namespace: {{ .Values.serviceMonitor.namespace }}
  {{- end }}
  labels:
    app: {{ template "prometheus-pushgateway.name" . }}
    chart: {{ template "prometheus-pushgateway.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    {{- if .Values.serviceMonitor.additionalLabels }}
{{ toYaml .Values.serviceMonitor.additionalLabels | indent 4 }}
    {{- end }}
spec:
  endpoints:
  - port: http
    {{- if .Values.serviceMonitor.interval }}
    interval: {{ .Values.serviceMonitor.interval }}
    {{- end }}
    {{- if .Values.serviceMonitor.scrapeTimeout }}
    scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
    {{- end }}
    path: /metrics
    honorLabels: {{ .Values.serviceMonitor.honorLabels }}
  namespaceSelector:
    matchNames:
      - {{ .Release.Namespace }}
  selector:
    matchLabels:
      app: {{ template "prometheus-pushgateway.name" . }}
      release: {{ .Release.Name }}
{{- end -}}

# Default values for prometheus-pushgateway.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
image:
  repository: prom/pushgateway
  tag: v1.2.0
  pullPolicy: IfNotPresent

service:
  type: ClusterIP
  port: 9091
  targetPort: 9091

# Optional pod annotations
podAnnotations: {}

# Optional pod labels
podLabels: {}

# Optional service annotations
serviceAnnotations: {}

# Optional service labels
serviceLabels: {}

# Optional serviceAccount labels
serviceAccountLabels: {}

# Optional persistentVolume labels
persistentVolumeLabels: {}

# Optional additional environment variables
extraVars: []

## Additional pushgateway container arguments
##
## example:
## extraArgs:
##  - --persistence.file=/data/pushgateway.data
##  - --persistence.interval=5m
extraArgs: []

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: 200m
  #    memory: 50Mi
  # requests:
  #   cpu: 100m
  #   memory: 30Mi

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:

## Configure ingress resource that allow you to access the
## pushgateway installation. Set up the URL
## ref: http://kubernetes.io/docs/user-guide/ingress/
##
ingress:
  ## Enable Ingress.
  ##
  enabled: false
  # AWS ALB requires path of /*
  path: /

    ## Annotations.
    ##
    # annotations:
    #   kubernetes.io/ingress.class: nginx
    #   kubernetes.io/tls-acme: 'true'

    ## Hostnames.
    ## Must be provided if Ingress is enabled.
    ##
    # hosts:
    #   - pushgateway.domain.com

    ## TLS configuration.
    ## Secrets must be manually created in the namespace.
    ##
    # tls:
    #   - secretName: pushgateway-tls
    #     hosts:
    #       - pushgateway.domain.com

tolerations: {}
  # - effect: NoSchedule
  #   operator: Exists

## Node labels for pushgateway pod assignment
## Ref: https://kubernetes.io/docs/user-guide/node-selection/
##
nodeSelector: {}

replicaCount: 1

## Security context to be added to push-gateway pods
##
securityContext:
  fsGroup: 65534
  runAsUser: 65534
  runAsNonRoot: true

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

# Enable this if you're using https://github.com/coreos/prometheus-operator
serviceMonitor:
  enabled: false
  namespace: monitoring

  # Fallback to the prometheus default unless specified
  # interval: 10s

  # Fallback to the prometheus default unless specified
  # scrapeTimeout: 30s

  ## Used to pass Labels that are used by the Prometheus installed in your cluster to select Service Monitors to work with
  ## ref: https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#prometheusspec
  additionalLabels: {}

  # Retain the job and instance labels of the metrics pushed to the Pushgateway
  # [Scraping Pushgateway](https://github.com/prometheus/pushgateway#configure-the-pushgateway-as-a-target-to-scrape)
  honorLabels: true

# The values to set in the PodDisruptionBudget spec (minAvailable/maxUnavailable)
# If not set then a PodDisruptionBudget will not be created
podDisruptionBudget: {}

# Deployment Strategy type
strategy:
  type: Recreate

persistentVolume:
  ## If true, pushgateway will create/use a Persistent Volume Claim
  ## If false, use emptyDir
  ##
  enabled: false

  ## pushgateway data Persistent Volume access modes
  ## Must match those of existing PV or dynamic provisioner
  ## Ref: http://kubernetes.io/docs/user-guide/persistent-volumes/
  ##
  accessModes:
    - ReadWriteOnce

  ## pushgateway data Persistent Volume Claim annotations
  ##
  annotations: {}

  ## pushgateway data Persistent Volume existing claim name
  ## Requires pushgateway.persistentVolume.enabled: true
  ## If defined, PVC must be created manually before volume will be bound
  existingClaim: ""

  ## pushgateway data Persistent Volume mount root path
  ##
  mountPath: /data

  ## pushgateway data Persistent Volume size
  ##
  size: 2Gi

  ## pushgateway data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"

  ## Subdirectory of pushgateway data Persistent Volume to mount
  ## Useful if the volume's root directory is not empty
  ##
  subPath: ""

# Configuration for clusters with restrictive network policies in place:
# - allowAll allows access to the PushGateway from any namespace
# - customSelector is a list of pod/namespaceSelectors to allow access from
# These options are mutually exclusive and the latter will take precedence.
networkPolicy: {}
  # allowAll: true
  # customSelectors:
  #   - namespaceSelector:
  #       matchLabels:
  #         type: admin
  #   - podSelector:
  #       matchLabels:
  #         app: myapp
