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

{{/*
Return the appropriate apiVersion for RBAC APIs.
*/}}
{{- define "rbac.apiVersion" -}}
{{- if .Capabilities.APIVersions.Has "rbac.authorization.k8s.io/v1" -}}
rbac.authorization.k8s.io/v1
{{- else if .Capabilities.APIVersions.Has "rbac.authorization.k8s.io/v1beta1" -}}
rbac.authorization.k8s.io/v1beta1
{{- else -}}
rbac.authorization.k8s.io/v1alpha1
{{- end -}}
{{- end -}}

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

{{/*
Return the appropriate apiGroup for PodSecurityPolicy.
*/}}
{{- define "rbac.pspApiGroup" -}}
{{- if semverCompare "<1.14-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "extensions" -}}
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "policy" -}}
{{- end -}}
{{- end -}}

{{/*
Return the appropriate apiVersion for DaemonSet.
*/}}
{{- define "daemonSet.apiVersion" -}}
{{- if semverCompare "<1.9-0" .Capabilities.KubeVersion.GitVersion -}}
{{- print "extensions/v1beta1" -}}
{{- else -}}
{{- print "apps/v1" -}}
{{- end -}}
{{- end -}}
 # cluster-role.yaml
{{- if .Values.rbac.create -}}
apiVersion: {{ template "rbac.apiVersion" . }}
kind: ClusterRole
metadata:
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "fluent-bit.fullname" . }}
rules:
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - get
{{- if .Values.rbac.pspEnabled }}
  - apiGroups:
    - {{ template "rbac.pspApiGroup" . }}
    resources:
    - podsecuritypolicies
    resourceNames:
    - {{ template "fluent-bit.fullname" . }}
    verbs:
    - use
{{- end }}
{{- end -}}
 # cluster-rolebinding.yaml
{{- if .Values.rbac.create -}}
apiVersion: {{ template "rbac.apiVersion" . }}
kind: ClusterRoleBinding
metadata:
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "fluent-bit.fullname" . }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: {{ template "fluent-bit.fullname" . }}
subjects:
  - kind: ServiceAccount
    name: {{ template "fluent-bit.serviceAccountName" . }}
    namespace: {{ .Release.Namespace }}
{{- end -}}
 # config.yaml
{{- if (empty .Values.existingConfigMap) -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "fluent-bit.fullname" . }}-config
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
data:
  fluent-bit-service.conf: |
    [SERVICE]
        Flush        {{ .Values.service.flush }}
        Daemon       Off
        Log_Level    {{ .Values.service.logLevel }}
        Parsers_File parsers.conf
{{- if .Values.parsers.enabled }}
        Parsers_File parsers_custom.conf
{{- end }}
{{- if .Values.metrics.enabled }}
        HTTP_Server  On
        HTTP_Listen  0.0.0.0
        HTTP_Port    2020
{{- end }}
{{ .Values.extraEntries.service | indent 8 }}

  fluent-bit-input.conf: |
    [INPUT]
        Name              tail
        Path              {{ .Values.input.tail.path }}
        Parser            {{ .Values.input.tail.parser }}
        Tag               {{ .Values.filter.kubeTag }}.*
        Refresh_Interval  5
        Mem_Buf_Limit     {{ .Values.input.tail.memBufLimit }}
        Skip_Long_Lines   On
{{- if .Values.input.tail.ignore_older }}
        Ignore_Older      {{ .Values.input.tail.ignore_older }}
{{- end }}
{{- if .Values.trackOffsets }}
        DB                /tail-db/tail-containers-state.db
        DB.Sync           Normal
{{- end }}
{{- if .Values.input.tail.dockerMode }}
        Docker_Mode       On
        Docker_Mode_Flush {{ .Values.input.tail.dockerModeFlush }}
{{- end }}
{{- if .Values.input.tail.exclude_path }}
        Exclude_Path    {{ .Values.input.tail.exclude_path }}
{{- end }}
{{- if .Values.input.systemd.enabled }}
    [INPUT]
        Name            systemd
        Tag             {{ .Values.input.systemd.tag }}
{{- range $value := .Values.input.systemd.filters.systemdUnit }}
        Systemd_Filter  _SYSTEMD_UNIT={{ $value }}
{{- end }}
        Max_Entries     {{ .Values.input.systemd.maxEntries }}
        Read_From_Tail  {{ .Values.input.systemd.readFromTail }}
        Strip_Underscores  {{ .Values.input.systemd.stripUnderscores }}
{{- end }}
{{ .Values.extraEntries.input | indent 8 }}

{{- if .Values.audit.enable }}
    [INPUT]
        Name              tail
        Path              {{ .Values.audit.input.path }}
        Parser            {{ .Values.audit.input.parser }}
        DB                /var/log/audit.db
        Tag               {{ .Values.audit.input.tag }}
        Refresh_Interval  5
        Mem_Buf_Limit     {{ .Values.audit.input.memBufLimit }}
        Buffer_Chunk_Size {{ .Values.audit.input.bufferChunkSize }}
        Buffer_Max_Size   {{ .Values.audit.input.bufferMaxSize }}
        Skip_Long_Lines   {{ .Values.audit.input.skipLongLines}}
        Key               {{ .Values.audit.input.key}}
{{ .Values.extraEntries.audit | indent 8 }}
{{- end }}

  fluent-bit-filter.conf: |
    [FILTER]
        Name                kubernetes
        Match               {{ .Values.filter.kubeTag }}.*
        Kube_Tag_Prefix     {{ .Values.filter.kubeTagPrefix }}
        Kube_URL            {{ .Values.filter.kubeURL }}
        Kube_CA_File        {{ .Values.filter.kubeCAFile }}
        Kube_Token_File     {{ .Values.filter.kubeTokenFile }}
{{- if .Values.filter.mergeJSONLog }}
        Merge_Log           On
{{- end }}

{{- if .Values.filter.mergeLogKey }}
        Merge_Log_Key       {{ .Values.filter.mergeLogKey }}
{{- end }}

{{- if .Values.filter.enableParser }}
        K8S-Logging.Parser  On
{{- end }}
{{- if .Values.filter.enableExclude }}
        K8S-Logging.Exclude On
{{- end }}
{{- if .Values.filter.useJournal }}
        Use_Journal         On
{{- end }}
{{ .Values.extraEntries.filter | indent 8 }}

  fluent-bit-output.conf: |
{{ if eq .Values.backend.type "test" }}
    [OUTPUT]
        Name  file
        Match *
        Path /tmp/fluent-bit.log
{{ else if eq .Values.backend.type "forward" }}
    [OUTPUT]
        Name          forward
        Match         *
        Host          {{ .Values.backend.forward.host }}
        Port          {{ .Values.backend.forward.port }}
        Retry_Limit False
{{- if .Values.backend.forward.shared_key }}
        Shared_Key    {{ .Values.backend.forward.shared_key }}
{{- end }}
{{- if .Values.backend.forward.tls }}
        tls           {{ .Values.backend.forward.tls }}
{{- end }}
{{- if .Values.backend.forward.tls_verify }}
        tls.verify    {{ .Values.backend.forward.tls_verify }}
{{- end }}
{{- if .Values.backend.forward.tls_debug }}
        tls.debug     {{ .Values.backend.forward.tls_debug }}
{{- end }}
{{ else if eq .Values.backend.type "es" }}
    [OUTPUT]
        Name  es
        Match *
        Host  {{ .Values.backend.es.host }}
        Port  {{ .Values.backend.es.port }}
        Logstash_Format {{ default "On" .Values.backend.es.logstash_format  }}
        Retry_Limit {{ .Values.backend.es.retry_limit }}
        Type  {{ .Values.backend.es.type }}
{{- if .Values.backend.es.time_key }}
        Time_Key {{ .Values.backend.es.time_key }}
{{- end }}
{{- if .Values.backend.es.replace_dots }}
        Replace_Dots {{ .Values.backend.es.replace_dots }}
{{- end }}
{{- if .Values.backend.es.logstash_prefix }}
        Logstash_Prefix {{ .Values.backend.es.logstash_prefix }}
{{- if .Values.backend.es.logstash_prefix_key }}
        Logstash_Prefix_Key {{ .Values.backend.es.logstash_prefix_key }}
{{- end }}
{{- if .Values.backend.es.logstash_dateformat }}
        Logstash_DateFormat {{ .Values.backend.es.logstash_dateformat }}
{{- end }}
{{ else if .Values.backend.es.index }}
        Index {{ .Values.backend.es.index }}
{{- end }}
{{- if .Values.backend.es.http_user }}
        HTTP_User {{ .Values.backend.es.http_user }}
{{- if .Values.backend.es.http_passwd }}
        HTTP_Passwd {{ .Values.backend.es.http_passwd }}
{{- else }}
        HTTP_Passwd ${HTTP_PASSWORD}
{{- end }}
{{- end }}
{{if eq .Values.backend.es.tls "on" }}
        tls {{ .Values.backend.es.tls }}
        tls.verify {{ .Values.backend.es.tls_verify }}
        tls.debug {{ .Values.backend.es.tls_debug }}
{{- if .Values.backend.es.tls_ca }}
        tls.ca_file /secure/es-tls-ca.crt
{{- end }}
{{- end }}
{{ else if eq .Values.backend.type "splunk" }}
    [OUTPUT]
        Name  splunk
        Match *
        Host  {{ .Values.backend.splunk.host }}
        Port  {{ .Values.backend.splunk.port }}
        Splunk_Token  {{ .Values.backend.splunk.token }}
        Splunk_Send_Raw {{ .Values.backend.splunk.send_raw}}
        TLS   {{ .Values.backend.splunk.tls }}
        TLS.Verify   {{ .Values.backend.splunk.tls_verify }}
        tls.debug {{ .Values.backend.splunk.tls_debug }}
        Message_Key   {{ .Values.backend.splunk.message_key }}
{{ else if eq .Values.backend.type "stackdriver" }}
    [OUTPUT]
        Name  stackdriver
        Match *
        resource global
{{- if .Values.backend.stackdriver.google_service_credentials }}
        google_service_credentials /secure/google_service_credentials.json
{{- else }}
        service_account_email  {{ .Values.backend.stackdriver.service_account_email }}
        service_account_secret  {{ .Values.backend.stackdriver.service_account_secret }}
{{- end }}
{{ else if eq .Values.backend.type "http" }}
    [OUTPUT]
        Name  http
        Match *
        Host {{ .Values.backend.http.host }}
        Port {{ .Values.backend.http.port }}
        URI {{ .Values.backend.http.uri }}
{{- if .Values.backend.http.http_user }}
        HTTP_User {{ .Values.backend.http.http_user }}
        HTTP_Passwd {{ .Values.backend.http.http_passwd }}
{{- end }}
        tls {{ .Values.backend.http.tls }}
        tls.verify {{ .Values.backend.http.tls_verify }}
        tls.debug {{ .Values.backend.http.tls_debug }}
{{- if .Values.backend.http.proxy }}
        Proxy {{ .Values.backend.http.proxy }}
{{- end }}
        Format {{ .Values.backend.http.format }}
{{- end }}
{{- if .Values.backend.http.json_date_format }}
        json_date_format {{ .Values.backend.http.json_date_format }}
{{- end }}
{{- range  .Values.backend.http.headers }}
        Header  {{ . }}
{{- end }}
{{ .Values.extraEntries.output | indent 8 }}


  fluent-bit.conf: |
{{ .Values.rawConfig | indent 4 }}

  parsers.conf: |
{{- if .Values.parsers.regex }}
{{- range .Values.parsers.regex }}
    [PARSER]
        Name        {{ .name }}
        Format      regex
        Regex       {{ .regex }}
{{- if .timeKey }}
        Time_Key    {{ .timeKey }}
{{- end }}
{{- if .timeFormat }}
        Time_Format {{ .timeFormat }}
{{- end }}
{{ end }}
{{- end }}
{{- if .Values.parsers.json }}
{{- range .Values.parsers.json }}
    [PARSER]
        Name        {{ .name }}
        Format      json
{{- if .timeKeep }}
        Time_Keep   {{ .timeKeep }}
{{- end }}
{{- if .timeKey }}
        Time_Key    {{ .timeKey }}
{{- end }}
{{- if .timeFormat }}
        Time_Format {{ .timeFormat }}
{{- end }}
{{- if .decodeFieldAs  }}
        Decode_Field_As {{ .decodeFieldAs }} {{ .decodeField | default "log" }}
{{- end}}
{{- if .extraEntries }}
{{ .extraEntries | indent 8 }}
{{- end }}
{{ end }}
{{- end }}
{{- if .Values.parsers.logfmt }}
{{- range .Values.parsers.logfmt }}
    [PARSER]
        Name        {{ .name }}
        Format      logfmt
{{- if .timeKey }}
        Time_Key    {{ .timeKey }}
{{- end }}
{{- if .timeFormat }}
        Time_Format {{ .timeFormat }}
{{- end }}
{{- if .extraEntries }}
{{ .extraEntries | indent 8 }}
{{- end }}
{{ end }}
{{- end }}

{{- end -}}
 # daemonset.yaml
apiVersion: {{ template "daemonSet.apiVersion" . }}
kind: DaemonSet
metadata:
  name: {{ template "fluent-bit.fullname" . }}
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
spec:
  selector:
    matchLabels:
      app: {{ template "fluent-bit.name" . }}
      release: {{ .Release.Name }}
{{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 6 }}
{{- end }}
  updateStrategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: {{ template "fluent-bit.name" . }}
        release: {{ .Release.Name }}
{{- if .Values.podLabels }}
{{ toYaml .Values.podLabels | indent 8 }}
{{- end }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}
{{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
{{- end }}
    spec:
{{- if .Values.podSecurityContext }}
      securityContext:
{{ toYaml .Values.podSecurityContext | indent 8 }}
{{- end }}
{{- if .Values.priorityClassName }}
      priorityClassName: "{{ .Values.priorityClassName }}"
{{- end }}
{{- if .Values.image.pullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.image.pullSecrets | indent 8 }}
{{- end }}
      hostNetwork: {{ .Values.hostNetwork }}
      dnsPolicy: {{ .Values.dnsPolicy }}
{{- if .Values.dnsConfig }}
      dnsConfig:
{{ toYaml .Values.dnsConfig | indent 8 }}
{{- end }}
      serviceAccountName: {{ template "fluent-bit.serviceAccountName" . }}
{{- if .Values.initContainers }}
      initContainers:
{{- range $key, $value := .Values.initContainers }}
      - name: "{{ $key }}"
{{ toYaml $value | indent 8 }}
{{- end }}
{{- end }}
      containers:
      - name: fluent-bit
        image: "{{ .Values.image.fluent_bit.repository }}:{{ .Values.image.fluent_bit.tag }}"
        imagePullPolicy: "{{ .Values.image.pullPolicy }}"
        env:
{{- if .Values.backend.es.http_passwd_secret }}
          - name: HTTP_PASSWORD
            valueFrom:
              secretKeyRef:
                name: {{ .Values.backend.es.http_passwd_secret }}
                key: {{ .Values.backend.es.http_passwd_secret_key }}
{{- end }}
{{- /* Only render empty array when no HTTP_PASSWORD */ -}}
{{- if or .Values.env (not .Values.backend.es.http_passwd_secret) }}
{{ toYaml .Values.env | indent 10 }}
{{- end }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
{{- if or .Values.metrics.enabled .Values.extraPorts }}
        ports:
{{- if .Values.metrics.enabled }}
        - name: metrics
          containerPort: 2020
          protocol: TCP
{{- end -}}
{{- if .Values.extraPorts }}
{{ toYaml .Values.extraPorts | indent 8 }}
{{- end }}
{{- end }}
{{- if .Values.securityContext }}
        securityContext:
{{ toYaml .Values.securityContext | indent 10 }}
{{- end }}
        volumeMounts:
        - name: varlog
          mountPath: /var/log
        - name: varlibdockercontainers
          mountPath: /var/lib/docker/containers
          readOnly: true
      {{- if .Values.input.systemd.enabled }}
        - name: etcmachineid
          mountPath: /etc/machine-id
          readOnly: true
      {{- end }}
{{- if .Values.fullConfigMap }}
        - name: config
          mountPath: /fluent-bit/etc
{{- else }}
        - name: config
          mountPath: /fluent-bit/etc/fluent-bit.conf
          subPath: fluent-bit.conf
        - name: config
          mountPath: /fluent-bit/etc/fluent-bit-service.conf
          subPath: fluent-bit-service.conf
        - name: config
          mountPath: /fluent-bit/etc/fluent-bit-input.conf
          subPath: fluent-bit-input.conf
        - name: config
          mountPath: /fluent-bit/etc/fluent-bit-filter.conf
          subPath: fluent-bit-filter.conf
        - name: config
          mountPath: /fluent-bit/etc/fluent-bit-output.conf
          subPath: fluent-bit-output.conf

{{- if .Values.parsers.enabled }}
        - name: config
          mountPath: /fluent-bit/etc/parsers_custom.conf
          subPath: parsers.conf
{{- end }}
{{- end }}
{{- if and .Values.backend.type "stackdriver" .Values.backend.stackdriver.google_service_credentials }}
        - name: gcp-stackdriver-secret
          mountPath: /secure/google_service_credentials.json
          subPath: google_service_credentials.json
{{- end }}
{{- if or .Values.backend.es.tls_ca .Values.backend.es.tls_secret }}
        - name: es-tls-secret
          mountPath: /secure/es-tls-ca.crt
          subPath: {{ .Values.backend.es.tls_secret_ca_key | default "es-tls-ca.crt" | quote }}
{{- end }}
{{- if .Values.trackOffsets }}
        - name: tail-db
          mountPath: /tail-db
{{- end }}
{{- if .Values.extraVolumeMounts }}
{{ toYaml .Values.extraVolumeMounts | indent 8 }}
{{- end }}
{{ if .Values.on_minikube }}
        - name: mnt
          mountPath: /mnt
          readOnly: true
{{ end }}
      terminationGracePeriodSeconds: 10
    {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
    {{- end }}
      {{ if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
      {{- end }}
    {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
    {{- end }}
      volumes:
      - name: varlog
        hostPath:
          path: /var/log
      - name: varlibdockercontainers
        hostPath:
          path: /var/lib/docker/containers
    {{- if .Values.input.systemd.enabled }}
      - name: etcmachineid
        hostPath:
          path: /etc/machine-id
          type: File
    {{- end }}
{{- if or .Values.backend.es.tls_ca .Values.backend.es.tls_secret }}
      - name: es-tls-secret
        secret:
          secretName: {{ .Values.backend.es.tls_secret | default ( print ( include "fluent-bit.fullname" . ) "-es-tls-secret" ) | quote }}
{{- end }}
{{- if and .Values.backend.type "stackdriver" .Values.backend.stackdriver.google_service_credentials }}
      - name: gcp-stackdriver-secret
        secret:
          secretName: "{{ template "fluent-bit.fullname" . }}-gcp-stackdriver-secret"
{{- end }}
{{- if .Values.trackOffsets }}
      - name: tail-db
        hostPath:
          path: {{ .Values.taildb.directory }}
          type: DirectoryOrCreate
{{- end }}
      - name: config
        configMap:
          name: {{ if .Values.existingConfigMap }}{{ .Values.existingConfigMap }}{{- else }}{{ template "fluent-bit.fullname" . }}-config{{- end }}
{{- if .Values.extraVolumes }}
{{ toYaml .Values.extraVolumes | indent 6 }}
{{- end }}
{{ if .Values.on_minikube }}
      - name: mnt
        hostPath:
          path: /mnt
{{ end }}
 # psp.yaml
{{- if .Values.rbac.pspEnabled }}
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: {{ template "fluent-bit.fullname" . }}
spec:
  # Prevents running in privileged mode
  privileged: false
  # Required to prevent escalations to root.
  allowPrivilegeEscalation: false
  # This is redundant with non-root + disallow privilege escalation,
  # but we can provide it for defense in depth.
  requiredDropCapabilities:
    - ALL
  volumes:
    - 'configMap'
    - 'secret'
    - 'hostPath'
  allowedHostPaths:
    - pathPrefix: "/var/log"
    - pathPrefix: "/var/lib/docker/containers"
      readOnly: true
{{- if .Values.input.systemd.enabled }}
    - pathPrefix: "/etc/machine-id"
      readOnly: true
{{- end }}
    - pathPrefix: "/fluent-bit/etc"
{{- if .Values.trackOffsets }}
    - pathPrefix: {{ .Values.taildb.directory }}
{{- end }}
{{- if .Values.on_minikube }}
    - pathPrefix: "/mnt"
{{- end }}
{{- range .Values.extraVolumes }}
  {{- if .hostPath }}
    - pathPrefix: {{ .hostPath.path }}
  {{- end }}
{{- end }}
  hostNetwork: {{ .Values.hostNetwork }}
  hostIPC: false
  hostPID: false
  runAsUser:
    rule: 'RunAsAny'
  seLinux:
    # This policy assumes the nodes are using AppArmor rather than 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 }}
 # secret.yaml
{{- if not .Values.backend.es.tls_secret }}
---
apiVersion: v1
kind: Secret
metadata:
  name: "{{ template "fluent-bit.fullname" . }}-es-tls-secret"
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
type: Opaque
data:
  es-tls-ca.crt: {{ .Values.backend.es.tls_ca | b64enc | quote }}
{{- end }}
{{- if eq .Values.backend.type "stackdriver" }}
---
apiVersion: v1
kind: Secret
metadata:
  name: "{{ template "fluent-bit.fullname" . }}-gcp-stackdriver-secret"
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
type: Opaque
data:
  google_service_credentials.json: {{ .Values.backend.stackdriver.google_service_credentials | b64enc | quote }}
{{- end }}
 # service.yaml
{{- if .Values.metrics.enabled }}
apiVersion: v1
kind: Service
metadata:
{{- if .Values.metrics.service.annotations }}
  annotations:
{{ toYaml .Values.metrics.service.annotations | indent 4 }}
{{- end }}
  name: {{ template "fluent-bit.fullname" . }}-metrics
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  {{- if .Values.metrics.service }}
  {{- range $key, $value := .Values.metrics.service.labels }}
    {{ $key }}: {{ $value | quote }}
  {{- end }}
  {{- end }}
spec:
  type: {{ .Values.metrics.service.type}}
  sessionAffinity: None
  ports:
  - port: {{ .Values.metrics.service.port }}
    targetPort: metrics
    name: metrics
  selector:
    app: {{ template "fluent-bit.name" . }}
    release: {{ .Release.Name }}
{{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "fluent-bit.serviceAccountName" . }}
  {{- with .Values.serviceAccount.annotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
  {{- end }}
{{- end -}}
 # servicemonitor.yaml
{{- if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled (.Capabilities.APIVersions.Has "monitoring.coreos.com/v1") }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ include "fluent-bit.fullname" . }}
  {{- if .Values.metrics.serviceMonitor.namespace }}
  namespace: {{ .Values.metrics.serviceMonitor.namespace }}
  {{- end }}
  labels:
    app: {{ template "fluent-bit.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
    {{- if .Values.metrics.serviceMonitor.additionalLabels }}
{{ toYaml .Values.metrics.serviceMonitor.additionalLabels | indent 4 }}
    {{- end }}
spec:
  endpoints:
    - port: metrics
      path: /api/v1/metrics/prometheus
      {{- if .Values.metrics.serviceMonitor.interval }}
      interval: {{ .Values.metrics.serviceMonitor.interval }}
      {{- end }}
      {{- if .Values.metrics.serviceMonitor.scrapeTimeout }}
      scrapeTimeout: {{ .Values.metrics.serviceMonitor.scrapeTimeout }}
      {{- end }}
  namespaceSelector:
    matchNames:
      - {{ .Release.Namespace }}
  selector:
    matchLabels:
      app: {{ include "fluent-bit.name" . }}
      release: {{ .Release.Name }}
{{- end }}
 # test-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "fluent-bit.fullname" . }}-test
  labels:
    app: {{ template "fluent-bit.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
data:
  run.sh: |-
    {{- if eq .Values.backend.type "forward"}}
    {{- if eq .Values.backend.forward.tls "on"}}
    fluent-gem install fluent-plugin-secure-forward
    {{- end }}
    @test "Test fluentd" {
      fluentd -c /tests/fluentd.conf --dry-run
    }
    {{- else if eq .Values.backend.type "es"}}
    @test "Test Elasticssearch Indices" {
      url="http://{{ .Values.backend.es.host }}:{{ .Values.backend.es.port }}/_cat/indices?format=json"
      body=$(curl $url)

      result=$(echo $body | jq -cr '.[] | select(.index | contains("{{ .Values.backend.es.index }}"))')
      [ "$result" != "" ]

      result=$(echo $body | jq -cr '.[] | select((.index | contains("{{ .Values.backend.es.index }}")) and (.health != "green"))')
      [ "$result" == "" ]
    }
    {{- end }}

  fluentd.conf: |-
    <source>
      {{- if eq .Values.backend.forward.tls "off" }}
      @type forward
      bind 0.0.0.0
      port {{ .Values.backend.forward.port }}
      {{- else }}
      @type secure_forward
      self_hostname myserver.local
      secure no
      {{- end }}
      shared_key {{ .Values.backend.forward.shared_key }}
    </source>

    <match **>
      @type stdout
    </match>
 # test.yaml
{{- if .Values.testFramework.enabled }}
{{- if or (eq .Values.backend.type "forward") (and (eq .Values.backend.type "es") (eq .Values.backend.es.tls "off")) }}
apiVersion: v1
kind: Pod
metadata:
  name: {{ template "fluent-bit.fullname" . }}-test
  labels:
    app: {{ template "fluent-bit.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
  annotations:
    "helm.sh/hook": test-success
spec:
{{- if .Values.testFramework.pullSecrets }}
  imagePullSecrets:
{{ toYaml .Values.testFramework.pullSecrets | indent 4 }}
{{- end }}
  initContainers:
    - name: test-framework
      image: "{{ .Values.testFramework.image}}:{{ .Values.testFramework.tag }}"
      command:
      - "bash"
      - "-c"
      - |
        set -ex
        # copy bats to tools dir
        cp -R /usr/local/libexec/ /tools/bats/
      volumeMounts:
      - mountPath: /tools
        name: tools
  containers:
    - name: {{ .Release.Name }}-test
      {{- if eq .Values.backend.type "forward"}}
      image: "{{ .Values.testFramework.fluentd.image }}:{{ .Values.testFramework.fluentd.tag }}"
      {{- else }}
      image: "{{ .Values.testFramework.curlJq.image }}:{{ .Values.testFramework.curlJq.tag }}"
      {{- end }}
      command: ["/tools/bats/bats", "-t", "/tests/run.sh"]
      {{- if and (eq .Values.backend.forward.tls "on") (eq .Values.backend.type "forward") }}
      securityContext:
        # run as root to install fluent gems
        runAsUser: 0
      {{- end }}
      volumeMounts:
        - mountPath: /tests
          name: tests
          readOnly: true
        - mountPath: /tools
          name: tools
  volumes:
  - name: tests
    configMap:
      name: {{ template "fluent-bit.fullname" . }}-test
  - name: tools
    emptyDir: {}
  restartPolicy: Never
{{- end }}
{{- end }}
# Minikube stores its logs in a separate directory.
# Enable if you install the chart in minikube.
on_minikube: false

image:
  fluent_bit:
    repository: fluent/fluent-bit
    tag: 1.3.7
  pullPolicy: Always
  # If specified, use these secrets to access the image
  # pullSecrets:
  #   - name: registry-secret

testFramework:
  # When enabled, performs helm tests
  enabled: true
  image: "dduportal/bats"
  tag: "0.4.0"
  # If specified, use these secrets to access the image
  # pullSecrets:
  #   - name: registry-secret
  # Backend test image when backend.type == "es"
  curlJq:
    image: dwdraju/alpine-curl-jq
    tag: latest
  # Backend test image when backend.type == "forward"
  # NOTE image runs as root user
  fluentd:
    image: fluent/fluentd
    tag: v1.4-debian-1

nameOverride: ""
fullnameOverride: ""

# When enabled, exposes json and prometheus metrics on {{ .Release.Name }}-metrics service
metrics:
  enabled: false
  service:
    # labels:
    #   key: value
    annotations: {}
    # In order for Prometheus to consume metrics automatically use the following annotations:
    # prometheus.io/path: "/api/v1/metrics/prometheus"
    # prometheus.io/port: "2020"
    # prometheus.io/scrape: "true"
    port: 2020
    type: ClusterIP
  serviceMonitor:
    enabled: false
    additionalLabels: {}
    # namespace: monitoring
    # interval: 30s
    # scrapeTimeout: 10s

# When enabled, fluent-bit will keep track of tailing offsets across pod restarts.
trackOffsets: false

## PriorityClassName
## Ref: https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/#priorityclass
priorityClassName: ""

backend:
  type: forward
  forward:
    host: fluentd
    port: 24284
    tls: "off"
    tls_verify: "on"
    tls_debug: 1
    shared_key:
  es:
    host: elasticsearch
    port: 9200
    # Elastic Index Name
    index: kubernetes_cluster
    type: flb_type
    logstash_prefix: kubernetes_cluster
    replace_dots: "On"
    logstash_format: "On"
    retry_limit: "False"
    time_key: "@timestamp"
    # Optional username credential for Elastic X-Pack access
    http_user:
    # Password for user defined in HTTP_User
    http_passwd:
    # Optional TLS encryption to ElasticSearch instance
    tls: "off"
    tls_verify: "on"
    # TLS certificate for the Elastic (in PEM format). Use if tls=on and tls_verify=on.
    tls_ca: ""
    # TLS debugging levels = 1-4
    tls_debug: 1
  splunk:
    host: 127.0.0.1
    port: 8088
    token: ""
    send_raw: "on"
    tls: "on"
    tls_verify: "off"
    tls_debug: 1
    message_key: "kubernetes"
  stackdriver: {}

  ##
  ## Ref: http://fluentbit.io/documentation/current/output/http.html
  ##
  http:
    host: 127.0.0.1
    port: 80
    uri: "/"
    http_user:
    http_passwd:
    tls: "off"
    tls_verify: "on"
    tls_debug: 1
    ## Specify the data format to be used in the HTTP request body
    ## Can be either 'msgpack' or 'json'
    format: msgpack
    # json_date_format: double or iso8601
    headers: []

parsers:
  enabled: false
  ## List the respective parsers in key: value format per entry
  ## Regex required fields are name and regex. JSON and Logfmt required field
  ## is name.
  regex: []
  logfmt: []
  ##  json parser config can be defined by providing an extraEntries field.
  ##  The following entry:
  ## json:
  ##   - extraEntries: |
  ##       Decode_Field_As  escaped log do_next
  ##       Decode_Field_As  json log
  ##
  ##  translates into
  ##
  ##   Command       |  Decoder  | Field | Optional Action   |
  ##   ==============|===========|=======|===================|
  ##   Decode_Field_As  escaped   log  do_next
  ##   Decode_Field_As  json log
  ##
  json: []

env: []

## Annotations to add to the DaemonSet's Pods
podAnnotations: {}

## By default there different 'files' provides in the config
## (fluent-bit.conf, custom_parsers.conf). This defeats
## changing a configmap (since it uses subPath). If this
## variable is set, the user is assumed to have provided,
## in 'existingConfigMap' the entire config (etc/*) of fluent-bit,
## parsers and system config. In this case, no subPath is
## used
fullConfigMap: false

## ConfigMap override where fullname is {{.Release.Name}}-{{.Values.existingConfigMap}}
## Defining existingConfigMap will cause templates/config.yaml
## to NOT generate a ConfigMap resource
##
existingConfigMap: ""


# NOTE If you want to add extra sections, add them here, inbetween the includes,
# wherever they need to go. Sections order matters.

rawConfig: |-
  @INCLUDE fluent-bit-service.conf
  @INCLUDE fluent-bit-input.conf
  @INCLUDE fluent-bit-filter.conf
  @INCLUDE fluent-bit-output.conf


# WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# This is to add extra entries to an existing section, NOT for adding new sections
# Do not submit bugs against indent being wrong. Add your new sections to rawConfig
# instead.
#
extraEntries:
  input: |-
#     # >=1 additional Key/Value entrie(s) for existing Input section
  audit: |-
#     # >=1 additional Key/Value entrie(s) for existing Input section
  filter: |-
#     # >=1 additional Key/Value entrie(s) for existing Filter section
  output: |-
#     # >=1 additional Key/Value entrie(s) for existing Ouput section
  service: |-
#     # >=1 additional Key/Value entrie(s) for existing Service section
# WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


## Extra ports to add to the daemonset ports section
extraPorts: []

## Extra volumes containing additional files required for fluent-bit to work
## (eg. CA certificates)
## Ref: https://kubernetes.io/docs/concepts/storage/volumes/
##
extraVolumes: []

## Extra volume mounts for the fluent-bit pod.
## Ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-volume-storage/
##
extraVolumeMounts: []

resources: {}
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  # requests:
  #   cpu: 10m
  #   memory: 8Mi

# When enabled, pods will bind to the node's network namespace.
hostNetwork: false

# Which DNS policy to use for the pod.
# Consider switching to 'ClusterFirstWithHostNet' when 'hostNetwork' is enabled.
dnsPolicy: ClusterFirst

# Optional field that allows more control on the DNS settings for the pod.
# Ref: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-dns-config
dnsConfig: {}
  # nameservers:
  #   - 1.2.3.4
  # searches:
  #   - ns1.svc.cluster-domain.example
  #   - my.dns.search.suffix
  # options:
  #   - name: ndots
  #     value: "2"
  #   - name: edns0

## Node tolerations for fluent-bit scheduling to nodes with taints
## Ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
##
tolerations: []
# - key: "key"
#  operator: "Equal|Exists"
#  value: "value"
#  effect: "NoSchedule|PreferNoSchedule|NoExecute(1.6 only)"

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

service:
  flush: 1
  logLevel: info

input:
  tail:
    memBufLimit: 5MB
    parser: docker
    path: /var/log/containers/*.log
    ignore_older: ""
    dockerMode: false
    dockerModeFlush: 4
    exclude_path: ""
  systemd:
    enabled: false
    filters:
      systemdUnit:
        - docker.service
        - kubelet.service
        - node-problem-detector.service
    maxEntries: 1000
    readFromTail: true
    stripUnderscores: false
    tag: host.*

audit:
  enable: false
  input:
    memBufLimit: 35MB
    parser: docker
    tag: audit.*
    path: /var/log/kube-apiserver-audit.log
    bufferChunkSize: 2MB
    bufferMaxSize: 10MB
    skipLongLines: On
    key: kubernetes-audit

filter:
  kubeURL: https://kubernetes.default.svc:443
  kubeCAFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
  kubeTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
  kubeTag: kube
  kubeTagPrefix: kube.var.log.containers.

# If true, check to see if the log field content is a JSON string map, if so,
# it append the map fields as part of the log structure.
  mergeJSONLog: true

# If set, all unpacked keys from mergeJSONLog (Merge_Log) will be packed under
# the key name specified on mergeLogKey (Merge_Log_Key)
  mergeLogKey: ""

# If true, enable the use of monitoring for a pod annotation of
# fluentbit.io/parser: parser_name. parser_name must be the name
# of a parser contained within parsers.conf
  enableParser: true

# If true, enable the use of monitoring for a pod annotation of
# fluentbit.io/exclude: true. If present, discard logs from that pod.
  enableExclude: true

# If true, the filter reads logs coming in Journald format.
  useJournal: false

rbac:
  # Specifies whether RBAC resources should be created
  create: true
  # Specifies whether a PodSecurityPolicy should be created
  pspEnabled: false

taildb:
  directory: /var/lib/fluent-bit

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

## Specifies security settings for a container
## Ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-container
securityContext: {}
  # securityContext:
  #   privileged: true

## Specifies security settings for a pod
## Ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-the-security-context-for-a-pod
podSecurityContext: {}
  # podSecurityContext:
  #   runAsUser: 1000

## Add your own init container (example installation of Lua filter plugin)
## Ref: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
initContainers: {}
  # load-plugin:
  #   image: "appropriate/curl:latest"
  #   imagePullPolicy: "IfNotPresent"
  #   # Assumed plugins volume is configured at Pod level via extraVolumes
  #   volumeMounts:
  #     - name: plugins
  #       mountPath: /fluent-bit/plugins
  #   command:
  #     - "/bin/sh"
  #     - "-c"
  #     - |
  #       curl -sS <download-url> -o /plugin.zip
  #       unzip /plugin.zip
  #       cp -av <plugin-zip-contents> /fluent-bit/plugins/
