diff --git a/README.md b/README.md index 646a4eb..e746524 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,76 @@ -[![Mod Portal](https://img.shields.io/badge/dynamic/json?label=Mod%20Portal&query=%24.releases%5B-1%3A%5D.version&url=https%3A%2F%2Fmods.factorio.com%2Fapi%2Fmods%2Fkafkatorio-events&style=flat-square&color=%23600401)](https://mods.factorio.com/mod/kafkatorio-events) -[![Factorio Version](https://img.shields.io/badge/dynamic/json?label=Factorio%20Version&query=%24.releases%5B-1%3A%5D.info_json.factorio_version&url=https%3A%2F%2Fmods.factorio.com%2Fapi%2Fmods%2Fkafkatorio-events&style=flat-square&color=%23d7cdf6)](https://mods.factorio.com/mod/kafkatorio-events) - # Kafkatorio -[Kafkatorio](https://github.com/adamko-dev/kafkatorio) is a platform used for creating -[Factorio](https://www.factorio.com/) mods that require communication with an external server. +Kafkatorio streams what happens on a [Factorio](https://www.factorio.com/) server to +[Apache Kafka](https://kafka.apache.org/), and turns it into a live website for the server: -Development is ongoing. +* **Map** – a live map of every surface, with terrain, resource patches (with their size or + number of wells), buildings (with their direction and recipe), belts, and players moving in real + time. +* **Production** – what's produced and consumed per minute, and science packs used, over the + last 10 minutes up to the last 7 days, for all surfaces or one. +* **Research** – what's researched, the current research and queue, and how many science packs are + left. Shown as a filterable list, or as a tree like the game's technology screen. -At present Kafkatorio is used to create a [live-view web map](https://factorio.adamko.dev), that -shows the current status of a Factorio server, and any connected players. +It's built for Factorio 2.0, and works with large mod packs (it's used with Space Exploration and +Krastorio 2). -However, Kafkatorio can be used for more than this. It has the potential to export metrics, and -allow for inter-server communication. +This is a fork of [adamko-dev/kafkatorio](https://github.com/adamko-dev/kafkatorio), updated for +Factorio 2.0, with the production and research pages and many fixes. -Kafkatorio was created to explore the possibilities of using -[Apache Kafka](https://kafka.apache.org/) to process updates from a Factorio server. +## Running it yourself -### Running +You need a Factorio server running in Docker, and a machine to build the images on. +**[The guide](./docs/guide.md)** covers building, configuring, connecting the Factorio server, +and putting the website behind a reverse proxy, with a ready-made setup for Unraid. -[Instructions for running a Kafkatorio instance are available in the docs](./docs/guide.md). - -### Overview - -This is a brief overview of how Kafkatorio gathers data, processes it, and uses it to create the -live web-map. - -Kafkatorio receives updates from a Factorio server, processes them, and exposes them over a REST -and WebSocket APIs. - -1. The Kafkatorio game mod, [`events-mod`](./modules/events-mod), collects event data, de-bouncing - and grouping events, and converts them to JSON packets -2. `events-mod` prints the packets to the Factorio game server logs -3. The Factorio logs are forwarded to a Kafka cluster, either using - * [syslog](https://docs.docker.com/config/containers/logging/syslog/) (using Docker logging - plugin) - * or [Kafka Pipe](./modules/infra-kafka-pipe) (a script that reads the server logs and forwards - them to a Kafka topic) -4. The packets are consumed by [`events-server`](./modules/events-server), which processes the - packets using Kafka Streams, creating and hosting map tiles. - - `events-server` serves the map tiles via a REST API, and produces WebSocket messages regarding - updates (for example, when a player's location has changed). -5. The `web-map` uses Leaflet/JS to display the map, using the tiles and WebSocket messages from - `events-server` +## How it works ```mermaid -sequenceDiagram +flowchart LR + factorio["Factorio server
+ kafkatorio-events mod"] + syslog[events-server-syslog] + kafka[(Kafka)] + processors[events-processors] + web[events-server-web] + map["web-map
(nginx)"] + browser([Browser]) -Factorio multiplayer server->>events-mod: in-game events -Note over events-mod: converts events to packets -events-mod->>logs processor: packets logged to console -logs processor->>Kafka: publishes packets
(Requires API key!) - -Kafka->>events-server: - -Note over events-server: Packets are processed - -events-server->>web-map: Web map tiles (REST API) -events-server-)web-map: WebSocket updates
(e.g. player movement) + factorio -- "packets in the server log
(Docker syslog log driver)" --> syslog + syslog -- "checks the server's token" --> kafka + kafka <--> processors + kafka --> web + web -- "REST + WebSocket" --> map + map --> browser ``` +1. The mod, [`events-mod`](./modules/events-mod) (written in TypeScript, compiled to Lua), listens + to in-game events, groups and de-bounces them, and prints them as JSON packets to the server + log. +2. Docker's syslog log driver forwards the Factorio container's log to + [`events-server-syslog`](./modules/events-server-syslog). Each server's log is tagged with a + token (a JWT), so only known servers are accepted. The packets go to a Kafka topic. +3. [`events-processors`](./modules/events-processors) uses Kafka Streams to turn the packets into + map tiles, buildings, resource patches, and so on. +4. [`events-server-web`](./modules/events-server-web) serves the tiles and the other data over a + REST API, and pushes live updates (such as players moving) over a WebSocket. +5. [`web-map`](./modules/web-map) is the website (Kotlin/JS, with Leaflet for the map). Its nginx + also forwards `/kafkatorio/` to `events-server-web`, so the whole site is on a single port. + +The packet format is defined once in [`events-library`](./modules/events-library) (Kotlin), which +also generates the mod's TypeScript types. + +## Building + +```shell +./gradlew build # build and test +./gradlew :modules:events-mod:distZip + # the mod: modules/events-mod/build/distributions/ +``` + +See [the guide](./docs/guide.md#1-build-the-docker-images-and-the-mod) for building the Docker +images. + ## License -Because I care about sharing improvements, Kafkatorio is licensed under the +Kafkatorio is licensed under the [**GNU General Public License v3.0**](https://choosealicense.com/licenses/gpl-3.0/). diff --git a/docs/guide.md b/docs/guide.md index 7f65f00..ff48116 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1,106 +1,309 @@ # Running Kafkatorio -### Building the project +This guide sets up Kafkatorio for a Factorio server, from building it to a public website. -#### Requirements +- [What you need](#what-you-need) +- [1. Build the Docker images and the mod](#1-build-the-docker-images-and-the-mod) +- [2. Configure Kafkatorio](#2-configure-kafkatorio) +- [3. Start Kafkatorio](#3-start-kafkatorio) +- [4. Connect the Factorio server](#4-connect-the-factorio-server) +- [5. Send the existing map](#5-send-the-existing-map) +- [6. Icons and names](#6-icons-and-names) +- [7. Put it on the internet](#7-put-it-on-the-internet) +- [Unraid](#unraid) +- [Updating](#updating) +- [Troubleshooting](#troubleshooting) +- [Developing](#developing) -* Docker -* Docker Compose -* Java 11 +## What you need -Kafkatorio uses [Gradle](https://docs.gradle.org/current/userguide/getting_started.html) to -build the project, and Docker Compose to create images. +* **A Factorio 2.0 server running in Docker**, for example + [factoriotools/factorio](https://hub.docker.com/r/factoriotools/factorio). Kafkatorio reads + the server's log through Docker's syslog log driver. The example setup can run the Factorio + server for you. +* **A Docker host for Kafkatorio**, ideally the same one as the Factorio server. It needs about + 5 GB of memory while the existing map is sent (step 5), and much less after that. (The memory + limits are the `-Xmx` options in `docker-compose.yml`.) +* **A machine to build on**, with Docker, Git and a JDK (11 or newer). There are no published + images, so you build them yourself. Gradle downloads everything else (including Node.js, for the + mod). -* `./gradlew build` - build and test the project -* `./gradlew runKafkatorio` - run locally (if Docker is running, a Kafka instance will start) -* `./gradlew dockerComposeBuild` - build, test, and create Kafkatorio Docker images +| Port | Service | Expose? | +|--------------|---------------------------------------------|--------------------------------------------| +| `12081` | the website (`web-map`) | yes, through a reverse proxy (step 7) | +| `12035` | receives the Factorio server's log (syslog) | only to the Factorio server's Docker host | +| `18090` | Kafka UI, for debugging | no - Kafka has no authentication | +| `34197/udp` | the Factorio game (if the example runs it) | yes, for players | -### Server set up +## 1. Build the Docker images and the mod -> See [./kafkatorio-platform/docker-compose.yml](kafkatorio-platform/docker-compose.yml) for a -> complete example +```shell +git clone kafkatorio +cd kafkatorio -1. Copy the [kafkatorio-platform](./kafkatorio-platform) directory to your computer -2. Rename - [`example.secret.kafkatorio-config.yml`](./kafkatorio-platform/example.secret.kafkatorio-config.yml) - to `.secret.kafkatorio-config.yml` +./gradlew \ + :modules:infra-kafka-cluster:dockerComposeBuild \ + :modules:events-processors:dockerComposeBuild \ + :modules:events-server-syslog:dockerComposeBuild \ + :modules:events-server-web:dockerComposeBuild \ + :modules:web-map:dockerComposeBuild \ + :modules:events-mod:distZip +``` - In it, define both - * a JWT secret password (a long alphanumeric string is best, you won't need to type this - password manually) - * a Factorio server, with a short-ID and a description. -3. Rename [`example.env`](./kafkatorio-platform/example.env) to `.env` -4. Create a JWT for your Factorio server, by going to https://jwt.io/ +This creates five images, tagged `localhost/dev.adamko.kafkatorio/:` +(`kafka-kraft`, `events-processors`, `events-server-syslog`, `events-server-web`, `web-map`), and +the mod, `modules/events-mod/build/distributions/kafkatorio-events_.zip`. The version is +the `version` in [`build.gradle.kts`](../build.gradle.kts). - * In 'PAYLOAD: DATA', set `sub` to your Factorio server's short ID. - ```json - { - "sub": "", - "iat": ... - } - ``` - (`iat`, 'issued-at-time', should update automatically to be the current time.) - * Replace `your-256-bit-secret` with your JWT secret password +If you build on a different machine from the Docker host, copy the images over (no registry needed): - Copy the 'Encoded' token (it should start with `ey`). +```shell +docker save $(docker images --format '{{.Repository}}:{{.Tag}}' | grep dev.adamko.kafkatorio) \ + | gzip | ssh 'gunzip | docker load' +``` - In the `.env` file, set `KAFKATORIO_TOKEN` to equal the token. -5. In `kafkatorio-platform`, start the docker containers +## 2. Configure Kafkatorio - ```terminal - docker-compose up -d; docker-compose logs -f +Copy the [`kafkatorio-platform`](./kafkatorio-platform) directory to the Docker host. All +Kafkatorio's data is kept in it. In that directory: + +1. Copy [`example.env`](./kafkatorio-platform/example.env) to `.env`, and check + `KAFKATORIO_VERSION` matches the images you built. + +2. Copy [`example.secret.kafkatorio-config.yml`](./kafkatorio-platform/example.secret.kafkatorio-config.yml) + to `.secret.kafkatorio-config.yml`, and set + + * `jwt-secret`: a long random password, used to sign the Factorio server's token. You won't + need to type it anywhere. For example, `openssl rand -hex 32`. + * `kafkatorio-servers`: your Factorio server. The key is the server's *token name* (put in + the token, below), and the value is its *ID*, which is used in the website's URLs + (`/servers//`). They can be the same, e.g. `my-server: "my-server"`. + +3. Create a Kafka cluster ID, so Kafka's data survives image rebuilds: + + ```shell + docker run --rm --entrypoint ./bin/kafka-storage.sh \ + localhost/dev.adamko.kafkatorio/kafka-kraft: random-uuid > config/cluster_id ``` -### Unraid set up +### Create a token for the Factorio server -> See [./kafkatorio-platform/unraid/docker-compose.yml](kafkatorio-platform/unraid/docker-compose.yml) +The Factorio server's log is tagged with a token (a JWT), so Kafkatorio knows which server it's +from, and ignores logs from anyone else. Create it with the `jwt-secret` and the server's token +name (`sub`): -This runs the Kafkatorio services on the same Unraid server as the Factorio server. The Docker -syslog log driver runs in the Docker daemon on the host, so the syslog port only needs to listen -on `127.0.0.1`, and Kafka isn't exposed at all. +```shell +python3 -c 'import base64,hashlib,hmac,json,sys,time +b=lambda d: base64.urlsafe_b64encode(d).rstrip(b"=").decode() +j=lambda o: b(json.dumps(o,separators=(",",":")).encode()) +m=j({"alg":"HS256","typ":"JWT"})+"."+j({"sub":sys.argv[2],"iat":int(time.time())}) +print(m+"."+b(hmac.new(sys.argv[1].encode(),m.encode(),hashlib.sha256).digest()))' \ + '' '' +``` + +(Or use [jwt.io](https://jwt.io/), with algorithm HS256, the payload +`{"sub": "", "iat": }`, and the `jwt-secret` as the secret. But +then you're typing the secret into a website.) + +The token starts with `ey`. Put it in `.env` as `KAFKATORIO_TOKEN`. + +## 3. Start Kafkatorio + +```shell +docker compose up -d +docker compose logs -f +``` + +The website is on `http://:12081`. It's empty until the Factorio server sends +something. + +## 4. Connect the Factorio server + +### Install the mod + +Put `kafkatorio-events_.zip` in the Factorio server's `mods` directory (for the example +server, `factorio-server/mods/`), and restart it. + +Players need the same mod, with the same version, to join, so give them the zip too (it goes in +their Factorio `mods` directory). Don't let them download it from the mod portal: the portal's +`kafkatorio-events` is the original project, for Factorio 1.1, and its version numbers overlap +with this one. + +### Forward the server's log to Kafkatorio + +**If the example runs your Factorio server**, this is already set up. Start it with: + +```shell +docker compose --profile factorio up -d +``` + +**If you already have a Factorio container**, add these options to it, then recreate it: + +```shell +--log-driver=syslog \ +--log-opt syslog-address=tcp://127.0.0.1:12035 \ +--log-opt syslog-format=rfc5424 \ +--log-opt mode=non-blocking \ +--log-opt tag= +``` + +or in a Compose file: + +```yaml + logging: + driver: syslog + options: + syslog-address: "tcp://127.0.0.1:12035" + syslog-format: "rfc5424" + mode: "non-blocking" + tag: "" +``` + +The log driver runs in the Docker daemon, not in the container, so `127.0.0.1` is the Docker +host. If the Factorio server runs on another host, use this host's address, and in +`docker-compose.yml` change `127.0.0.1:12035:9002` to `12035:9002` (and firewall it so only the +Factorio host can connect). + +Docker won't start a container if its syslog server can't be reached, so Kafkatorio must be +running before the Factorio server starts. After a reboot, delay the Factorio server's start by +about 30 seconds. + +To check it's working, `docker compose logs -f events-server-syslog` while someone plays. If the +token wasn't signed with the `jwt-secret`, you'll see `Could not decode JWT` there. + +## 5. Send the existing map + +New chunks, buildings and research are sent as they happen. To send what's already there, join the +game and run, in the chat console: + +``` +/kafkatorio prototypes +/kafkatorio chunks 10 +``` + +* `prototypes` sends the tile and entity types. Run it first, and again after changing mods. +* `chunks ` sends the terrain, resources and buildings of every chunk within `` + chunks of your position (on every surface). Each chunk is 32 tiles. Start small, and increase it + until the whole map is on the website. Large radiuses (e.g. `chunks 30`) take minutes to process, + and need the most memory. + +Research is sent every minute. Production statistics are sent every minute, but only while the +game is running: if the server pauses when nobody's online (`auto_pause`), there are no statistics +then. + +## 6. Icons and names + +The building icons on the map, the production page and the research page need icons, building +sizes, in-game names and the technology tree. They're exported from a Factorio client with the +same mods as the server (they're not in this repository, since they belong to Wube and the mod +authors). Without them, the map has no building icons, and those pages show internal names, or +nothing. + +On a computer with Factorio, with the game closed: + +```shell +factorio --dump-data +factorio --dump-prototype-locale +factorio --dump-icon-sprites +python3 docs/kafkatorio-platform/building-icons/export_building_icons.py ~/.factorio/script-output ./icons +scp -r ./icons :/ +``` + +* With Steam, run `SteamAppId=427520 factorio --dump-icon-sprites`, or Steam restarts the game + normally instead. +* `factorio` is the game's executable, e.g. `~/.steam/steam/steamapps/common/Factorio/bin/x64/factorio`. + `~/.factorio/script-output` is the Linux location; on Windows it's `%APPDATA%\Factorio\script-output`. +* If [Pillow](https://pypi.org/project/pillow/) is installed, the (large) technology icons are + shrunk. + +The website uses them straight away, but browsers keep icons for up to a day, so reload with +Ctrl+Shift+R. Export them again when the mods change. + +## 7. Put it on the internet + +Point a reverse proxy (Nginx Proxy Manager, Caddy, Traefik, ...) at port `12081`, and **enable +WebSocket support** - otherwise the website loads, but players and other live updates don't move. +The website, the API (`/kafkatorio/`) and the WebSocket (`/kafkatorio/ws`) are all on that one +port. + +Don't expose the other ports. Kafka and the Kafka UI have no authentication. + +## Unraid + +[`kafkatorio-platform/unraid`](./kafkatorio-platform/unraid) has a setup for running Kafkatorio +on the same Unraid server as the Factorio server. It's the same as the example above, but keeps +the data in `appdata`, and doesn't run a Factorio server. 1. Install the *Compose Manager* plugin (or *Compose Manager Plus*) from the Apps tab. -2. Build the images locally, and copy them to Unraid (no registry needed): - - ```terminal - ./gradlew dockerComposeBuild - docker save $(docker images --format '{{.Repository}}:{{.Tag}}' | grep dev.adamko.kafkatorio) \ - | gzip | ssh root@ 'gunzip | docker load' - ``` -3. On Unraid, create `/mnt/user/appdata/kafkatorio-platform/` containing - * `.secret.kafkatorio-config.yml` (see above) - * `config/kafka-server.properties` (copy from [./kafkatorio-platform/config](kafkatorio-platform/config)) - * `config/cluster_id` - a fixed Kafka cluster ID, so the Kafka data survives image rebuilds. - Generate one with `docker run --rm --entrypoint ./bin/kafka-storage.sh random-uuid`. -4. Create a Compose Manager stack, with the Unraid `docker-compose.yml`, and - [`example.env`](kafkatorio-platform/unraid/example.env) as its `.env`. Start the stack. -5. Edit the Factorio container, enable 'Advanced View', and set 'Extra Parameters' to +2. Build the images, and copy them to Unraid ([step 1](#1-build-the-docker-images-and-the-mod)). +3. Create `/mnt/user/appdata/kafkatorio-platform/` containing + * `.secret.kafkatorio-config.yml` ([step 2](#2-configure-kafkatorio)) + * `config/kafka-server.properties` (copy from [`kafkatorio-platform/config`](./kafkatorio-platform/config)) + * `config/cluster_id` ([step 2](#2-configure-kafkatorio)) +4. Create a Compose Manager stack, with the Unraid + [`docker-compose.yml`](./kafkatorio-platform/unraid/docker-compose.yml), and + [`example.env`](./kafkatorio-platform/unraid/example.env) as its `.env`. + Set `KAFKA_DATA_DIR` to a direct disk or pool path (e.g. `/mnt/cache/...` or `/mnt/disk1/...`), + not `/mnt/user/...`: Unraid's FUSE layer is slow for Kafka. Start the stack. +5. Edit the Factorio container, enable *Advanced View*, and set *Extra Parameters* to ``` --log-driver=syslog --log-opt syslog-address=tcp://127.0.0.1:12035 --log-opt syslog-format=rfc5424 --log-opt mode=non-blocking --log-opt tag= ``` - Docker won't start a container if its TCP syslog server isn't reachable, so on the Docker tab - give the Factorio container an autostart 'wait' of ~30 seconds, so the Kafkatorio services start - first. -6. The web map is on port `12081`. It also proxies `/kafkatorio/` to the events server, so a - reverse proxy (e.g. Nginx Proxy Manager) only needs to forward to that one port - make sure - WebSocket support is enabled. -7. In Factorio, run `/kafkatorio prototypes` and then `/kafkatorio chunks 10` to send the existing - map. -8. Optional: icons and names. The web map's 'Building icons' layer, the research page and the - production page use icons, building sizes, the technology tree and in-game names, exported from - a Factorio client that has the same mods as the server (they're not in this repo, since they - belong to Wube and the mod authors). Without them, those pages show less, or nothing. With the - game closed, run + On the Docker tab, give the Factorio container an autostart *wait* of about 30 seconds, so + Kafkatorio starts first. +6. Continue from [step 4](#4-connect-the-factorio-server) (installing the mod). Put the icons in + `/mnt/user/appdata/kafkatorio-platform/icons`. - ```terminal - factorio --dump-data - factorio --dump-prototype-locale - SteamAppId=427520 factorio --dump-icon-sprites # SteamAppId stops Steam relaunching the game - python3 docs/kafkatorio-platform/building-icons/export_building_icons.py ~/.factorio/script-output ./icons - scp -r ./icons root@:/mnt/user/appdata/kafkatorio-platform/ - ``` +## Updating - Re-export them when the mods change. If [Pillow](https://pypi.org/project/pillow/) is installed, - the (large) technology icons are shrunk. +1. Pull the changes, and rebuild the images and the mod ([step 1](#1-build-the-docker-images-and-the-mod)). + If the version in `build.gradle.kts` changed, update `KAFKATORIO_VERSION` in `.env`. +2. `docker compose up -d` recreates the containers with the new images. The map and other data are + kept. +3. If the mod changed, replace it on the server and give players the new zip. Factorio clients and + the server must have exactly the same mod. Close the game before replacing the zip in your own + `mods` directory. + +Restart all the Kafkatorio services together when updating, not only some of them: +`events-server-syslog` reads and re-writes every packet, so it drops anything it doesn't know +about yet. + +## Troubleshooting + +**The website shows "Loading servers…" forever, or a new page shows the landing page.** Reload +without the cache (Ctrl+Shift+R). Older versions of the website could be cached by browsers after +an update. + +**The website loads, but nothing moves.** Check WebSocket support is enabled in the reverse proxy +([step 7](#7-put-it-on-the-internet)). + +**Nothing appears on the map.** +* Check the server's log reaches Kafkatorio: `docker compose logs events-server-syslog`. + `Could not decode JWT` means the token wasn't signed with the `jwt-secret`. +* Log lines that Kafkatorio rejects go to the `kafkatorio.src.server-log.dlq` topic, with the + reason (look at it in the Kafka UI). `no server ID for token` means the token name (`sub`) isn't + in `kafkatorio-servers`. +* Run `/kafkatorio prototypes` and `/kafkatorio chunks 5` in game ([step 5](#5-send-the-existing-map)). +* After a large `chunks` command, processing takes minutes. The Kafka UI (`http://localhost:18090` + on the Docker host) shows the topics, and how far behind the processors are. + +**The Factorio container won't start: `failed to initialize logging driver`.** Kafkatorio's +syslog server isn't running yet. Start Kafkatorio first, wait a few seconds, then start the +Factorio container. + +**Building icons, names, or the technology tree are missing.** Export the icons and names +([step 6](#6-icons-and-names)) with the same mods as the server. + +## Developing + +* `./gradlew build` builds and tests everything. +* [`modules/modules.md`](../modules/modules.md) shows how the modules depend on each other. +* The packets are defined in [`events-library`](../modules/events-library). Changing them + regenerates the mod's TypeScript types + (`modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts`). +* For the website, `./gradlew :modules:web-map:browserDevelopmentRun --continuous` serves it on + `http://localhost:3000`. It forwards API requests to `events-server-web` on `localhost:12080`, so + add `ports: [ "12080:80" ]` to `events-server-web` in your local `docker-compose.yml`. (Icons + aren't forwarded.) diff --git a/docs/kafkatorio-platform/docker-compose.yml b/docs/kafkatorio-platform/docker-compose.yml index 82924b9..1fd479b 100644 --- a/docs/kafkatorio-platform/docker-compose.yml +++ b/docs/kafkatorio-platform/docker-compose.yml @@ -1,145 +1,150 @@ -version: "3.9" +## Kafkatorio, and optionally a Factorio server, on one Docker host. +## +## See docs/guide.md. In short: +## cp example.env .env # and edit it +## cp example.secret.kafkatorio-config.yml .secret.kafkatorio-config.yml # and edit it +## docker compose up -d # Kafkatorio only +## docker compose --profile factorio up -d # ... and the Factorio server +## +## All data is kept in this directory, so containers can be recreated (e.g. to upgrade) without +## losing the map. + +name: kafkatorio services: - ## Factorio game server that players will connect to - factorio-server: - image: factoriotools/factorio:${FACTORIO_VERSION} - container_name: "factorio-server" + ## Kafka (KRaft mode). Only reachable by the other containers. + infra-kafka: + image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/kafka-kraft:${KAFKATORIO_VERSION} + container_name: kafkatorio-kafka restart: unless-stopped - profiles: [ "factorio", "kafkatorio" ] networks: - - kafkatorio-infra-nw - ports: - - "34198:34197/udp" # factorio - - "27016:27015/tcp" # rcon + kafkatorio-nw: + aliases: [ kafka ] volumes: - - "./factorio-server:/factorio" - logging: - # set up syslog, so logs can be forwarded to Kafkatorio - driver: syslog - options: - syslog-address: ${SYSLOG_ADDRESS} - syslog-format: "rfc5424" - # set the tag to be a JWT, containing the server short-ID - tag: ${KAFKATORIO_TOKEN} + - "./config/kafka-server.properties:/kafka/server.properties:ro" + # fixed cluster ID, so the Kafka data survives image rebuilds + - "./config/cluster_id:/kafka/cluster_id:ro" + - "./kafka-data:/tmp/kraft-combined-logs" - - ## Kafkatorio Web Map host - web-map: - image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/web-map:${KAFKATORIO_VERSION} - container_name: web-map - profiles: [ "infra", "kafkatorio" ] - restart: unless-stopped - ports: - - "12081:80" # web map (also proxies /kafkatorio/ to events-server-web) - networks: - - kafkatorio-infra-nw -# volumes: -# # building icons - see building-icons/export_building_icons.py -# - "./icons:/usr/share/nginx/icons:ro" - - - ## Process Kafkatorio events + ## Processes Kafkatorio events (map tiles, buildings, resources...) events-processors: image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-processors:${KAFKATORIO_VERSION} - container_name: events-processors + container_name: kafkatorio-events-processors restart: unless-stopped - profiles: [ "infra", "kafkatorio" ] environment: KAFKA_BOOTSTRAP_SERVERS: "kafka:29092" - networks: - - kafkatorio-infra-nw - depends_on: - - infra-kafka + # one stream thread per partition (topics have 3) + KAFKA_STREAMS_NUM_THREADS: "3" + # merge repeated map-chunk updates for 10s before forwarding them (128MB cache per topology) + KAFKA_STREAMS_COMMIT_INTERVAL_MS: "10000" + KAFKA_STREAMS_CACHE_MAX_BYTES: "134217728" + # Sending the existing map (`/kafkatorio chunks 30`) needs a large heap for a while. G1 hands + # unused heap back to the OS when idle (G1PeriodicGCInterval). Lower -Xmx for small maps. + JAVA_OPTS: "-Xmx3g -XX:G1PeriodicGCInterval=60000 -XX:MaxHeapFreeRatio=30 -XX:MinHeapFreeRatio=10" + # off-heap memory shared by all RocksDB state stores + ROCKSDB_TOTAL_MEMORY_MB: "256" + networks: [ kafkatorio-nw ] + depends_on: [ infra-kafka ] + volumes: + - "./state/events-processors:/app/state" secrets: - source: kafkatorio_config target: /.secret.config.yml - - ## Receives packets from the Factorio Server, forwarded via Docker syslog-plugin + ## Receives packets from the Factorio server, forwarded by the Docker syslog log driver. + ## The log driver runs in the Docker daemon on the host, so if Factorio runs on this host, + ## localhost-only is enough. If Factorio runs on another host, remove `127.0.0.1:` - and only + ## allow that host in your firewall. events-server-syslog: image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-server-syslog:${KAFKATORIO_VERSION} - container_name: events-server-syslog + container_name: kafkatorio-events-server-syslog restart: unless-stopped - profiles: [ "infra", "kafkatorio" ] environment: KAFKA_BOOTSTRAP_SERVERS: "kafka:29092" + JAVA_OPTS: "-Xmx256m -XX:G1PeriodicGCInterval=60000" SOCKET_SERVER_HOST: "0.0.0.0" SOCKET_SERVER_PORT: "9002" ports: - - "12035:9002" # syslog socket - networks: - - kafkatorio-infra-nw - depends_on: - - infra-kafka - - events-processors + - "127.0.0.1:12035:9002" + networks: [ kafkatorio-nw ] + depends_on: [ infra-kafka ] secrets: - source: kafkatorio_config target: /.secret.config.yml - - ## Hosts map-tiles and forwards websocket messages to the web-map browsers + ## Serves map tiles and other data, and sends live updates to browsers over a WebSocket events-server-web: image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-server-web:${KAFKATORIO_VERSION} - container_name: events-server-web + container_name: events-server-web # web-map's nginx proxies to this hostname restart: unless-stopped - profiles: [ "infra", "kafkatorio" ] environment: KAFKA_BOOTSTRAP_SERVERS: "kafka:29092" + KAFKA_STREAMS_NUM_THREADS: "3" + JAVA_OPTS: "-Xmx768m -XX:G1PeriodicGCInterval=60000 -XX:MaxHeapFreeRatio=30 -XX:MinHeapFreeRatio=10" WEB_SERVER_PORT: "80" - ports: - - "12080:80" # http and ws - networks: - - kafkatorio-infra-nw - depends_on: - - infra-kafka - - events-processors + networks: [ kafkatorio-nw ] + depends_on: [ infra-kafka ] + volumes: + - "./data/events-server-web:/app/data" + - "./state/events-server-web:/app/state" secrets: - source: kafkatorio_config target: /.secret.config.yml - - ## An instance of Kafka - infra-kafka: - image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/kafka-kraft:${KAFKATORIO_VERSION} - container_name: infra-kafka + ## The website. Its nginx also proxies /kafkatorio/ to events-server-web, so a reverse proxy only + ## needs to forward to this one port (with WebSocket support). + web-map: + image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/web-map:${KAFKATORIO_VERSION} + container_name: kafkatorio-web-map restart: unless-stopped - profiles: [ "infra", "kafka" ] - networks: - kafkatorio-infra-nw: - aliases: [ kafka ] - volumes: - - "./config/kafka-server.properties:/kafka/server.properties" ports: - # note: other Docker containers should use 29092 - - "9092:9092" - - "9093:9093" + - "12081:80" + networks: [ kafkatorio-nw ] + volumes: + # icons, names and the technology tree - see "Icons and names" in docs/guide.md + - "./icons:/usr/share/nginx/icons:ro" - - ## web-based GUI for Kafka + ## Kafka admin UI. Only on localhost: Kafka has no authentication, so don't expose this. infra-kafka-ui: image: provectuslabs/kafka-ui:v0.4.0 - container_name: infra-kafka-ui + container_name: kafkatorio-kafka-ui restart: unless-stopped - profiles: [ "infra", "kafka" ] - networks: - - kafkatorio-infra-nw ports: - - "18090:8080" - depends_on: - - infra-kafka + - "127.0.0.1:18090:8080" + networks: [ kafkatorio-nw ] + depends_on: [ infra-kafka ] environment: - KAFKA_CLUSTERS_0_NAME: "${COMPOSE_PROJECT_NAME}" + KAFKA_CLUSTERS_0_NAME: "kafkatorio" KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: "kafka:29092" - + ## Optional: a Factorio server (start with `--profile factorio`). + ## Put the kafkatorio-events mod zip in ./factorio-server/mods/ + factorio-server: + image: factoriotools/factorio:${FACTORIO_VERSION} + container_name: kafkatorio-factorio-server + restart: unless-stopped + profiles: [ "factorio" ] + ports: + - "34197:34197/udp" # game + - "27015:27015/tcp" # RCON + volumes: + - "./factorio-server:/factorio" + # Docker won't start a container if its syslog server can't be reached, so start this last + depends_on: [ events-server-syslog ] + logging: + # forward the server log (which contains the mod's packets) to Kafkatorio + driver: syslog + options: + syslog-address: "tcp://127.0.0.1:12035" + syslog-format: "rfc5424" + mode: "non-blocking" + # the server's token (a JWT), which says which Kafkatorio server this is + tag: ${KAFKATORIO_TOKEN} secrets: kafkatorio_config: file: ./.secret.kafkatorio-config.yml - networks: - kafkatorio-infra-nw: - kafkatorio-game-nw: + kafkatorio-nw: diff --git a/docs/kafkatorio-platform/example.env b/docs/kafkatorio-platform/example.env index 4339796..063b420 100644 --- a/docs/kafkatorio-platform/example.env +++ b/docs/kafkatorio-platform/example.env @@ -1,10 +1,12 @@ -# Docker Compose containers config - -COMPOSE_PROJECT_NAME=Kafkatorio - -KAFKATORIO_TOKEN= -KAFKATORIO_VERSION=0.9.15 +# Docker Compose settings - copy to `.env` +# the version of the Kafkatorio images you built (the `version` in build.gradle.kts) +KAFKATORIO_VERSION=0.10.1 +# images are built locally, and tagged `localhost/dev.adamko.kafkatorio/...` REGISTRY_HOST=localhost -SYSLOG_ADDRESS=tcp://www.my-website.com:12345 +# Only needed for the optional Factorio server (`docker compose --profile factorio up -d`) +# A factoriotools/factorio tag: https://hub.docker.com/r/factoriotools/factorio +FACTORIO_VERSION=stable +# The Factorio server's token - see "Create a token for the Factorio server" in docs/guide.md +KAFKATORIO_TOKEN=