Take the site name from servername only, never from the Host header

A log line without a servername used to be filed under its vhost field,
which is the Host header the visitor sent. Every invented Host header
then became a site of its own in the dashboard's Site menu. Such lines
are now filed under "(no servername)", and the client logs one warning
per log file that has them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
5 files changed
tree: 82d8ff9aeba138272e9fe19926987e15250de1cd
  1. .github/
  2. bin/
  3. churn/
  4. docs/
  5. systemd/
  6. tests/
  7. tools/
  8. .gitignore
  9. .python-version
  10. CHANGELOG.md
  11. churn.example.yaml
  12. churn.yaml
  13. pipservice-churn.service
  14. pyproject.toml
  15. README.md
  16. RUNBOOK.md
  17. server.example.yaml
  18. uv.lock
README.md

Churn

Churn watches a fleet of Apache web servers and shows, in one dashboard, how the machines are doing and who is visiting them.

It comes in two halves. A small client runs on every web server. It follows the Apache access logs, takes readings of CPU, memory, network and disk, and every five seconds sends a summary to the server. The server keeps up to thirty days of history for each machine, works out which network every visitor belongs to, sorts user agents into real browsers, honest bots, scripts and fakes, and points out origins that send suspiciously much traffic. People with root access log in through ASF OAuth and look at all of this in a browser.

This README explains what Churn does and how the pieces work. The step by step procedures for installing, upgrading and fixing it are in RUNBOOK.md.

Contents

The big picture

   web server 1                web server 2                 ... up to a hundred or so
 +----------------+          +----------------+
 | Apache logs    |          | Apache logs    |
 | /proc counters |          | /proc counters |
 |       |        |          |       |        |
 |  churn-client  |          |  churn-client  |
 +-------+--------+          +-------+--------+
         |                           |
         |   HTTPS POST every 5 s, gzip-compressed JSON,
         |   signed with the client's own ECDSA P-384 key
         v                           v
 +--------------------------------------------------------------+
 |  churn-server host                                           |
 |                                                              |
 |   Apache (TLS, churn.apache.org)                             |
 |      |  reverse proxy to 127.0.0.1:8084                      |
 |      v                                                       |
 |   churn-server (asfquart)                                    |
 |      |- client API     /api/client/register, /api/client/data|
 |      |- dashboard      /, /static/..., /api/...  (root only) |
 |      |- worker threads: verify, unpack, store, detect        |
 |      v                                                       |
 |   /opt/churn/data/                                           |
 |      registry.json            who is approved, pending, denied
 |      clients/<id>.sqlite      one file per client, 30 days   |
 |      ipdata/                  routing table, AS names        |
 +--------------------------------------------------------------+
         ^
         |  browser, logged in through oauth.apache.org, root access required
      admins

The same checkout goes onto every machine. A single systemd unit starts the right half by looking at the host name: a machine whose name contains churn-server runs the server, every other machine runs the client.

The work is split so that the web servers do as little as possible. The client only counts. Everything that needs data or judgement (which network an address belongs to, whether a user agent is genuine, whether an origin is misbehaving) happens on the server. That keeps the client small, and it means a better detection rule or a fresh routing table takes effect for the whole fleet by updating one machine.

What you need

  • Ubuntu 24.04 or 26.04, or Debian 13 or 14.
  • uv. It creates the Python environment from the lock file in this repository, and fetches a Python 3.13 of its own if the system's is a different version (the version is pinned in .python-version, so every machine runs the same interpreter no matter which distribution it is).
  • On the server only: a C compiler and the Python headers (apt install build-essential python3-dev), because the pyasn routing table library has no ready-made packages and is built from source when it is installed. The clients need neither.
  • On the server only: Apache with mod_proxy_http and mod_ssl in front of Churn, and a DNS name with a certificate. The default name is churn.apache.org.
  • Apache access logs written as one JSON object per line. See the log format below.

Churn runs as root. The client needs that to read the access logs and the counters of every Apache process; the server simply follows the same layout. Everything lives under /opt/churn:

PathWhat it is
/opt/churn/this repository
/opt/churn/churn.yamlthe client's configuration (on web servers)
/opt/churn/server.yamlthe server's configuration (on the server)
/opt/churn/data/keys, state and stored data; never in git

Trying it out on one machine

You can run both halves on a laptop without Apache, OAuth or root. This is also the quickest way to see what the dashboard looks like.

uv sync --extra server

Make a scratch directory with two small configuration files. dev_login: true switches the login off, which the server only allows on a loopback address.

mkdir -p /tmp/churn-demo/logs && cd /tmp/churn-demo
cat > server.yaml <<'EOF'
listen: {host: 127.0.0.1, port: 8611}
public_url: http://127.0.0.1:8611
data_dir: /tmp/churn-demo/server
dev_login: true
EOF
cat > churn.yaml <<'EOF'
server: {url: "http://127.0.0.1:8611"}
name: demo-web1
data_dir: /tmp/churn-demo/client
logs: {directories: [/tmp/churn-demo/logs]}
EOF

Then, from the repository, start three things in three terminals: a generator that writes realistic access logs (including one flooding address and a group of clients with faked user agents), the server, and the client.

uv run python tools/genlog.py --dir /tmp/churn-demo/logs --today --live --rate 40
uv run --extra server churn-server --config /tmp/churn-demo/server.yaml
uv run churn-client --config /tmp/churn-demo/churn.yaml

Open http://127.0.0.1:8611/. The client is waiting under Pending approvals. Approve it, and within a few seconds the Fleet and Machine views fill up. The first start of the server downloads about 37 MB of IP data, so give it a moment.

The client

The client is one process with four threads, each with one job.

                    churn-client
 +---------------------------------------------------------------+
 |                                                               |
 |  tailer thread                    main thread (every 5 s)     |
 |  ------------                     ----------------------      |
 |  finds *.log files                takes the finished tally    |
 |  reads new lines        tally     samples CPU, memory,        |
 |  notices rotation   ----------->  network, disk, Apache       |
 |  and truncation      (in memory)  builds one packet           |
 |                                         |                     |
 |  backfill thread                        v                     |
 |  ---------------                  sender thread               |
 |  once, after approval:            -------------               |
 |  reads what today's logs          signs and POSTs packets     |
 |  held before the client   ----->  live first, then the spool, |
 |  began following them             then backfill               |
 |                                         |                     |
 |                                         |  server unreachable?|
 |                                         v                     |
 |                                   data/spool/*.pkt            |
 +---------------------------------------------------------------+

Following the logs

The client scans the configured directories (by default /var/log/apache2 and /x1/logs) for files matching *.log. A directory that does not exist is skipped, so the same configuration works on every host. Every 30 seconds it looks again for files that have appeared.

Log files are rotated once a day, and the client is built around that. It remembers each file by its inode, not only by its name. When the name suddenly belongs to a different inode, the file has been rotated: the client opens the new file from the start and keeps reading the old one for another two minutes, because Apache workers that were in the middle of a request still write their last lines there. A file that shrinks (the copytruncate style of rotation) is read again from the beginning.

The position in each file is saved every 15 seconds and on shutdown. After a restart the client carries on where it stopped. If a file was rotated while the client was down, it finds the old file under its new name by inode, finishes it, and then reads the new one from the top.

The log format

Each line must be a JSON object. It may be prefixed with a marker such as <%JSON:apache_access%> ; the client simply starts reading at the first {. These are the fields Churn uses:

FieldMeaningUsed for
timewhen the request arrived, e.g. 2026-12-04T09:52:46+0000placing the request on the timeline
servernamethe virtual host's own name (%v)the site: all statistics are kept per site
vhostthe Host header the visitor sentthe “Host headers” list only
client_ipthe visitor's addressorigins, unique clients
statusthe response codestatus and error charts
bytesresponse size in bytestraffic
durationtime taken, in microseconds (%D)processing time
request_method, protocole.g. GET, HTTP/2.0the methods and protocols chart
urithe path, without the query stringmost requested and slowest paths
useragentthe User-Agent headeruser agent classification
sec_ch_ua, sec_ch_ua_platform, sec_ch_ua_mobilethe browser's client hint headerstelling real browsers from imitations
https_protocol, portTLS version, portknowing whether the request came over HTTPS
geo_countrytwo letter country codethe countries list

Fields that are missing are simply not counted. Query strings, referers and user names are in the logs but are never read, and never leave the web server.

The site comes from servername and from nothing else. The Host header is whatever the visitor chose to send, and scanners send a great many invented ones, so it is never used as a site name: if it were, the Site menu of the dashboard would fill up with names that are not sites. A line that has no servername is filed under a site called (no servername), and the client writes one warning to its log for each log file in which it finds such lines.

What the client measures about the machine

Every five seconds: CPU use in total and per core (split into user, system, I/O wait and steal), memory in use and in the page cache, swap, the three load averages, bytes in and out over the network (loopback, Docker and bridge interfaces are left out), bytes read from and written to disk, and for Apache itself the number of processes, the CPU they used and their resident memory.

When the server cannot be reached

Packets that cannot be delivered are written to data/spool/, one file each. When the server answers again the client sends the newest live packet first, so the dashboard is current straight away, and then works through the spool from oldest to newest. The spool is bounded: by default it holds 24 hours or 200 MB, whichever is reached first, and drops the oldest packets beyond that.

How data travels

This is the path of a request from the moment Apache logs it to the moment it shows up in a chart.

 Apache writes a line
        |
        v
 [client] tailer reads it  ->  tally adds it to the current 5-second count:
        |                      per site:   requests, bytes, time taken, status codes,
        |                                  methods, protocols, latency histogram
        |                      per origin: (site, address, user agent) -> requests,
        |                                  bytes, time, 4xx, 5xx
        |                      plus top paths, Host headers and countries
        v
 every 5 seconds: the tally is closed and becomes a packet, together with the
 system readings for those 5 seconds
        |
        v
 packet -> JSON -> gzip -> signed -> HTTPS POST /api/client/data
        |
        v
 [server] web loop: is this client approved?  no -> 403, body not even read
        |           yes -> put the raw bytes on a queue, answer 202 at once
        v
 [server] worker thread (each client always goes to the same worker):
        |    1. check the signature against the client's public key
        |    2. check the send time is within 5 minutes of the server's clock
        |    3. check the sequence number is newer than the last one stored
        |    4. unpack; refuse anything malformed or outside the 30-day window
        |    5. for every origin: look up network prefix and AS, classify the
        |       user agent
        |    6. add the numbers to the client's SQLite file
        v
 [server] every 30 s: write the top-list tallies to disk
          every 60 s: run the detection rules over the last 10 minutes
        |
        v
 [browser] asks for fresh numbers every 5 seconds

A few things about this design are worth knowing.

The web loop does almost nothing. Accepting a packet is a dictionary lookup and a queue insert. Signature checks, decompression, lookups and database writes all happen on worker threads, and dashboard queries run on a separate thread pool with their own read-only database connections. A slow query or a burst of packets does not hold up the rest.

Packets are added, never replaced. Each packet says “in these 5 seconds (or this minute) I counted this much”, and the server adds that to whatever it already has for the period. Because of that, it does not matter in which order packets arrive, and the same code path handles live data, the spool after an outage, and the backfill.

Old entries travel as minutes. A log line that is more than two minutes old when the client reads it (during backfill, or while catching up) is counted into a one-minute tally for the minute it belongs to instead of the live five-second one. Those “late” packets fill in the one-minute and ten-minute history. They do not appear in the five-second view, which only ever shows what was reported live.

Accepted does not mean stored. The server answers 202 before it has verified the packet. If verification fails afterwards, the client is not told. The refusal and its reason show up in the dashboard‘s Clients tab and in the server’s log instead.

What is in a packet

{
  "v": 1, "kind": "live", "start": 1796377965, "span": 5,
  "name": "web1.example.org", "version": "0.1.0",
  "site_names": ["gitbox.apache.org", ...],
  "sites":   { "gitbox.apache.org": { requests, bytes, time, status codes,
                                      methods, protocols, histogram, peak } },
  "agents":  [ [user agent, sec-ch-ua, platform, mobile], ... ],
  "origins": [ [site, address, agent, flags, requests, bytes, time, 4xx, 5xx], ... ],
  "uris":    [ [site, path, requests, bytes, time, errors], ... ],
  "hosts":   { "gitbox.apache.org": 412, ... },
  "cc":      [ [site, "BR", 17], ... ],
  "system":  { cpu, cores, memory, load, network, disk, apache },
  "stats":   { how the client itself is doing: files followed, rotations, spool }
}

On a busy machine the origin list is cut off at 5000 rows per packet. The per-site totals are counted separately and stay exact; the dashboard notes when a client's origin list was capped.

How a request is signed

Three headers go with every POST:

HeaderContent
X-Churn-Clientthe client id: the SHA-256 of the client's public key, in hex
X-Churn-Seqthe time of sending in milliseconds, always larger than the previous one
X-Churn-Signaturean ECDSA P-384 / SHA-384 signature, base64

The signature covers the text churn-v1, the request path, the sequence number and the SHA-384 of the body, each on its own line. Changing any of them invalidates it, and a recorded request cannot be played back later: the server refuses a sequence number it has already seen, and one that is more than five minutes away from its own clock.

Registration and approval

A machine cannot just start sending data. Somebody with root access has to say yes first.

   churn-client                     churn-server                      admin
        |                                |                              |
        |  first start: generate an      |                              |
        |  ECDSA P-384 key, keep it in   |                              |
        |  data/client.key (mode 0600)   |                              |
        |                                |                              |
        |-- POST /api/client/register -->|                              |
        |   public key, name, version,   |  signature proves the sender |
        |   signed with the private key  |  holds the private key       |
        |<-------- "pending" ------------|                              |
        |                                |-- shows up under ----------->|
        |   (asks again every 30 s;      |   "Pending approvals" with   |
        |    reads no logs yet)          |   name, address, fingerprint |
        |                                |                              |
        |                                |<------ Approve / Deny -------|
        |-- POST /api/client/register -->|                              |
        |<-- "approved", backfill: yes --|                              |
        |                                |                              |
        |  start following the logs      |                              |
        |-- POST /api/client/data ------>|  stored                      |
        |-- POST /api/client/data ------>|  stored                      |
        |   ... every 5 seconds ...      |                              |

The client's identity is its key. The key is created on the first start and never leaves the machine; the server only ever sees the public half. The client id is a hash of that public key, and the fingerprint shown in the dashboard is its first sixteen hex digits. Before approving, compare the fingerprint in the dashboard with the one on the machine:

/opt/churn/.venv/bin/churn-client --show-id

What the admin can do with a client:

  • Approve. Data is accepted from now on.
  • Deny. The key goes on a denied list. The client keeps asking and keeps being refused, and it does not reappear under pending. You can change your mind later (“Approve after all”) or forget the key, after which it may ask again.
  • Suspend / Resume. Packets are refused while suspended. Everything stored so far is kept and stays visible.
  • Rename. Gives the machine a name of your choosing in the dashboard.
  • Remove. Takes the client off the list. You are asked whether to keep its data file or delete it. A removed client that is still running registers again and turns up under pending.

Until a client is approved nothing it sends is stored. Its data packets are answered with 403 before the body is read.

Backfill

When a client is approved for the first time, the server tells it to backfill. The client then reads what today's log files already contained at that moment and sends it as one-minute packets, in the background and behind the live data. That way a newly added machine has a history from midnight (or from whenever the logs were last rotated) instead of starting with empty charts.

The backfill happens once per client. The server hands out the permission a single time, because reading the same lines twice would double the numbers. Set backfill: false in the client's configuration if you would rather start from now.

The server

The server is an asfquart application. It listens on 127.0.0.1:8084 and expects Apache in front of it for TLS.

                          churn-server
 +-------------------------------------------------------------------+
 |  asyncio loop (asfquart / hypercorn)                              |
 |    client API ........ checks status, queues the bytes, 202       |
 |    dashboard API ..... hands the query to the query pool          |
 |    OAuth ............. /auth, session cookie                      |
 |                                                                   |
 |  ingest workers (2 threads)      query pool (8 threads)           |
 |    verify, unpack, look up,        read-only SQLite connections,  |
 |    classify, write                 results cached for a few       |
 |    flush tallies every 30 s        seconds                        |
 |    detection every 60 s                                           |
 |                                                                   |
 |  housekeeping thread             webhook thread                   |
 |    saves the registry              posts new findings             |
 |    refreshes IP data weekly                                       |
 +-------------------------------------------------------------------+

Login

Only people whose ASF account has root access (is_root) get in. That applies to every page, every script and stylesheet, and every data and admin endpoint; a logged in user without root access gets a 403 for all of them. The two client endpoints are the only ones that work without a login, and they require a signature instead.

Churn uses the legacy ASF OAuth endpoints, as configured in server.yaml:

oauth:
  init_url: "https://oauth.apache.org/auth?state=%s&redirect_uri=%s"
  callback_url: "https://oauth.apache.org/token?code=%s"

With these, asfquart logs one warning at the first login saying that the code is sent in the URL of a GET request. That is how the legacy endpoint works and is expected here.

After the login, the OAuth service sends the browser back to the address in public_url. It has to be the name people actually use to reach the dashboard.

What is kept, and for how long

Each client has one SQLite file, data/clients/<client id>.sqlite. Nothing is shared between clients, so removing a machine is deleting a file, and a damaged file affects one machine only.

Time series are kept at three levels of detail. Every packet is added to all three at once.

LevelOne point perKept forUsed by the dashboard for
rawpacket (5 seconds)2 hours“15 min” and “1 h”
minuteminute48 hours“6 h” and “24 h”
ten-minute10 minutes30 days“7 d” and “30 d”

The top lists (addresses, prefixes, networks, user agents, paths, Host headers, countries) are counted in 10-minute buckets, kept for 48 hours, and in daily buckets, kept for 30 days. Once a bucket has closed it is trimmed to its busiest entries, so the long tail of addresses that came by once does not accumulate for a month. The sizes are in the tables section of server.yaml.

Two details about the numbers:

  • Unique clients is an estimate once there are more than 48 distinct addresses in a period (a HyperLogLog sketch, usually within a few percent). It is done this way so that “unique clients over 7 days” can be worked out by combining stored sketches, without keeping every address for a month.
  • Daily buckets are UTC days. “7 d” means today and the six UTC days before it. Charts show times in your browser's time zone.

IP data: networks, prefixes and one important caveat

The server groups visitors by the BGP prefix that announces their address and by the autonomous system (AS) that owns the prefix. It uses the same three datasets as sg2.py, fetched from the same places in the same way:

FileFromContains
pyasn.datinfra-reports.apache.org/_assetsthe global routing table: prefix to AS number
asnames.jsoninfra-reports.apache.org/_assetsAS number to operator name
ipdata.jsonsvn.apache.org (infra DNS zones)the ASF's own hosts, so they can be labelled

They are stored in data/ipdata/, downloaded at the first start and again when they are more than a week old. A download goes to a temporary file first and is renamed into place when complete, so a broken download never replaces a good file. If a refresh fails the server carries on with what it has.

The caveat about prefix sizes. The routing table contains announcements that should not be believed. The example sg2.py documents is AS32653 announcing 128.0.0.0/2, a quarter of the IPv4 internet. Taken at face value, every address in that range that has no more specific announcement would be attributed to that one AS, and it would show up as the largest “network” on every machine. Churn applies the same rule as sg2.py: an IPv4 announcement wider than a /8 is ignored (ipdata.min_ipv4_prefix: 8).

An address that then has no believable announcement is not thrown into one big “unknown” pile either. It is filed under a small block of its own, the surrounding /24 for IPv4 or /64 for IPv6, with AS 0 and the name “Unrouted or unknown network”. Private and loopback addresses are kept apart as their own group.

Lookups happen when a packet is stored, and the result is saved with the data. A later change in the routing table does not rewrite history.

User agents

Every request is sorted into one of five kinds:

KindWhat it means
browserlooks like a real, current browser, and nothing contradicts it
bota crawler that says what it is (Googlebot, bingbot, GPTBot, ...)
toola script or library (curl, python-requests, Go-http-client, ...) or no user agent at all
fakedclaims to be a browser or a well-known crawler, but something gives it away
othernone of the above

A user agent is counted as faked for one of these reasons, and the dashboard shows how often each occurred:

  • It claims to be Chrome, Edge or Opera over HTTPS but did not send the Sec-CH-UA header those browsers always send.
  • It sent Sec-CH-UA, but the header disagrees with the User-Agent (another engine, version, brand or platform), or names HeadlessChrome.
  • It sent Sec-CH-UA while claiming to be Firefox or Safari, which never send it.
  • The version is from the future, or more than about five years old.
  • Details that modern Chrome freezes to fixed values are not frozen.
  • It says it is Googlebot, bingbot or another crawler with known networks, but the address does not belong to that operator's AS. This is the one check that needs the IP data, which is why classification happens on the server.

The hint checks only apply when the log actually records the sec_ch_ua fields. A log format without them still gets browsers, bots and tools told apart, just with fewer ways of spotting an imitation.

The list of current browser versions is not downloaded from anywhere. Chrome and Firefox release on a steady schedule, so the classifier works out what “current” means from today's date.

Findings

Once a minute, for each machine, the server looks at the last ten minutes and checks every address, prefix and AS against these rules:

RuleFires whenDefault
high requestsmore requests per minute than the limit300 per address, 1200 per prefix, 3000 per AS
high trafficmore megabytes per minute than the limit200 / 500 / 1000
outsized shareone origin takes more than its share of all requests10 % / 20 % / 35 %
far above typicalan address is many times busier than the median address20 times
faked agentmany requests with a faked user agent50 requests
mostly errorsnearly everything it asked for was answered with a 4xx80 % of at least 200

The first two are fixed limits. The next two compare an origin with everyone else on the same machine at the same time, so they adapt to how busy the machine is; they only apply above a minimum volume so that a quiet site does not produce noise.

A finding is a notice when only “faked agent” or “mostly errors” fired, a warning when one of the volume rules fired, and critical when a volume rule was exceeded three times over. There is one finding per origin and machine. It stays open while the rules keep firing and closes by itself after fifteen quiet minutes. Addresses from the ASF's own host list are exempt by default, and you can exempt AS numbers (your monitoring provider, for instance) with detection.exempt_asns.

Webhook

If webhook.url is set, new findings are posted there as JSON:

{
  "text": "Churn findings:\n[critical] web1: Address 45.148.10.77 (AS48090), DMZHOST - TECHOFF SRV LIMITED, GB: 1,150 requests per minute (limit 300)\nhttps://churn.apache.org/#findings",
  "findings": [ { "level": "ip", "key": "45.148.10.77", "severity": "critical", "client": "web1", "details": { } } ]
}

The text field is what Slack and compatible services display. Several findings within 30 seconds go out as one message. Only new findings are posted; a finding that stays open or closes does not produce another message.

The dashboard

There are five views.

  • Fleet shows all machines together: how many are reporting, requests and errors per second, traffic, CPU per machine, one row per machine with its current numbers, and the top networks, prefixes, addresses and user agents added up over the whole fleet.
  • Machine shows one machine, and optionally one site on it. System charts (CPU, per-core heat map, load, memory, network, disk, Apache), visitor charts (requests, processing time percentiles, status classes, errors, unique clients, traffic), request origins by AS, prefix and address, user agents, and the most requested and slowest paths. The Site menu lists the virtual hosts the machine's logs name in their servername field.
  • Findings lists what the detection rules turned up, currently and in the past.
  • Clients is the list of approved machines, where they are renamed, suspended and removed.
  • Pending approvals shows who is waiting and who was denied.

The period buttons (15 min to 30 d) apply to whatever is on screen. Every chart has a “Table” button that shows the same numbers as text. The address in the browser keeps track of view, machine, site and period, so a link to a particular view can be passed around.

The page refreshes itself by asking for new data every five seconds for the short periods and less often for the long ones. It stops asking while its tab is in the background.

All of it is served from the Churn server itself. There is no JavaScript framework, no font, no map tile and no analytics script from anywhere else, and a Content-Security-Policy header tells the browser to refuse any such request should one ever creep in. Looking at the dashboard tells no third party that you did.

The lists of where requests come from

The Fleet view and the Machine view both have three lists: networks (autonomous systems), network prefixes, and addresses. Networks and prefixes sit side by side and the address list, which has the most columns, runs across the full width below.

Putting a list in order. The headings of four columns can be clicked: Requests, Traffic, Errors and Client types. A click puts that list in the order of that column, and a second click on the same heading turns the order around. An arrow next to the heading shows which column is in charge and which way round. Each list has its own order, and the server does the sorting, because only the top of a list is sent to the browser and the top is a different set of origins in every order.

OrderWhat it comparesStarts with
Requeststhe number of requeststhe most
Trafficthe bytes sent backthe most
Errorsthe share of requests answered with a 4xx or 5xxthe highest share
Client typesa score for who was behind the requests, see belowthe lowest score

The client type score. Every request counts for something, depending on what kind of client made it:

Kind of clientCounts
a real browser+1.0
a tool or script0.0
a bot or crawler that says what it is-0.5
a faked user agent-1.0
other0.0

An origin‘s score is the sum over its requests divided by the number of requests, so it runs from +1.0 (nothing but real browsers) to -1.0 (nothing but faked user agents). The list starts with the lowest score, because those are the origins worth a look; click the heading again for the most browser-like ones. Hovering over an origin’s coloured bar shows the counts and the score.

The two orders that compare a share (Errors and Client types) leave out origins with fewer than 10 requests in the period. Without that, an address that sent a single request and got a 404 would top the list at 100 %. The card says so next to its title while one of these orders is in use. Among origins with the same share, the busier one comes first.

The colours. The small bar in the Client types column is split by kind of client, and a legend above the lists gives the colours: browsers blue, bots and crawlers green, tools and scripts yellow, faked user agents red, other grey. The same colours are used in the charts of the User agents section.

Grouping addresses. The address list has a switch between “One by one” and “Grouped by /24 and /56”. Grouped, every IPv4 address is filed under its /24 and every IPv6 address under its /56, and a row shows how many different addresses of that block were seen. This is for the case the other lists miss: a handful of neighbouring addresses all doing the same thing, each too quiet to stand out alone, inside an announced prefix far too large to single them out. It is a different grouping from the announced prefixes of the middle list, and the block sizes are fixed. The grouped list can be put in order the same way as the others.

The share bar. The User agents section of the Machine view starts with one bar across the page, split into the kinds of client by their share of the period. A switch chooses whether the shares are of all requests or of the traffic sent, and the figures are written out underneath.

Security

A summary of what protects what:

  • Who may look. OAuth login with is_root, enforced on every page, asset and API call.
  • Who may send. Only keys an admin approved. Each request is signed; a stolen recording of one cannot be replayed.
  • Changing things. Approve, deny, suspend, rename and remove need a logged in root user, and a request header that only the dashboard's own script sends. The session cookie is SameSite=Strict. Together these keep another website from triggering an admin action in your name.
  • What clients can do. A client can only add to its own file. It cannot read anything back, and it cannot write to another client's data, because the file is chosen by the id that its signature proves.
  • Limits. Packets are capped in size before and after decompression, the number of pending registrations is capped, and a full queue makes the server answer “come back later” instead of growing without bound.
  • On disk. The client‘s private key, the server’s registry and the cookie-signing secret are created with mode 0600. data/ is in .gitignore.
  • Privacy. Addresses and user agents of visitors are stored on the Churn server for up to 30 days. Query strings, referers and authenticated user names are never sent by the client.

dev_login switches the login off entirely. It exists for development. The server refuses to start with it unless it listens on a loopback address, and refuses any request that came through a proxy while it is on. Do not use it on a real server.

Configuration

Both programs read a YAML file. Every setting has a default, so a file only needs to contain what differs. The two example files list every setting with an explanation:

A setting the program does not know is reported in the log at start-up, which catches most typos.

Which half starts is decided by bin/churn-launch, which the systemd unit runs. It looks for churn-server in the host name. To overrule that, put CHURN_ROLE=server or CHURN_ROLE=client in /etc/default/churn.

Working on Churn

churn/
  config.py            defaults and YAML loading for both halves
  wire.py              what client and server must agree on: paths, signing, encoding
  client/
    tailer.py          following log files through rotation
    tally.py           parsing lines, counting, building packets
    sysstats.py        CPU, memory, network, disk, Apache processes
    transport.py       registration, sending, the spool
    main.py            the threads and the 5-second loop
  server/
    app.py             the asfquart application and all routes
    ingest.py          worker threads, live overview, webhook
    store.py           the per-client SQLite file
    queries.py         what the dashboard asks for
    detect.py          the finding rules
    asn.py             IP datasets and lookups
    useragents.py      the user agent classifier
    registry.py        approved, pending and denied clients
    sketch.py          unique-visitor estimates
    static/            the dashboard: one HTML page, hand-written JS and CSS
bin/churn-launch       picks server or client by host name
systemd/churn.service  the unit file
tools/genlog.py        writes realistic test logs
tests/
  client/              tests that need nothing but the client
  server/              tests of the server and the web layer
  test_wire.py         the signing and packet code both halves share
  test_pipeline.py     a log line through the client into the server and back out
.github/workflows/     the checks GitHub runs (see below)
docs/bbq/              the design decisions this was built from

Tests and type checks

Run all the tests with:

uv run --extra server pytest

They cover signing, log following through rotation and restarts, tallying, the full path from a log line to a dashboard query, detection, the registry, and the web layer including who is let in. Nothing in the test suite uses the network.

The code carries type annotations, and mypy checks that they hold together:

uv run --extra server mypy

Its settings are in pyproject.toml. It also looks inside functions that have no annotations of their own, so a mistake such as treating a value that may be None as if it were always there is reported wherever it happens.

What GitHub checks

Two workflows run the same tests and type checks on GitHub, on every pull request and on every push to main. Each one only starts when something it covers has changed.

WorkflowStarts when these changeJobs
Clientchurn/client/, tests/client/client tests; type checks; “server still reads the client's packets”
Serverchurn/server/ (dashboard files included), tests/server/server tests; type checks

Both also start when something they share changes: churn/config.py, churn/wire.py, the shared tests, pyproject.toml, uv.lock, .python-version, or the workflow files themselves. A change to the README alone starts neither.

Two things about them are deliberate. The client‘s tests and type checks run in an environment without the server’s dependencies, so a client that accidentally starts to need asfquart or pyasn fails there before it fails on a web server. And the client workflow has one job that does install the server's side: it runs tests/test_pipeline.py, because the likeliest way to break the server is to change what the client puts in a packet.

The steps all jobs share (Python from .python-version, a pinned uv, the locked dependencies) are in .github/actions/setup/action.yml. The workflows use only actions published by GitHub itself (actions/checkout, actions/setup-python, actions/cache); uv is installed with pip, so there is no third-party action to review or pin.

To run locally what a workflow runs, look at its run: lines. For the client, for example:

uv run pytest tests/client tests/test_wire.py
uv run mypy churn/client churn/config.py churn/wire.py

The server is started with its own small runner and not with asfquart's runx(). runx() watches the source files and restarts the process when one changes, which is useful on a laptop but would restart the collector in the middle of a git pull on a server. Restarts are left to systemd.

The chart code (static/js/charts.js), the base stylesheet and the user agent classifier started out as copies from the poneestats project and were adapted here for several machines and sites. They are plain files in this repository now and have no link back to it.

Changes are recorded in CHANGELOG.md.

Known limits

These are things Churn does not do, or does imperfectly, that are better known in advance.

  • A crash can double-count a few seconds. The client saves its read positions every 15 seconds. After a clean stop nothing is lost or repeated. After a crash or a power cut it resumes from the last saved position and counts up to 15 seconds of lines a second time.
  • The backfill is one attempt. If the client is stopped while backfilling, the rest of that day's earlier history is not fetched later.
  • A log file that first appears while the client is stopped is followed from its end when the client starts again. What was written to it before that is not read.
  • Clocks matter. A client whose clock is more than five minutes off has all its packets refused. Run NTP.
  • Top lists are top lists. Closed periods keep their busiest entries only. An address that made three requests last Tuesday is included in that day's totals but can no longer be looked up individually. Putting an origin list in another order rearranges what was kept; it cannot bring back an origin that was too quiet to be kept. What is kept is chosen by requests, by bytes and by faked requests, so a quiet address with nothing but errors may be missing from the order of errors.
  • Across the fleet, an origin has to stand out somewhere. For the fleet-wide origin lists every machine first names its own front-runners in the order asked for, eight times as many as the list shows (200 with the default tables.top_n of 25). The best of those are then looked up on every machine and added together. The figures shown for an origin are therefore complete, but an origin that no single machine names is not considered, even if it would rank overall.
  • Fleet-wide top lists get slower with size. They are computed by asking every client's file and adding the answers. With a hundred busy machines the 24-hour fleet tables can take a few seconds; the result is cached.
  • Disk use has not been measured over a full month. A test client at about 75 requests per second from a few thousand addresses reached 45 MB in its first twenty minutes, backfill included. Growth flattens as periods close and are trimmed, but watch data/clients/ in the first weeks and adjust the tables settings if needed.
  • One server. There is no replication. The runbook describes backing up and moving it.