apiVersion: v1
data:
  entrypoint.sh: |-
    #!/usr/bin/env bash

    GRAYLOG_HOME=/usr/share/graylog
    export GRAYLOG_PLUGIN_DIR=${GRAYLOG_HOME}/plugin
    # Graylog 4.0.2 images move plugin dir to `plugins-default`
    find ${GRAYLOG_HOME}/plugins-default/ -type f -exec cp {} ${GRAYLOG_PLUGIN_DIR} \;
    # Looking for Master IP
    retry=1
    for i in {0..2}
    do
      MASTER_IP=`/k8s/kubectl --namespace default 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 default get pod $HOSTNAME -o jsonpath='{.status.podIP}'`
      echo "Current master is $MASTER_IP"
      echo "Self IP is $SELF_IP"
      retry=$((retry+1))
      [[ ! -z "$MASTER_IP" ]] && break
      echo "[Try ${retry}/3] Waiting for master node..."
      sleep 2
    done
    if [[ -z "$MASTER_IP" ]]; then
      echo "Launching $HOSTNAME as master"
      export GRAYLOG_IS_MASTER="true"
      /k8s/kubectl --namespace default 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
        echo "Launching $HOSTNAME as master"
        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 default label --overwrite pod $HOSTNAME graylog-role="coordinating"
      fi
    fi
    # Download plugins
    # 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
    export GRAYLOG_ELASTICSEARCH_VERSION=7
    echo "Graylog Home ${GRAYLOG_HOME}"
    echo "Graylog Plugin Dir ${GRAYLOG_PLUGIN_DIR}"
    echo "Graylog Elasticsearch Version ${GRAYLOG_ELASTICSEARCH_VERSION}"
    "${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 \
      -f ${GRAYLOG_HOME}/config/graylog.conf
  graylog.conf: "node_id_file = /usr/share/graylog/data/journal/node-id\nroot_username
    = admin\nroot_email = \nroot_timezone = UTC\n\nhttp_bind_address = 0.0.0.0:9000\nelasticsearch_hosts
    = http://elasticsearch-master.default.svc.cluster.local:9200\nallow_leading_wildcard_searches
    = false\nallow_highlighting = false\noutput_batch_size = 500\noutput_flush_interval
    = 1\noutput_fault_count_threshold = 5\noutput_fault_penalty_seconds = 30\nprocessbuffer_processors
    = 5\noutputbuffer_processors = 3\nprocessor_wait_strategy = blocking\nring_size
    = 65536\ninputbuffer_ring_size = 65536\ninputbuffer_processors = 2\ninputbuffer_wait_strategy
    = blocking\nmessage_journal_enabled = true\n# Do not change `message_journal_dir`
    location\nmessage_journal_dir = /usr/share/graylog/data/journal\nmessage_journal_max_size
    = 5gb\nlb_recognition_period_seconds = 3\n# Use a replica set instead of a single
    host\nmongodb_uri = mongodb://RELEASE-NAME-mongodb-headless.default.svc.cluster.local:27017/graylog?replicaSet=rs0\nmongodb_max_connections
    = 1000\nmongodb_threads_allowed_to_block_multiplier = 5\n# Email transport\ntransport_email_enabled
    = false\ntransport_email_hostname = \ntransport_email_port = 2587\ntransport_email_use_auth
    = true\ntransport_email_use_tls = true\ntransport_email_use_ssl = false\ntransport_email_auth_username
    = \ntransport_email_auth_password = \ntransport_email_subject_prefix = [graylog]\ntransport_email_from_email
    = \ncontent_packs_dir = /usr/share/graylog/data/contentpacks\ncontent_packs_auto_load
    = grok-patterns.json\nproxied_requests_thread_pool_size = 32"
  log4j2.xml: |-
    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration packages="org.graylog2.log4j" shutdownHook="disable">
        <Appenders>
            <Console name="STDOUT" target="SYSTEM_OUT">
                <PatternLayout pattern="%d %-7level [%c{1}] - %m - %X%n"/>
            </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>
kind: ConfigMap
metadata:
  labels:
    app.kubernetes.io/instance: RELEASE-NAME
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: graylog
    app.kubernetes.io/version: 4.2.3
    helm.sh/chart: graylog-2.0.0
  name: RELEASE-NAME-graylog
