# _helpers.tpl
{{/* vim: set filetype=mustache: */}}

{{/*
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).
*/}}
{{- define "graylog.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 "graylog.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 "graylog.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "graylog.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

{{/*
Create the name of the headless service
*/}}
{{- define "graylog.service.headless.name" }}
{{- printf "%s-%s" (include "graylog.fullname" .) .Values.graylog.service.headless.suffix | trimSuffix "-" -}}
{{- end -}}

{{/*
Craft url taking into account the TLS settings of the server
*/}}
{{- define "graylog.formatUrl" -}}
{{- $env := index . 0 }}
{{- $url := index . 1 }}
{{- if $env.Values.graylog.tls.enabled }}
{{- printf "https://%s" $url }}
{{- else }}
{{- printf "http://%s" $url }}
{{- end -}}
{{- end -}}

{{/*
Print external URI
*/}}
{{- define "graylog.url" -}}
{{- if .Values.graylog.externalUri }}
{{- include "graylog.formatUrl" (list . .Values.graylog.externalUri) }}
{{- else if .Values.graylog.ingress.enabled }}
{{- if .Values.graylog.ingress.tls }}
{{- range .Values.graylog.ingress.tls }}{{ range .hosts }}https://{{ . }}{{ end }}{{ end }}
{{- else }}
{{- range .Values.graylog.ingress.hosts }}http://{{ . }}{{ end }}
{{- end }}
{{- end }}
{{- end -}}

{{/*
Create a default fully qualified elasticsearch name or use the `graylog.elasticsearch.hosts` value if defined.
Or use chart dependencies with release name
*/}}
{{- define "graylog.elasticsearch.hosts" -}}
{{- if .Values.graylog.elasticsearch.uriSecretKey }}
    {{- if .Values.graylog.elasticsearch.uriSSL }}
        {{- printf "https://${GRAYLOG_ELASTICSEARCH_HOST}" -}}
    {{- else }}
        {{- printf "http://${GRAYLOG_ELASTICSEARCH_HOST}" -}}
    {{- end }}
{{- else if .Values.graylog.elasticsearch.hosts }}
    {{- .Values.graylog.elasticsearch.hosts -}}
{{- else }}
    {{- printf "http://%s-elasticsearch-client.%s.svc.cluster.local:9200" .Release.Name .Release.Namespace -}}
{{- end -}}
{{- end -}}

{{/*
Create a default fully qualified mongodb name or use the `graylog.mongodb.uri` value if defined.
Or use chart dependencies with release name
*/}}
{{- define "graylog.mongodb.uri" -}}
{{- if .Values.graylog.mongodb.uriSecretKey }}
    {{- printf "${GRAYLOG_MONGODB_URI}" -}}
{{- else if .Values.graylog.mongodb.uri }}
    {{- .Values.graylog.mongodb.uri -}}
{{- else }}
    {{- printf "mongodb://%s-mongodb-replicaset.%s.svc.cluster.local:27017/graylog?replicaSet=rs0" .Release.Name .Release.Namespace -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "graylog.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Standard metadata labels used by the chart.
*/}}
{{- define "graylog.metadataLabels" -}}
helm.sh/chart: {{ template "graylog.chart" . }}
{{ template "graylog.selectorLabels" . }}
app.kubernetes.io/version: "{{ .Chart.AppVersion }}"
{{- end -}}

{{/*
Selector labels used by the chart.
*/}}
{{- define "graylog.selectorLabels" -}}
app.kubernetes.io/name: {{ template "graylog.name" . }}
app.kubernetes.io/instance: "{{ .Release.Name }}"
{{- if .Values.helm2Compatibility }}
app.kubernetes.io/managed-by: "Tiller"
{{- else }}
app.kubernetes.io/managed-by: "{{ .Release.Service }}"
{{- end -}}
{{- end -}}
 # configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "graylog.fullname" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
data:
  log4j2.xml: |-
    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration packages="org.graylog2.log4j" shutdownHook="disable">
        <Appenders>
            <Console name="STDOUT" target="SYSTEM_OUT">
              {{- if .Values.graylog.logInJson }}
                <JsonLayout eventEOL="true" compact="true"/>
              {{- else }}
                <PatternLayout pattern="%d %-7level [%c{1}] - %m - %X%n"/>
              {{- end }}
            </Console>
            <RollingFile name="rolling-file" fileName="/usr/share/graylog/log/server.log" filePattern="/usr/share/graylog/log/server.log.%i.gz">
                <PatternLayout>
                    <Pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5p [%c{1}] %m%n</Pattern>
                </PatternLayout>
                <Policies>
                    <SizeBasedTriggeringPolicy size="50MB"/>
                </Policies>
                <DefaultRolloverStrategy max="10" fileIndex="min"/>
            </RollingFile>
            <!-- Internal Graylog log appender. Please do not disable. This makes internal log messages available via REST calls. -->
            <Memory name="graylog-internal-logs" bufferSize="500"/>
            <!-- Rotate audit logs daily -->
            <RollingFile name="AUDITLOG" fileName="/usr/share/graylog/log/audit.log" filePattern="/usr/share/graylog/log/audit-%d{yyyy-MM-dd}.log.gz">
                <PatternLayout>
                    <Pattern>%d [%c{1}] - %m - %X%n</Pattern>
                </PatternLayout>
                <Policies>
                    <TimeBasedTriggeringPolicy />
                </Policies>
            </RollingFile>
        </Appenders>
        <Loggers>
            <!-- Application Loggers -->
            <Logger name="org.graylog2" level="warn"/>
            <Logger name="com.github.joschi.jadconfig" level="warn"/>
            <!-- This emits a harmless warning for ActiveDirectory every time which we can't work around :( -->
            <Logger name="org.apache.directory.api.ldap.model.message.BindRequestImpl" level="error"/>
            <!-- Prevent DEBUG message about Lucene Expressions not found. -->
            <Logger name="org.elasticsearch.script" level="warn"/>
            <!-- Disable messages from the version check -->
            <Logger name="org.graylog2.periodical.VersionCheckThread" level="off"/>
            <!-- Suppress crazy byte array dump of Drools -->
            <Logger name="org.drools.compiler.kie.builder.impl.KieRepositoryImpl" level="warn"/>
            <!-- Silence chatty natty -->
            <Logger name="com.joestelmach.natty.Parser" level="warn"/>
            <!-- Silence Kafka log chatter -->
            <Logger name="kafka.log.Log" level="warn"/>
            <Logger name="kafka.log.OffsetIndex" level="warn"/>
            <!-- Silence useless session validation messages -->
            <Logger name="org.apache.shiro.session.mgt.AbstractValidatingSessionManager" level="warn"/>
            <Root level="warn">
                <AppenderRef ref="STDOUT"/>
            </Root>
            <!-- Security Loggers -->
          <Logger name="org.graylog2.security.realm.PasswordAuthenticator" level="trace" additivity="false">
                <AppenderRef ref="AUDITLOG"/>
            </Logger>
            <Logger name="org.graylog2.security.realm.AccessTokenAuthenticator" level="trace" additivity="false">
                <AppenderRef ref="AUDITLOG"/>
            </Logger>
            <Logger name="org.graylog2.security.realm.RootAccountRealm" level="trace" additivity="false">
                <AppenderRef ref="AUDITLOG"/>
            </Logger>
            <Logger name="org.graylog2.shared.security.ShiroAuthorizationFilter" level="trace" additivity="false">
                <AppenderRef ref="AUDITLOG"/>
            </Logger>
        </Loggers>
    </Configuration>
  graylog.conf: |-
    node_id_file = /usr/share/graylog/data/journal/node-id
    root_username = {{ .Values.graylog.rootUsername }}
    root_email = {{ .Values.graylog.rootEmail }}
    root_timezone = {{ default "UTC" .Values.graylog.rootTimezone }}
    plugin_dir = /usr/share/graylog/plugin
  {{- $externalUri := include "graylog.url" . }}
  {{- if contains ":2" .Values.graylog.image.repository }}
    rest_listen_uri = http://0.0.0.0:9000/api/
    web_listen_uri = http://0.0.0.0:9000/
  {{- if $externalUri }}
    web_endpoint_uri =  {{ $externalUri }}/api
  {{- end }}
  {{- else }}
    http_bind_address = 0.0.0.0:9000
    {{- if .Values.graylog.tls.enabled }}
    http_enable_tls = true
    http_tls_cert_file = {{ .Values.graylog.tls.certFile }}
    http_tls_key_file = {{ .Values.graylog.tls.keyFile }}
    {{- end }}
    {{- if $externalUri }}
    http_external_uri = {{ $externalUri }}/
    {{- end }}
  {{- end }}
    elasticsearch_hosts = {{ template "graylog.elasticsearch.hosts" . }}
    allow_leading_wildcard_searches = false
    allow_highlighting = false
    output_batch_size = 500
    output_flush_interval = 1
    output_fault_count_threshold = 5
    output_fault_penalty_seconds = 30
    processbuffer_processors = 5
    outputbuffer_processors = 3
    processor_wait_strategy = blocking
    ring_size = 65536
    inputbuffer_ring_size = 65536
    inputbuffer_processors = 2
    inputbuffer_wait_strategy = blocking
    message_journal_enabled = true
    # Do not change `message_journal_dir` location
    message_journal_dir = /usr/share/graylog/data/journal
    lb_recognition_period_seconds = 3
    # Use a replica set instead of a single host
    mongodb_uri = {{ template "graylog.mongodb.uri" . }}
    mongodb_max_connections = {{ default 1000 .Values.graylog.mongodb.maxConnections }}
    mongodb_threads_allowed_to_block_multiplier = 5
    # Email transport
    transport_email_enabled = {{ default false .Values.graylog.transportEmail.enabled }}
    transport_email_hostname = {{ default .Values.graylog.transportEmail.hostname }}
    transport_email_port = {{ default .Values.graylog.transportEmail.port }}
    transport_email_use_auth = {{ default .Values.graylog.transportEmail.useAuth }}
    transport_email_use_tls = {{ default .Values.graylog.transportEmail.useTls }}
    transport_email_use_ssl = {{ default false .Values.graylog.transportEmail.useSsl }}
    transport_email_auth_username = {{ default .Values.graylog.transportEmail.authUsername }}
    transport_email_auth_password = {{ default .Values.graylog.transportEmail.authPassword }}
    transport_email_subject_prefix = {{ default .Values.graylog.transportEmail.subjectPrefix }}
    transport_email_from_email = {{ default .Values.graylog.transportEmail.fromEmail }}
  {{- if $externalUri }}
    transport_email_web_interface_url = {{ $externalUri }}
  {{- end }}
    content_packs_dir = /usr/share/graylog/data/contentpacks
    content_packs_auto_load = grok-patterns.json
    proxied_requests_thread_pool_size = 32
  {{- if .Values.graylog.config }}
{{ .Values.graylog.config | indent 4 }}
  {{- end }}
  entrypoint.sh: |-
    #!/usr/bin/env bash

    export GRAYLOG_HTTP_PUBLISH_URI="{{ template "graylog.formatUrl" (list . "$(hostname -f):9000/") }}"

    GRAYLOG_HOME=/usr/share/graylog
    # Looking for Master IP
    MASTER_IP=`/k8s/kubectl --namespace {{ .Release.Namespace }} get pod -o jsonpath='{range .items[*]}{.metadata.name} {.status.podIP}{"\n"}{end}' -l graylog-role=master --field-selector=status.phase=Running|awk '{print $2}'`
    SELF_IP=`/k8s/kubectl --namespace {{ .Release.Namespace }} get pod $HOSTNAME -o jsonpath='{.status.podIP}'`
    echo "Current master is $MASTER_IP"
    echo "Self IP is $SELF_IP"
    if [[ -z "$MASTER_IP" ]]; then
      echo "Launching $HOSTNAME as master"
      export GRAYLOG_IS_MASTER="true"
      /k8s/kubectl --namespace {{ .Release.Namespace }} label --overwrite pod $HOSTNAME graylog-role="master"
    else
      # When container was recreated or restart, MASTER_IP == SELF_IP, running as master and no need to change label graylog-role="master"
      if [ "$SELF_IP" == "$MASTER_IP" ];then
        export GRAYLOG_IS_MASTER="true"
      else
        # MASTER_IP != SELF_IP, running as coordinating
        echo "Launching $HOSTNAME as coordinating"
        export GRAYLOG_IS_MASTER="false"
        /k8s/kubectl --namespace {{ .Release.Namespace }} label --overwrite pod $HOSTNAME graylog-role="coordinating"
      fi
    fi
    # Download plugins
  {{- if .Values.graylog.plugins }}
    echo "Downloading Graylog Plugins..."
  {{- range .Values.graylog.plugins }}
    echo "Downloading {{ .url }} ..."
    curl -s --location --retry 3 -o ${GRAYLOG_HOME}/plugin/{{ .name }} "{{ .url }}"
  {{- end }}
  {{- end }}
  {{- if .Values.graylog.metrics.enabled }}
    echo "Downloading https://github.com/graylog-labs/graylog-plugin-metrics-reporter/releases/download/3.0.0/metrics-reporter-prometheus-3.0.0.jar ..."
    curl -s --location --retry 3 -o ${GRAYLOG_HOME}/plugin/metrics-reporter-prometheus-3.0.0.jar "https://github.com/graylog-labs/graylog-plugin-metrics-reporter/releases/download/3.0.0/metrics-reporter-prometheus-3.0.0.jar"
  {{- end }}
  {{- if .Values.graylog.geoip.enabled }}
    echo "Downloading Maxmind GeoLite2 ..."
    curl -s --location --retry 3 -o /tmp/GeoLite2-City.tar.gz "{{ .Values.graylog.geoip.mmdbUri }}"
    curlreturn=$?
    if [[ $curlreturn -eq 0 ]]; then
      mkdir -p ${GRAYLOG_HOME}/geoip && cd ${GRAYLOG_HOME}/geoip && tar xvzf /tmp/GeoLite2-City.tar.gz --wildcards "*.mmdb" --strip-components=1 -C ${GRAYLOG_HOME}/geoip && chown -R graylog:graylog ${GRAYLOG_HOME}/geoip
    fi
  {{- end }}
    # Start Graylog
    echo "Starting graylog"
    # Original docker-entrypoint.sh in Graylog Docker will error while executing since you can't chown readonly files in `config`
    # exec /docker-entrypoint.sh graylog
  {{- if or (.Values.graylog.elasticsearch.uriSecretKey) (.Values.graylog.mongodb.uriSecretKey) }}
    # Interpolate
    sed 's/"/\\\"/g;s/.*/echo "&"/e' ${GRAYLOG_HOME}/config/graylog.conf > ${GRAYLOG_HOME}/graylog.conf.subst
  {{- end }}
    echo "Graylog Home ${GRAYLOG_HOME}"
    echo "JVM Options ${GRAYLOG_SERVER_JAVA_OPTS}"
    "${JAVA_HOME}/bin/java" \
      ${GRAYLOG_SERVER_JAVA_OPTS} \
      -jar \
      -Dlog4j.configurationFile=${GRAYLOG_HOME}/config/log4j2.xml \
      -Djava.library.path=${GRAYLOG_HOME}/lib/sigar/ \
      -Dgraylog2.installation_source=docker \
      ${GRAYLOG_HOME}/graylog.jar \
      server \
    {{- if or (.Values.graylog.elasticsearch.uriSecretKey) (.Values.graylog.mongodb.uriSecretKey) }}
      -f ${GRAYLOG_HOME}/graylog.conf.subst
    {{- else }}
      -f ${GRAYLOG_HOME}/config/graylog.conf
    {{- end }}
 # files-configmap.yaml
{{- if .Values.graylog.serverFiles -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "graylog.fullname" . }}-files
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
data:
{{- range $key, $value := .Values.graylog.serverFiles }}
  {{ $key }}: |
{{ $value | default "{}" | indent 4 }}
{{- end -}}
{{- end -}}
 # headless-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "graylog.service.headless.name" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
spec:
  ports:
    - name: graylog
      port: 9000
  type: ClusterIP
  clusterIP: None
  publishNotReadyAddresses: true
  selector:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
 # ingress.yaml
{{- if .Values.graylog.ingress.enabled -}}
{{- $extraPaths := .Values.graylog.ingress.extraPaths -}}
{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
  annotations:
  {{- range $key, $value := .Values.graylog.ingress.annotations }}
    {{ $key }}: {{ $value | quote }}
  {{- end }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
    app.kubernetes.io/component: "web"
  name: {{ template "graylog.fullname" . }}-web
spec:
  rules:
  {{- range .Values.graylog.ingress.hosts }}
    - host: {{ . }}
      http:
        paths:
          {{ if $extraPaths }}
{{ toYaml $extraPaths | indent 10 }}
          {{- end }}
          - backend:
              serviceName: {{ template "graylog.fullname" $ }}-web
              servicePort: graylog
            {{- if $.Values.graylog.ingress.path }}
            path: {{ $.Values.graylog.ingress.path }}
            {{- end -}}
  {{- end -}}
  {{- if .Values.graylog.ingress.tls }}
  tls:
{{ toYaml .Values.graylog.ingress.tls | indent 4 }}
  {{- end -}}
{{- end -}}
 # job.yaml
{{ if .Values.graylog.provisioner.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "graylog.fullname" . }}-provisioner-job
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
{{- with .Values.graylog.provisioner.annotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
spec:
  template:
    metadata:
      labels:
{{ include "graylog.metadataLabels" . | indent 8 }}
    spec:
      {{ if .Values.graylog.provisioner.useGraylogServiceAccount }}
      serviceAccountName: {{ template "graylog.serviceAccountName" . }}
      {{ end }}
      containers:
      - name: {{ template "graylog.fullname" . }}-provisioner-job
        image: "alpine"
        imagePullPolicy: "IfNotPresent"
        command:
          - /bin/sh
          - -c
          - |
            apk update && apk add --no-cache curl bash && bash /configmap/script.sh
        env:
          - name: GRAYLOG_PASSWORD_SECRET
            valueFrom:
              secretKeyRef:
                name: {{ .Values.graylog.existingRootSecret | default (include "graylog.fullname" .) }}

                key: graylog-password-secret
        volumeMounts:
          - name: configmap
            mountPath: /configmap
      volumes:
        - name: configmap
          configMap:
            name: {{ template "graylog.fullname" . }}-provisioner-job
            items:
              - key: script.sh
                path: script.sh
                mode: 365
      restartPolicy: OnFailure
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "graylog.fullname" . }}-provisioner-job
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
data:
  script.sh: |
{{ .Values.graylog.provisioner.script | indent 4 }}
{{ end }}
 # master-service.yaml
{{- if .Values.graylog.service.master.enabled }}
apiVersion: v1
kind: Service
metadata:
{{- if .Values.graylog.service.master.annotations }}
  annotations:
{{ toYaml .Values.graylog.service.master.annotations | indent 4 }}
{{- end }}
  name: {{ template "graylog.fullname" . }}-master
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
    graylog-role: "master"
spec:
  ports:
    - name: graylog
{{- if .Values.graylog.service.master.port }}
      port: {{ default 9000 .Values.graylog.service.master.port }}
{{- else }}
      port: {{ default 9000 .Values.graylog.service.port }}
{{- end }}
      protocol: TCP
      targetPort: 9000
{{- if eq "NodePort" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.nodePort }}
      nodePort:  {{ .Values.graylog.service.nodePort }}
  {{- end }}
{{- end }}
{{- if .Values.graylog.service.externalIPs }}
  externalIPs:
{{ toYaml .Values.graylog.service.externalIPs | indent 4 }}
{{- end }}
{{- if eq "ClusterIP" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.clusterIP }}
  clusterIP:  {{ .Values.graylog.service.clusterIP }}
  {{- end }}
{{- end }}
  selector:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
    graylog-role: "master"
  type: "{{ .Values.graylog.service.type }}"
{{- if eq "LoadBalancer" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.graylog.service.loadBalancerIP }}
  {{- end -}}
  {{- if .Values.graylog.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
  {{- range .Values.graylog.service.loadBalancerSourceRanges }}
  - {{ . }}
  {{- end }}
  {{- end -}}
{{- end -}}
{{- end -}}
 # role.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: {{ template "graylog.fullname" . }}
  labels:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    helm.sh/chart: {{ template "graylog.chart" . }}
    app.kubernetes.io/managed-by: "{{ .Release.Service }}"
    app.kubernetes.io/instance: "{{ .Release.Name }}"
    app.kubernetes.io/version: "{{ .Chart.AppVersion }}"
rules:
- apiGroups:
    - ""
  resources:
{{ toYaml .Values.rbac.resources | indent 4 }}
  verbs:
    - get
    - list
    - patch
{{- end -}}
 # rolebinding.yaml
{{- if .Values.rbac.create -}}
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: {{ template "graylog.fullname" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ template "graylog.fullname" . }}
subjects:
- kind: ServiceAccount
  name: {{ template "graylog.serviceAccountName" . }}
{{- end -}}
 # secret.yaml
{{- if not .Values.graylog.existingRootSecret }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "graylog.fullname" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
type: Opaque
data:
  graylog-root-username: {{ .Values.graylog.rootUsername | b64enc | quote }}
  {{- if .Values.graylog.rootPassword }}
  graylog-password-secret: {{ .Values.graylog.rootPassword | b64enc | quote }}
  graylog-password-sha2: {{ .Values.graylog.rootPassword | sha256sum | b64enc | quote }}
  {{- else }}
  {{- $randpass := randAlphaNum 16 }}
  graylog-password-secret: {{ $randpass | b64enc | quote }}
  graylog-password-sha2: {{ $randpass | sha256sum | b64enc | quote }}
  {{- end }}
{{- end }}
 # serviceaccount.yaml
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "graylog.serviceAccountName" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
{{- end -}}
 # statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ template "graylog.fullname" . }}
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
spec:
  serviceName: {{ template "graylog.service.headless.name" . }}
  replicas: {{ .Values.graylog.replicas }}
  selector:
    matchLabels:
{{ include "graylog.selectorLabels" . | indent 6 }}
  updateStrategy:
    type: {{ .Values.graylog.updateStrategy }}
  template:
    metadata:
      labels:
{{ include "graylog.metadataLabels" . | indent 8 }}
      annotations:
      {{- if .Values.graylog.podAnnotations }}
      {{- range $key, $value := .Values.graylog.podAnnotations }}
        {{ $key }}: {{ $value | quote }}
      {{- end }}
      {{- end }}
      {{- if .Values.graylog.metrics.enabled }}
        prometheus.io/scrape: "true"
        prometheus.io/port: "9000"
      {{- end }}
    spec:
      serviceAccountName: {{ template "graylog.serviceAccountName" . }}
{{- if .Values.graylog.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.graylog.nodeSelector | indent 8 }}
{{- end }}
{{- if .Values.graylog.affinity }}
      affinity:
{{ toYaml .Values.graylog.affinity | indent 8 }}

{{- end }}
{{- if .Values.graylog.tolerations }}
      tolerations:
{{ toYaml .Values.graylog.tolerations | indent 8 }}
{{- end }}
      {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.imagePullSecrets | indent 8 }}
      {{- end }}
      initContainers:
        - name: "setup"
          image: "alpine"
          imagePullPolicy: "IfNotPresent"
          # Graylog journal will recursive in every subdirectories. Any invalid format directories will cause errors
          command:
            - /bin/sh
            - -c
            - |
              rm -rf /usr/share/graylog/data/journal/lost+found
            {{- if .Values.graylog.journal.deleteBeforeStart }}
              rm -rf /usr/share/graylog/data/journal/graylog2-committed-read-offset
              rm -rf /usr/share/graylog/data/journal/messagejournal-0
              rm -rf /usr/share/graylog/data/journal/recovery-point-offset-checkpoint
            {{- end }}
              wget https://storage.googleapis.com/kubernetes-release/release/v1.16.3/bin/linux/amd64/kubectl -O /k8s/kubectl
              chmod +x /k8s/kubectl

              GRAYLOG_HOME=/usr/share/graylog
              chown -R 1100:1100 ${GRAYLOG_HOME}/data/
          env:
            {{- range $key, $value := .Values.graylog.init.env }}
            - name: {{ $key }}
              value: {{ $value | quote }}
            {{- end }}
          volumeMounts:
            - name: journal
              mountPath: /usr/share/graylog/data/journal
            - mountPath: /k8s
              name: kubectl
{{- if .Values.graylog.init.resources }}
          resources:
{{ toYaml .Values.graylog.init.resources | indent 12 }}
{{- end }}
{{- if .Values.graylog.extraInitContainers }}
{{ toYaml .Values.graylog.extraInitContainers | indent 8 }}
{{- end }}
      containers:
        - name: graylog-server
          image: "{{ .Values.graylog.image.repository }}"
          imagePullPolicy: {{ .Values.graylog.image.pullPolicy | quote }}
          command:
            - /entrypoint.sh
          env:
            - name: GRAYLOG_SERVER_JAVA_OPTS
              {{- $javaOpts := "-Djava.net.preferIPv4Stack=true -XX:NewRatio=1 -server -XX:+ResizeTLAB -XX:+UseConcMarkSweepGC -XX:+CMSConcurrentMTEnabled -XX:+CMSClassUnloadingEnabled -XX:+UseParNewGC -XX:-OmitStackTraceInFastThrow" }}
              {{- if .Values.graylog.heapSize }}
              value: "{{ $javaOpts }} {{ printf "-Xms%s -Xmx%s" .Values.graylog.heapSize .Values.graylog.heapSize}} {{ .Values.graylog.additionalJavaOpts }}"
              {{- else }}
              value: "{{ $javaOpts }} -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap {{ .Values.graylog.additionalJavaOpts }}"
              {{- end }}
            - name: GRAYLOG_PASSWORD_SECRET
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.graylog.existingRootSecret | default (include "graylog.fullname" .) }}
                  key: graylog-password-secret
            - name: GRAYLOG_ROOT_PASSWORD_SHA2
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.graylog.existingRootSecret | default (include "graylog.fullname" .) }}
                  key: graylog-password-sha2
            {{- if .Values.graylog.elasticsearch.uriSecretKey }}
            - name: GRAYLOG_ELASTICSEARCH_HOST
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.graylog.elasticsearch.uriSecretName | default (printf "%s-es" (include "graylog.fullname" .)) }}
                  key: {{ .Values.graylog.elasticsearch.uriSecretKey }}
            {{- end }}
            {{- if .Values.graylog.mongodb.uriSecretKey }}
            - name: GRAYLOG_MONGODB_URI
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.graylog.mongodb.uriSecretName | default (printf "%s-mongodb" (include "graylog.fullname" .)) }}
                  key: {{ .Values.graylog.mongodb.uriSecretKey }}
            {{- end }}
            {{- range $key, $value := .Values.graylog.env }}
            - name: {{ $key }}
              value: {{ $value | quote }}
            {{- end }}
            {{- if .Values.graylog.envRaw }}
            {{- with .Values.graylog.envRaw }}
                {{- toYaml . | nindent 12 }}
            {{- end }}
            {{- end }}
          securityContext:
            privileged: {{ .Values.graylog.privileged }}
          ports:
            - containerPort: 9000
              name: graylog
          {{- range .Values.graylog.service.ports }}
            - containerPort: {{ .port }}
              name: {{ .name}}
              protocol: {{ .protocol }}
          {{- end }}
          {{- with .Values.graylog.input }}
          {{- if .udp }}
          {{- range .udp.ports }}
            - containerPort: {{ .port }}
              name: {{ .name }}
              protocol: UDP
          {{- end }}
          {{- end }}
          {{- if .tcp }}
          {{- range .tcp.ports }}
            - containerPort: {{ .port }}
              name: {{ .name }}
              protocol: TCP
          {{- end }}
          {{- end }}
          {{- end }}
          resources:
{{ toYaml .Values.graylog.resources | indent 12 }}
          livenessProbe:
            httpGet:
              path: /api/system/lbstatus
              port: 9000
            {{- if .Values.graylog.tls.enabled }}
              scheme: HTTPS
            {{- end }}
            initialDelaySeconds: 120
            periodSeconds: 30
            failureThreshold: 3
            successThreshold: 1
            timeoutSeconds: 5
          readinessProbe:
            httpGet:
              path: /api/system/lbstatus
              port: 9000
            {{- if .Values.graylog.tls.enabled }}
              scheme: HTTPS
            {{- end }}
            initialDelaySeconds: 60
            periodSeconds: 10
            failureThreshold: 3
            successThreshold: 1
            timeoutSeconds: 5
          volumeMounts:
            - name: journal
              mountPath: /usr/share/graylog/data/journal
            - name: config
              mountPath: /usr/share/graylog/config
            - name: entrypoint
              mountPath: /entrypoint.sh
              subPath: entrypoint.sh
          {{- if .Values.graylog.serverFiles }}
            - name: files
              mountPath: /etc/graylog/server
          {{- end }}
            - name: kubectl
              mountPath: /k8s
          {{- if .Values.graylog.extraVolumeMounts }}
          {{ toYaml .Values.graylog.extraVolumeMounts | nindent 12 }}
          {{- end }}
          lifecycle:
            preStop:
              exec:
                command:
                  - bash
                  - -ec
                  - |
                    curl {{ if .Values.graylog.tls.enabled }}-k{{ end }} -XPOST -sS \
                      -u "{{ .Values.graylog.rootUsername }}:${GRAYLOG_PASSWORD_SECRET}" \
                      -H "X-Requested-By: {{ template "graylog.fullname" . }}" \
                      {{ template "graylog.formatUrl" (list . "localhost:9000/api/system/shutdown/shutdown") }}
      {{- if .Values.graylog.sidecarContainers }}
        {{ toYaml .Values.graylog.sidecarContainers | nindent 8 }}
      {{- end }}
      terminationGracePeriodSeconds: {{ default 30 .Values.graylog.terminationGracePeriodSeconds }}
      volumes:
        - name: config
          configMap:
            name: {{ template "graylog.fullname" . }}
            items:
              - key: graylog.conf
                path: graylog.conf
                mode: 292 # 0444
              - key: log4j2.xml
                path: log4j2.xml
                mode: 292 # 0444
        - name: entrypoint
          configMap:
            name: {{ template "graylog.fullname" . }}
            items:
              - key: entrypoint.sh
                path: entrypoint.sh
                mode: 365 # 0555
        {{- if .Values.graylog.serverFiles }}
        - name: files
          configMap:
            name: {{ template "graylog.fullname" . }}-files
        {{- end }}
        - name: kubectl
          emptyDir: {}
{{- if .Values.graylog.extraVolumes }}
{{ toYaml .Values.graylog.extraVolumes | indent 8 }}
{{- end }}
{{- if not .Values.graylog.persistence.enabled }}
        - name: journal
          emptyDir: {}
{{- else }}
  volumeClaimTemplates:
    - metadata:
        name: journal
      spec:
        accessModes:
          - {{ .Values.graylog.persistence.accessMode | quote }}
      {{- if .Values.graylog.persistence.storageClass }}
      {{- if (eq "-" .Values.graylog.persistence.storageClass) }}
        storageClassName: ""
      {{- else }}
        storageClassName: "{{ .Values.graylog.persistence.storageClass }}"
      {{- end }}
      {{- end }}
        resources:
          requests:
            storage: "{{ .Values.graylog.persistence.size }}"
{{- end }}
 # tcp-service.yaml
{{- if .Values.graylog.input.tcp }}
apiVersion: v1
kind: Service
metadata:
{{- if .Values.graylog.input.tcp.service.annotations }}
  annotations:
{{ toYaml .Values.graylog.input.tcp.service.annotations | indent 4 }}
{{- end }}
  name: {{ template "graylog.fullname" . }}-tcp
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
    app.kubernetes.io/component: "TCP"
spec:
  ports:
  {{- range .Values.graylog.input.tcp.ports }}
    - name: {{ .name }}
      port: {{ .port }}
      protocol: TCP
      targetPort: {{ .port }}
    {{- if eq "NodePort" $.Values.graylog.input.tcp.service.type }}
      {{- if .nodePort }}
      nodePort:  {{ .nodePort }}
      {{- end }}
    {{- end }}
  {{- end }}
{{- if .Values.graylog.input.tcp.service.externalIPs }}
  externalIPs:
{{ toYaml .Values.graylog.input.tcp.service.externalIPs | indent 4 }}
{{- end }}
{{- if eq "ClusterIP" .Values.graylog.input.tcp.service.type }}
  {{- if .Values.graylog.input.tcp.service.clusterIP }}
  clusterIP:  {{ .Values.graylog.input.tcp.service.clusterIP }}
  {{- end }}
{{- end }}  
  selector:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
  type: "{{ .Values.graylog.input.tcp.service.type }}"
{{- if eq "LoadBalancer" .Values.graylog.input.tcp.service.type }}
  externalTrafficPolicy: {{ .Values.graylog.input.tcp.service.externalTrafficPolicy | default "Cluster" }}
  {{- if .Values.graylog.input.tcp.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.graylog.input.tcp.service.loadBalancerIP }}
  {{- end -}}
  {{- if .Values.graylog.input.tcp.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
  {{- range .Values.graylog.input.tcp.service.loadBalancerSourceRanges }}
  - {{ . }}
  {{- end }}
  {{- end -}}
{{- end -}}
{{- end }}
 # udp-service.yaml
{{- if .Values.graylog.input.udp }}
apiVersion: v1
kind: Service
metadata:
{{- if .Values.graylog.input.udp.service.annotations }}
  annotations:
{{ toYaml .Values.graylog.input.udp.service.annotations | indent 4 }}
{{- end }}
  name: {{ template "graylog.fullname" . }}-udp
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
    app.kubernetes.io/component: "UDP"
spec:
  ports:
  {{- range .Values.graylog.input.udp.ports }}
    - name: {{ .name }}
      port: {{ .port }}
      protocol: UDP
      targetPort: {{ .port }}
    {{- if eq "NodePort" $.Values.graylog.input.udp.service.type }}
      {{- if .nodePort }}
      nodePort:  {{ .nodePort }}
      {{- end }}
    {{- end }}
  {{- end }}
{{- if .Values.graylog.input.udp.service.externalIPs }}
  externalIPs:
{{ toYaml .Values.graylog.input.udp.service.externalIPs | indent 4 }}
{{- end }}
{{- if eq "ClusterIP" .Values.graylog.input.udp.service.type }}
  {{- if .Values.graylog.input.udp.service.clusterIP }}
  clusterIP:  {{ .Values.graylog.input.udp.service.clusterIP }}
  {{- end }}
{{- end }}  
  selector:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
  type: "{{ .Values.graylog.input.udp.service.type }}"
{{- if eq "LoadBalancer" .Values.graylog.input.udp.service.type }}
  externalTrafficPolicy: {{ .Values.graylog.input.udp.service.externalTrafficPolicy | default "Cluster" }}
  {{- if .Values.graylog.input.udp.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.graylog.input.udp.service.loadBalancerIP }}
  {{- end -}}
  {{- if .Values.graylog.input.udp.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
  {{- range .Values.graylog.input.udp.service.loadBalancerSourceRanges }}
  - {{ . }}
  {{- end }}
  {{- end -}}
{{- end -}}
{{- end }}
 # web-service.yaml
apiVersion: v1
kind: Service
metadata:
{{- if .Values.graylog.service.annotations }}
  annotations:
{{ toYaml .Values.graylog.service.annotations | indent 4 }}
{{- end }}
  name: {{ template "graylog.fullname" . }}-web
  labels:
{{ include "graylog.metadataLabels" . | indent 4 }}
    app.kubernetes.io/component: "web"
spec:
  ports:
    - name: graylog
      port: {{ default 9000 .Values.graylog.service.port }}
      protocol: TCP
      targetPort: 9000
{{- if eq "NodePort" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.nodePort }}
      nodePort:  {{ .Values.graylog.service.nodePort }}
  {{- end }}
{{- end }}
{{- range .Values.graylog.service.ports }}
    - name: {{ .name }}
      port: {{ .port }}
      protocol: {{ .protocol }}
      targetPort: {{ .port }}
{{- end }}
{{- if .Values.graylog.service.externalIPs }}
  externalIPs:
{{ toYaml .Values.graylog.service.externalIPs | indent 4 }}
{{- end }}
{{- if eq "ClusterIP" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.clusterIP }}
  clusterIP:  {{ .Values.graylog.service.clusterIP }}
  {{- end }}
{{- end }}
  selector:
    app.kubernetes.io/name: {{ template "graylog.name" . }}
    app.kubernetes.io/instance: "{{ .Release.Name }}"
  type: "{{ .Values.graylog.service.type }}"
{{- if eq "LoadBalancer" .Values.graylog.service.type }}
  {{- if .Values.graylog.service.loadBalancerIP }}
  loadBalancerIP: {{ .Values.graylog.service.loadBalancerIP }}
  {{- end -}}
  {{- if .Values.graylog.service.loadBalancerSourceRanges }}
  loadBalancerSourceRanges:
  {{- range .Values.graylog.service.loadBalancerSourceRanges }}
  - {{ . }}
  {{- end }}
  {{- end -}}
{{- end -}}

# Default values for Graylog.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

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

  resources:
    - pods
    - secrets

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:

tags:
  # If true, this chart will install Elasticsearch from requirement dependencies
  install-elasticsearch: true
  # If true, this chart will install MongoDB replicaset from requirement dependencies
  install-mongodb: true

## Enable only if your current release was migrated from helm2 (using 2to3 plugin).
##
## Because Kubernetes considers some StatefulSets fields/labels immutable,
## this flag preserves the values rendered by helm2. This allows helm3
## to upgrade the current release without a complete purge/reinstall.
##
## Further details: https://github.com/helm/charts/issues/20306
##
# helm2Compatibility: true

graylog:
  ## Graylog image version
  ## Ref: http://kubernetes.io/docs/user-guide/images/#pre-pulling-images
  ##
  ## Important note: Official Graylog Docker image may replace the existing Docker image tags and cause some corrupt when starting the pod.
  ## Make sure you strict with the `x` version of Graylog where `x` is ${version}-${x}
  ##
  image:
    repository: "graylog/graylog:3.1"
    pullPolicy: "IfNotPresent"

  ## Number of Graylog instance
  ##
  replicas: 2

  ## Additional environment variables to be added to Graylog pods
  ##
  env: {}

  ## Additional environment variables in raw yaml format
  ## - name: POD_IP
  ##   valueFrom:
  ##     fieldRef:
  ##       fieldPath: status.podIP
  ## - name: SERVICE_8000_NAME
  ##   value: servicename
  envRaw: {}

  ## Run as privileged container
  ##
  privileged: false

  ## Pod affinity
  ## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
  ##
  affinity: {}

  ## Node tolerations for node-exporter 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 node-exporter pod assignment
  ## Ref: https://kubernetes.io/docs/user-guide/node-selection/
  ##
  nodeSelector: {}

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

  persistence:
    ## If true, Graylog will create/use a Persistent Volume Claim
    ## If false, use emptyDir
    ##
    enabled: true
    ## Graylog data Persistent Volume access modes
    ## Must match those of existing PV or dynamic provisioner
    ## Ref: http://kubernetes.io/docs/user-guide/persistent-volumes/
    ##
    accessMode: ReadWriteOnce
    ## Graylog data Persistent Volume size
    ##
    size: "20Gi"
    ## Graylog 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: "ssd"

  ## Additional plugins you need to install on Graylog.
  ##
  plugins: []
    # - name: graylog-plugin-slack-notification-3.1.0.jar
    #   url: https://github.com/omise/graylog-plugin-slack-notification/releases/download/v3.1.0/graylog-plugin-slack-notification-3.1.0.jar
    # - name: graylog-plugin-function-check-diff-1.0.0.jar
    #   url: https://github.com/omise/graylog-plugin-function-check-diff/releases/download/1.0.0/graylog-plugin-function-check-diff-1.0.0.jar
    # - name: graylog-plugin-auth-sso-3.0.0.jar
    #   url: https://github.com/Graylog2/graylog-plugin-auth-sso/releases/download/3.0.0/graylog-plugin-auth-sso-3.0.0.jar

  ## Sidecar containers
  ##
  sidecarContainers: []

  ## Additional init containers
  ##
  extraInitContainers: []

  ## Additional volume mounts
  ##
  extraVolumeMounts: []

  ## Additional volumes
  ##
  extraVolumes: []

  ## A service for Graylog web interface
  ##
  service:
    type: ClusterIP
    port: 9000
    ## Add additional ports for the service/statefulset to expose
    ##
    ports: []

    headless:
      ## Add suffix to headless service name
      ##
      suffix: ""

    master:
      ## Enable Graylog master service
      ##
      enabled: true
      ## Graylog master service Ingress annotations
      ##
      annotations: {}
      ## Graylog master service port.
      ##
      port: 9000

  ## Additional input ports for receiving logs from servers
  ## Note: Name must be in IANA_SVC_NAME (at most 15 characters, matching regex [a-z0-9]([a-z0-9-]*[a-z0-9])* and it must contains at least one letter [a-z], hyphens cannot be adjacent to other hyphens)
  ## Note: Array must be sorted by port order
  ##
  input: {}
    # tcp:
    #   service:
    #     type: LoadBalancer
    #     loadBalancerIP:
    #   ports:
    #     - name: gelf
    #       port: 12222
    # udp:
    #   service:
    #     type: ClusterIP
    #   ports:
    #     - name: syslog
    #       port: 12222

  tls:
    ## If true, Graylog server will run with TLS enabled
    ##
    enabled: false
    ## TLS certificate key file
    ##
    keyFile: /etc/graylog/server/server.key
    ## TLS certificate file
    ##
    certFile: /etc/graylog/server/server.cert

  ## External URL to access Graylog at
  ##
  externalUri: ""

  ingress:
    ## If true, Graylog server Ingress will be created
    ##
    enabled: false
    ## Graylog server Ingress annotations
    ##
    annotations: {}
    ## Graylog server Ingress hostnames with optional path
    ## Must be provided if Ingress is enabled
    ## Note: Graylog does not support two URL. You can specify only single URL
    ##
    hosts: []
    #   - graylog.yourdomain.com

    ## Extra paths to prepend to every host configuration. This is useful when working with annotation based services.
    extraPaths: []
    # - path: /*
    #   backend:
    #     serviceName: ssl-redirect
    #     servicePort: use-annotation

    ## Graylog server Ingress TLS configuration
    ## Secrets must be manually created in the namespace
    ##
    tls: []
    #   - secretName: graylog-server-tls
    #     hosts:
    #       - graylog.yourdomain.com


  ## Configure resource requests and limits
  ## ref: http://kubernetes.io/docs/user-guide/compute-resources/
  ##
  resources:
    limits:
      cpu: "1"
    requests:
      cpu: "500m"
      memory: "1024Mi"

  ## Set Graylog Java heapsize. If this value empty, chart will allocate heapsize using `-XX:+UseCGroupMemoryLimitForHeap`
  ## ref: https://blogs.oracle.com/java-platform-group/java-se-support-for-docker-cpu-and-memory-limits
  ##
  # heapSize: "1024g"

  ## RollingUpdate update strategy
  ## ref: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#update-strategies
  ##
  updateStrategy: RollingUpdate
  ## Graylog server pod termination grace period
  ##
  terminationGracePeriodSeconds: 120

  metrics:
    ## If true, prometheus annotations will be attached
    ##
    enabled: false

  geoip:
    ## If true, Maxmind GeoLite2 will be installed to ${GRAYLOG_HOME}/geoip location
    ##
    enabled: false
    ## If true, mmdbUri points to the URI where to find the DB
    # https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-geolite2-databases/
    mmdbUri: ""

  ## Graylog root user name
  ##
  rootUsername: "admin"

  ## Graylog root password
  ## Defaults to a random 16-character alphanumeric string if not set
  ##
  # rootPassword: ""

  ## Graylog root email
  ##
  rootEmail: ""

  ## Graylog root timezone
  ##
  rootTimezone: "UTC"

  ## Grayog existing root secret
  ##
  existingRootSecret: ""

  elasticsearch:
    ## List of Elasticsearch hosts Graylog should connect to.
    ## Need to be specified as a comma-separated list of valid URIs for the http ports of your elasticsearch nodes.
    ## If one or more of your elasticsearch hosts require authentication, include the credentials in each node URI that
    ## requires authentication.
    ##
    # hosts: http://elasticsearch-client.graylog.svc.cluster.local:9200
    hosts: ""
    # Allow elasticsearch hosts to be fetched from a k8s secret
    # {{ graylog.fullname }}-es will be used as uriSecretName if left empty
    uriSecretName: ""
    uriSecretKey: ""
    uriSSL: false

  mongodb:
    ## MongoDB connection string
    ## See https://docs.mongodb.com/manual/reference/connection-string/ for details
    # uri: mongodb://user:pass@host1:27017,host2:27017,host3:27017/graylog?replicaSet=rs01
    uri: ""
    # Allow mongodb uri to be fetched from a k8s secret
    # {{ graylog.fullname }}-mongodb will be used as uriSecretName if left empty
    uriSecretName: ""
    uriSecretKey: ""

    ## Increase this value according to the maximum connections your MongoDB server can handle from a single client
    ## if you encounter MongoDB connection problems.
    ##
    maxConnections: 1000

  transportEmail:
    ## If true, enable Email transport.
    ## See http://docs.graylog.org/en/3.0/pages/configuration/server.conf.html#email for detail
    ##
    enabled: false
    hostname: ""
    port: 2587
    useAuth: true
    useTls: true
    useSsl: false
    authUsername: ""
    authPassword: ""
    subjectPrefix: "[graylog]"
    fromEmail: ""

  ## Additional graylog config which is defined on `graylog.conf`.
  ## You can find a complete list of graylog config from http://docs.graylog.org/en/3.0/pages/configuration/server.conf.html
  ## Graylog config is written in Java properites format. Make sure you write it correctly.
  ##
  # config: |
  #   elasticsearch_connect_timeout = 10s
  #   elasticsearch_socket_timeout = 60s
  #   elasticsearch_idle_timeout = -1s

  journal:
    ## Sometime Graylog journal continually grow up or corrupt and cause Graylog unable to start.
    ## You need to clean up all journal files in order to run the Graylog.
    ## Change `graylog.journal.deleteBeforeStart` to `true` to delete all journal files before start
    ## Note: All uncommitted logs will be permanently DELETED when this value is true
    ##
    deleteBeforeStart: false

  init:
    # Additional environment variables to be added to Graylog initContainer
    env: {}

    # Configure resource requests and limits for the Graylog StatefulSet initContainer
    resources: {}

  ## Additional server files will be deployed to /etc/graylog/server
  ## For example, you can put server certificates or authorized clients certificates here
  ##
  serverFiles: {}
    # server.key: |
    # server.cert: |

  ## Configure whether Graylog pods should log in JSON (one event per line)
  logInJson: false

  ## Specify a Bash script to run as Kubernetes Job (running on Alpine with curl and bash packages already installed).
  ## Useful for calling the API to pre-configure some aspect of Graylog, as in the example.
  ##
  provisioner:
    enabled: false
    annotations: {}
    useGraylogServiceAccount: false
    # script: |
    #  json='{
    #    "username_header": "X-Auth-Request-User",
    #    "fullname_header": "X-Auth-Request-User",
    #    "email_header": "X-Auth-Request-Email",
    #    "default_group": "Admin",
    #    "auto_create_user": true,
    #    "require_trusted_proxies": true,
    #    "trusted_proxies": "0.0.0.0/0",
    #    "default_email_domain": "mydomain.com",
    #    "sync_roles": false,
    #    "roles_header": "Roles"
    #  }'
    #  curl -v -u "admin:$GRAYLOG_PASSWORD_SECRET" -X PUT --header 'Content-Type: application/json' --header 'X-Requested-By: localhost' --data-binary "${json}" http://graylog-master:9000/api/plugins/org.graylog.plugins.auth.sso/config
## Specify image pull secrets used in the deployment
imagePullSecrets: []
## imagePullSecrets:
##   - name: some-registry
##   - name: another-registry
## Specify Elasticsearch version from requirement dependencies. Ignore this seection if you install Elasticsearch manually.
## Note: Graylog 2.4 requires Elasticsearch version <= 5.6
elasticsearch:
  image:
    repository: "docker.elastic.co/elasticsearch/elasticsearch-oss"
    tag: "6.5.4"
  cluster:
    xpackEnable: false
