job "clickhouse" {
  datacenters = ["alo"]

  meta {
    uuid = uuidv4()
  }

  group "db" {
    # Run on primary storage node (zippy) for local disk performance
    # TODO: move to fractal once it's converted to NixOS (spinning disks OK for time-series data)
    constraint {
      attribute = "${meta.storage_role}"
      value     = "primary"
    }

    network {
      port "clickhouse" {
        static = 8123
      }
    }

    task "clickhouse" {
      driver = "docker"

      config {
        image = "clickhouse/clickhouse-server:25.9"
        volumes = [
          "/data/services/clickhouse:/var/lib/clickhouse",
          "local/clickhouse-config.xml:/etc/clickhouse-server/config.d/logging.xml:ro",
          "local/clickhouse-user-config.xml:/etc/clickhouse-server/users.d/logging.xml:ro",
        ]
        ports = [ "clickhouse" ]
      }

      env {
        # TODO: this is insecure, see "Managing default user" at https://hub.docker.com/r/clickhouse/clickhouse-server/
        CLICKHOUSE_SKIP_USER_SETUP = 1
      }

      service {
        name = "clickhouse"
        port = "clickhouse"
      }

      template {
data = <<EOH
<clickhouse>
    <logger>
        <level>warning</level>
        <console>true</console>
    </logger>
    <listen_host>0.0.0.0</listen_host>

    <!-- Stop all the unnecessary logging -->
    <query_thread_log remove="remove"/>
    <query_log remove="remove"/>
    <text_log remove="remove"/>
    <trace_log remove="remove"/>
    <metric_log remove="remove"/>
    <asynchronous_metric_log remove="remove"/>
    <session_log remove="remove"/>
    <part_log remove="remove"/>
</clickhouse>
EOH
        destination = "local/clickhouse-config.xml"
      }

      template {
data = <<EOH
<clickhouse>
    <profiles>
        <default>
            <log_queries>0</log_queries>
            <log_query_threads>0</log_query_threads>
        </default>
    </profiles>
</clickhouse>
EOH
        destination = "local/clickhouse-user-config.xml"
      }

      resources {
        memory = 1000
      }
    }
  }
}
