# Loki Server
#
# Scope: Log ingester and aggregator to be run on the monitoring node
#
# See also:
#   - The configuration is adapted from
#     https://grafana.com/docs/loki/latest/configuration/examples/#complete-local-configyaml
#

{ config, ...}:
let
  logRetention = toString(config.services.private-storage.monitoring.policy.logRetentionSeconds) + "s";

in {
  config.networking.firewall.interfaces.monitoringvpn.allowedTCPPorts = [ 3100 ];

  config.services.loki = {
    enable = true;

    configuration =
      {
        auth_enabled = false;

        common = {
          ring = {
            kvstore = {
              store = "inmemory";
            };
          };
          instance_addr = "127.0.0.1";
          replication_factor = 1;
          path_prefix = "/var/lib/loki";
          storage = {
            filesystem = {
              chunks_directory = "/var/lib/loki/chunks";
              rules_directory = "/var/lib/loki/rules";
            };
          };
        };

        server = {
          http_listen_port = 3100;
          grpc_listen_port = 9095; # unused, but no option to turn it off.
          grpc_listen_address = "127.0.0.1"; # unused, but no option to turn it off.
        };

        ingester = {
          lifecycler = {
            final_sleep = "0s";
          };
          chunk_target_size = 1536000; # As per https://grafana.com/docs/loki/v2.2.1/best-practices/
        };

        schema_config = {
          configs = [{
            from = "2020-12-26";
            store = "boltdb-shipper";
            object_store = "filesystem";
            schema = "v11";
            index = {
              prefix = "index_";
              period = "24h";
            };
          }];
        };

        limits_config = {
          allow_structured_metadata = false;
        };

        table_manager = {
          retention_deletes_enabled = true;
          retention_period = logRetention;
        };
      };
  };
}