Add a forwarder for Factorio servers that don't run in Docker

The mod prints its packets to the server's standard output, and Docker's
syslog log driver sends them to Kafkatorio. kafkatorio-forward.py does
the same without Docker: it runs the server (or reads its output from a
pipe), prints the output as usual, and sends the mod's packets to the
syslog port in the same format as Docker, tagged with the token.

- the server keeps running when Kafkatorio is unreachable: packets wait in
  a bounded buffer, and are sent after reconnecting
- before each send it checks Kafkatorio hasn't closed the connection, so
  lines aren't silently lost in a dead socket
- Ctrl+C and SIGTERM are passed to the server once, so it saves and stops
- the token is read from a file or the environment, not the command line
- only the Python standard library

util-linux's logger can't be used instead: it rejects the token, which is
longer than syslog's 48 character APP-NAME limit.

Tested on Linux with a Factorio 2.0.77 server: packets arrive, the
forwarder reconnects when the syslog server restarts (no packets lost),
and the server saves when stopped.

The guide has a section for it, with a systemd service example, and the
README no longer says the Factorio server must run in Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-11-22 11:00:24 +01:00
parent 1f4786c1bd
commit 47ab9f30fc
3 changed files with 281 additions and 9 deletions

View file

@ -19,7 +19,8 @@ Factorio 2.0, with the production and research pages and many fixes.
## Running it yourself
You need a Factorio server running in Docker, and a machine to build the images on.
You need a Factorio server (in Docker, or not), a Docker host for Kafkatorio, 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.
@ -35,7 +36,7 @@ flowchart LR
map["web-map<br/>(nginx)"]
browser([Browser])
factorio -- "packets in the server log<br/>(Docker syslog log driver)" --> syslog
factorio -- "packets in the server's output<br/>(Docker syslog log driver,<br/>or kafkatorio-forward.py)" --> syslog
syslog -- "checks the server's token" --> kafka
kafka <--> processors
kafka --> web
@ -46,8 +47,9 @@ flowchart LR
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
2. Docker's syslog log driver (or, for a server outside Docker,
[`kafkatorio-forward.py`](./docs/kafkatorio-platform/forwarder/kafkatorio-forward.py)) forwards
the server's output 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.

View file

@ -17,10 +17,10 @@ This guide sets up Kafkatorio for a Factorio server, from building it to a publi
## What you need
* **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 Factorio 2.0 server**. Kafkatorio reads what the server prints. In Docker (for example
[factoriotools/factorio](https://hub.docker.com/r/factoriotools/factorio)), Docker's syslog log
driver sends it; the example setup can run the Factorio server for you. Without Docker, a small
Python script does it ([see below](#factorio-server-without-docker)).
* **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`.)
@ -31,7 +31,7 @@ This guide sets up Kafkatorio for a Factorio server, from building it to a publi
| 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 |
| `12035` | receives the Factorio server's log (syslog) | only to the Factorio server's host |
| `18090` | Kafka UI, for debugging | no - Kafka has no authentication |
| `34197/udp` | the Factorio game (if the example runs it) | yes, for players |
@ -171,6 +171,63 @@ 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.
### Factorio server without Docker
The mod prints its packets to the server's standard output (not to `factorio-current.log`).
[`kafkatorio-forward.py`](./kafkatorio-platform/forwarder/kafkatorio-forward.py) runs the server,
prints its output as usual, and sends the mod's packets to Kafkatorio. It needs Python 3.8 or
newer, and nothing else.
Copy it to the Factorio machine, put the token in a file only the server's user can read, and
start the server through it:
```shell
echo '<KAFKATORIO_TOKEN>' > kafkatorio-token.txt
chmod 600 kafkatorio-token.txt
python3 kafkatorio-forward.py --host <kafkatorio host> --token-file kafkatorio-token.txt -- \
./bin/x64/factorio --start-server my-save.zip --server-settings server-settings.json
```
* Everything after `--` is the server's usual command.
* `--host` is Kafkatorio's Docker host (default `127.0.0.1`). If that's another machine, publish
port `12035` to it: in `docker-compose.yml`, change `127.0.0.1:12035:9002` to `12035:9002`, and
firewall it so only the Factorio machine can connect.
* Ctrl+C (or SIGTERM) is passed to the server, so it saves and stops as usual.
* If Kafkatorio can't be reached, the server keeps running. The packets are kept in memory (up to
100,000, see `--buffer`) and sent when it's back.
* You can also pipe into it, `factorio --start-server ... | python3 kafkatorio-forward.py ...`,
but then stopping the script stops the server without saving. Prefer the first way.
* `KAFKATORIO_TOKEN=<token>` in the environment works instead of `--token-file`. Don't put the
token on the command line, where other users can see it in `ps`.
As a systemd service, for example `/etc/systemd/system/factorio.service`:
```ini
[Unit]
Description=Factorio server, forwarding to Kafkatorio
After=network-online.target
Wants=network-online.target
[Service]
User=factorio
WorkingDirectory=/opt/factorio
ExecStart=/usr/bin/python3 /opt/factorio/kafkatorio-forward.py \
--host <kafkatorio host> --token-file /opt/factorio/kafkatorio-token.txt -- \
/opt/factorio/bin/x64/factorio --start-server /opt/factorio/saves/my-save.zip \
--server-settings /opt/factorio/data/server-settings.json
# stop the script, which passes the signal to the server once, so it saves
KillMode=mixed
TimeoutStopSec=60
Restart=on-failure
[Install]
WantedBy=multi-user.target
```
Messages like `can't connect to ... retrying` from `[kafkatorio-forward]` mean Kafkatorio isn't
reachable yet; it keeps trying. It's tested on Linux.
## 5. Send the existing map
New chunks, buildings and research are sent as they happen. To send what's already there, join the

View file

@ -0,0 +1,213 @@
#!/usr/bin/env python3
"""
Forward a Factorio server's output to Kafkatorio, for servers that don't run in Docker.
The kafkatorio-events mod prints its packets to the server's standard output. In Docker, the
syslog log driver sends them to Kafkatorio. This does the same for a server that runs directly on
a machine: it reads the server's output, prints it as usual, and sends the mod's packets to
Kafkatorio's syslog port, tagged with the server's token.
Run the server through it (recommended):
KAFKATORIO_TOKEN=<token> kafkatorio-forward.py --host <kafkatorio host> -- \\
./bin/x64/factorio --start-server my-save.zip
or pipe the server's output into it:
./bin/x64/factorio --start-server my-save.zip | kafkatorio-forward.py --token-file token.txt
The server keeps running if Kafkatorio is down or restarts: packets are kept in memory (up to
--buffer lines) and sent when Kafkatorio is back. Ctrl+C or SIGTERM is passed to the server, so it
saves and stops as usual.
Only needs Python 3.8+, no extra packages.
"""
import argparse
import collections
import datetime
import os
import select
import signal
import socket
import subprocess
import sys
import threading
import time
PACKET_PREFIX = "KafkatorioPacket:::"
def log(message: str) -> None:
print(f"[kafkatorio-forward] {message}", file=sys.stderr, flush=True)
class Sender(threading.Thread):
"""Sends queued lines to the syslog server, reconnecting when needed."""
def __init__(self, host: str, port: int, token: str, buffer_size: int):
super().__init__(name="kafkatorio-sender", daemon=True)
self.address = (host, port)
self.token = token
self.hostname = socket.gethostname().split(".")[0] or "-"
self.queue = collections.deque()
self.buffer_size = buffer_size
self.dropped = 0
self.lock = threading.Condition()
self.closing = False
self.sock = None
def add(self, line: str) -> None:
with self.lock:
if len(self.queue) >= self.buffer_size:
self.queue.popleft()
self.dropped += 1
if self.dropped == 1 or self.dropped % 1000 == 0:
log(f"buffer full, dropped {self.dropped} oldest packets so far")
self.queue.append(line)
self.lock.notify()
def close(self, timeout: float) -> None:
"""Send what's left, for up to `timeout` seconds."""
with self.lock:
self.closing = True
self.lock.notify()
self.join(timeout)
with self.lock:
if self.queue:
log(f"stopped with {len(self.queue)} packets not sent")
def format(self, line: str) -> bytes:
# RFC 5424, like Docker's syslog log driver: the token goes in the APP-NAME field
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds")
timestamp = timestamp.replace("+00:00", "Z")
return f"<14>1 {timestamp} {self.hostname} {self.token} - - - {line}\n".encode("utf-8")
def peer_closed(self) -> bool:
"""
Kafkatorio never sends anything, so if the socket is readable, it has been closed.
Without this check, lines written after Kafkatorio closes the connection (e.g. when it
restarts) seem to be sent, but are lost.
"""
try:
readable, _, _ = select.select([self.sock], [], [], 0)
return bool(readable) and self.sock.recv(1, socket.MSG_PEEK) == b""
except OSError:
return True
def connect(self) -> None:
delay = 1.0
while self.sock is None:
try:
self.sock = socket.create_connection(self.address, timeout=10)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
log(f"connected to {self.address[0]}:{self.address[1]}")
except OSError as e:
with self.lock:
if self.closing:
raise
log(f"can't connect to {self.address[0]}:{self.address[1]} ({e}), retrying in {delay:.0f}s")
time.sleep(delay)
delay = min(delay * 2, 60)
def run(self) -> None:
while True:
with self.lock:
while not self.queue and not self.closing:
self.lock.wait()
if not self.queue:
break # closing, and everything is sent
line = self.queue[0]
try:
if self.sock is not None and self.peer_closed():
raise ConnectionResetError("closed by Kafkatorio")
self.connect()
self.sock.sendall(self.format(line))
with self.lock:
self.queue.popleft()
except OSError as e:
if self.sock is not None:
log(f"connection lost ({e}), reconnecting")
self.sock.close()
self.sock = None
with self.lock:
if self.closing:
break
if self.sock is not None:
self.sock.close()
def read_token(args) -> str:
if args.token_file:
with open(args.token_file) as f:
token = f.read().strip()
else:
token = os.environ.get("KAFKATORIO_TOKEN", "").strip()
if not token:
sys.exit("kafkatorio-forward: no token - set KAFKATORIO_TOKEN, or use --token-file")
if any(c.isspace() for c in token):
sys.exit("kafkatorio-forward: the token can't contain spaces")
return token
def forward(stream, sender: Sender, forward_all: bool) -> None:
"""Print each line of the server's output, and queue the packets."""
for raw in stream:
line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
try:
print(line, flush=True)
except BrokenPipeError:
pass # nobody's reading our output - keep forwarding anyway
if forward_all or line.startswith(PACKET_PREFIX):
sender.add(line)
def main() -> int:
parser = argparse.ArgumentParser(
description="Forward a Factorio server's output to Kafkatorio.",
epilog="Put the server's command after `--`, or pipe its output in.",
)
parser.add_argument("--host", default="127.0.0.1", help="Kafkatorio's host (default: 127.0.0.1)")
parser.add_argument("--port", type=int, default=12035, help="Kafkatorio's syslog port (default: 12035)")
parser.add_argument("--token-file", help="a file containing the server's token (default: $KAFKATORIO_TOKEN)")
parser.add_argument("--buffer", type=int, default=100_000,
help="packets to keep while Kafkatorio can't be reached (default: 100000)")
parser.add_argument("--all", action="store_true", help="send every line, not only the mod's packets")
parser.add_argument("command", nargs=argparse.REMAINDER, help="the Factorio server command")
args = parser.parse_args()
command = args.command[1:] if args.command[:1] == ["--"] else args.command
sender = Sender(args.host, args.port, read_token(args), args.buffer)
sender.start()
if not command:
# Piped: Ctrl+C reaches the server too, which then stops and closes the pipe. Keep going
# until then, so the last packets are sent.
signal.signal(signal.SIGINT, signal.SIG_IGN)
forward(sys.stdin.buffer, sender, args.all)
sender.close(timeout=10)
return 0
# In its own process group, so Ctrl+C only reaches the server once (passed on below), not
# twice (from the terminal, and from us).
server = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True,
)
def pass_on(signum, _frame):
# Factorio saves and stops on SIGINT/SIGTERM
server.send_signal(signum)
signal.signal(signal.SIGINT, pass_on)
signal.signal(signal.SIGTERM, pass_on)
if hasattr(signal, "SIGHUP"):
signal.signal(signal.SIGHUP, pass_on)
forward(server.stdout, sender, args.all)
code = server.wait()
sender.close(timeout=10)
return code
if __name__ == "__main__":
sys.exit(main())