Time: an evening. Cost: nothing, if you have an old computer and a database already. Difficulty: you need to be comfortable in a terminal and editing a config file. Some SQL helps; you won't have to write any.
My always-on machine is Nexus, a Raspberry Pi 5. It runs the databases, the dashboards and a dozen small services, and its one job is to be up and quick. The moment I ask it to render a book as a PDF or make preview frames from an hour of video, it stops being that machine for several minutes.
So it doesn't do those jobs. It writes them down, and a second machine does them. That machine is Osgiliath, a 2018 all-in-one with a low-power four-core Pentium and 7.5GB of memory. It was Lynne's old all-in-one, until it reached the end of its life as hers. Since September it has rendered 1,128 preview images and clips for the catalogue where my agents file everything they make, as well as the PDF and ebook editions of my books, and since this Tuesday a new kind of job for fetching media. It's working while I write this.
The interesting part isn't which machine. Any old computer will do. It's how the work gets from one machine to the other, and that's where people reach for a message broker they don't need. This guide builds the whole thing, small enough to read in one sitting: a queue that is just a table, a worker, a way to send it jobs, a way to rescue jobs when a worker dies, and a check that tells you whether the work is actually getting done. I built it from scratch on the same two machines on Thursday 19 November 2026, then pulled the plug on it in every way I could think of. Every number below comes from that afternoon.
Verified 19 November 2026: MariaDB 10.11.18 on a Raspberry Pi 5 (Debian 12, Python 3.11.2); worker on Debian 13.7 with Python 3.13.5; PyMySQL 1.2.4; Pillow 13.0.0.
At the end of this you will have
- A job queue that is one table in a database you already run. No broker, no Redis, no cloud service.
- A worker on a second machine that takes jobs, does them and records the result, and only takes jobs it actually knows how to do.
- A one-line way to send a job from any machine that can reach the database, and optionally wait for the answer.
- A safe claim: run as many workers as you like on as many machines, and no job gets done twice. I measured it both ways.
- A sweeper that rescues jobs from a worker that died halfway through, without ever recycling a job forever.
- A status check that answers "is the work getting done?", not just "is the worker running?". Those are different questions, and the second one is the one most tools answer.
- Two jobs that work out of the box, checksums and thumbnails, and the pattern for adding your own.
Why a table and not a message broker
Message brokers are good software for problems you probably don't have: millions of messages, many teams, delivery guarantees across data centres. For "the small machine has some heavy jobs for the big one", a table does everything you need, and it has two advantages a broker doesn't. You can see the whole queue with one SELECT. And every job leaves a row behind: who asked, when, which machine did it, how long it took, what came back, and what went wrong. That history is how you answer questions later, and it costs nothing.
If you already run MariaDB or MySQL, you already run a job queue. You just haven't made the table yet.
Before you start
Have
- An always-on machine with MariaDB 10.6 or newer, or MySQL 8.0 or newer. Older versions lack the one feature this depends on. Check with
mariadb --versionormysql --version. A Raspberry Pi is plenty; mine is. - A second computer for the heavy work. Anything that runs Python 3.9 or newer. It doesn't need to be fast; it needs to be left alone. Mine is a seven-year-old all-in-one.
- Python 3 on both machines.
python3 --version. - The two machines on the same network, and permission to change the database's settings.
Decide
- What's heavy for you. OCR, converting documents, rendering PDFs, making thumbnails or video previews, checksumming backups, anything that pins a processor for minutes. The kit comes with two simple jobs so you can prove the queue works before you write your own.
- Where the files live. This is the decision people skip. A job says "do this to
/data/scan.pdf", and that path has to mean something on the worker. Either the files are already on the worker, or the job fetches them first. Mine fetches them over SSH. I don't share a folder between the machines, on the advice of Scotty, the agent who runs my servers: a network share that nothing is using doesn't stay free, because when it quietly dies after a reboot every job that touches it fails in a way that looks like the job's fault: a hang, or an empty folder where the files used to be, so the job reports "file not found" or "nothing to do". - Which jobs matter more. Every job has a priority, and lower numbers go first. The default is 5. You can ignore this until the day a big batch is holding up something urgent.
Step 1: Make the queue
On the always-on machine, create a database and a user for the queue, then the two tables. Connect as an administrator (sudo mysql on most Linux systems) and run this, with your own password:
CREATE DATABASE job_queue;
CREATE USER 'queue'@'%' IDENTIFIED BY 'choose-a-long-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON job_queue.* TO 'queue'@'%';
The '%' lets that user connect from other machines. It can only touch this one database, and only rows, not tables. Then load the tables from the kit:
sudo mysql job_queue < schema.sql
That file is short enough to read in full, and worth reading, because it's the whole design:
CREATE TABLE jobs (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
job_type VARCHAR(40) NOT NULL, -- which handler runs it
input JSON NOT NULL, -- what it needs, e.g. {"path": "/data/scan.jpg"}
status ENUM('queued','claimed','complete','failed') NOT NULL DEFAULT 'queued',
priority TINYINT NOT NULL DEFAULT 5, -- lower runs first
submitted_by VARCHAR(60) NOT NULL, -- who asked
claimed_by VARCHAR(60) NULL,
claimed_at DATETIME NULL,
completed_at DATETIME NULL,
attempts TINYINT UNSIGNED NOT NULL DEFAULT 0, -- counted when a job is CLAIMED
result JSON NULL, -- small: a path, a size, a checksum
error TEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY idx_next (status, priority, created_at)
);
CREATE TABLE workers (
name VARCHAR(60) PRIMARY KEY,
heartbeat_at DATETIME NOT NULL,
state JSON NOT NULL -- what it's doing, and what it can do
);
Two columns look like bookkeeping and aren't. submitted_by records who asked. The moment more than one thing sends work, "where did all these jobs come from?" stops being answerable any other way, and you'll want the answer most on the day something floods the queue. attempts is counted when a job is taken, not when it fails, and that one decision is what stops a job that crashes its worker from going round forever. More on that in "How it works".
Finally, the database has to accept connections from the network. On Debian-style systems, find bind-address in the files under /etc/mysql/, set it to 0.0.0.0, and restart the database. If it's already set that way, leave it. Don't open the database port to the internet: this is for machines in your house.
What you should see: sudo mysql job_queue -e "SHOW TABLES" lists jobs and workers.
Step 2: Put the kit on both machines
Download it: a-second-pair-of-hands.zip. Copy it to both machines, unzip it, and in the kit folder on each:
python3 -m venv .venv
.venv/bin/pip install pymysql pillow
That took 10 seconds on Osgiliath. Pillow is only needed on a machine that will make thumbnails. Leave it out and that machine simply won't offer them, which the next steps will show you.
a-second-pair-of-hands/
schema.sql the two tables
queue_common.py connecting (and waiting), and the one rule for giving up
worker.py runs on the second machine: takes jobs and does them
enqueue.py runs anywhere: puts a job on the queue
sweep.py runs every few minutes: rescues jobs from workers that died
status.py is the work getting done? exits 1 if not
queue-worker.service makes the worker start with the machine
config.example.json copy to config.json
Copy config.example.json to config.json on each machine and fill in your database's address, the user and password from step 1, and job_queue. That file holds a password, so make it readable only by you: chmod 600 config.json.
What you should see: on the second machine, .venv/bin/python -c "from queue_common import connect; connect()" prints nothing and returns. If it prints database unreachable … retrying, the address, password or bind-address is wrong; press Ctrl+C and check them.
Step 3: Start a worker
On the second machine, run it in the foreground first so you can watch:
.venv/bin/python worker.py
What you should see:
Osgiliath: worker up, handling sha256, sleep, thumbnail
The worker names itself after the machine, and tells you exactly which job types it can do. sleep is a job that takes as long as you tell it, for testing. If thumbnail is missing, Pillow isn't installed in this machine's .venv.
Step 4: Send it a job
On the always-on machine, or any machine with the kit and a config.json, ask the worker to checksum a file that's on its disk, and wait for the answer:
.venv/bin/python enqueue.py sha256 '{"path": "/tmp/hands-1g.bin"}' --wait
Mine was a 1GB file. This is what came back:
queued job 1 (sha256)
complete after 7.0s, 1 attempt(s)
{"sha256": "c6549066de62aaf9…", "bytes": 1073741824, "seconds": 1.99}
Two seconds of work, seven seconds door to door. The difference is the worker's polling: when the queue is empty it looks every five seconds, so a job can wait up to five seconds to be noticed. For jobs that take minutes, that doesn't matter. If it matters to you, make POLL smaller in worker.py; every look is one small query, about 17,000 a day at five seconds, which an idle database won't notice.
Now try one that can't work, a file that doesn't exist:
.venv/bin/python enqueue.py sha256 '{"path": "/tmp/no-such-file.iso"}' --wait
queued job 3 (sha256)
failed after 5.0s, 1 attempt(s)
Permanent: no such file on Osgiliath: '/tmp/no-such-file.iso'
What you should see: the first job complete, the second failed after one attempt, with a message that names the machine. One attempt matters. A missing file won't appear if you try again, and retrying it is just a slower way of being wrong.
Step 5: Ask whether the work is getting done
.venv/bin/python status.py
To see it catch something, first send a job type no worker handles: .venv/bin/python enqueue.py ocr '{"path": "/tmp/scan.pdf"}'. This is what it printed for me:
Workers
Osgiliath heartbeat 0s ago idle done 2 failed 1 handles sha256, sleep, thumbnail
Queue queued 1 claimed 0 complete 2 failed 1
sha256 1 done, longest 2s
thumbnail 1 done, longest 0s
Checks
PASS a worker has checked in recently 1 of 1 within 120s
FAIL every waiting job type has a live worker nobody handles: ocr
PASS work is moving oldest waiting job: 0s
PASS nothing stuck mid-job 0 claimed over 15 min ago
Failed in the last day: 1
job 3 sha256 after 1 attempt(s): Permanent: no such file on Osgiliath: '/tmp/no-such-file.iso'
That FAIL is the reason the worker publishes what it can do. Without it, a job nobody can handle looks exactly like a job that hasn't been reached yet, and it sits there looking patient until somebody wonders where their PDF went. Delete the test job (sudo mysql job_queue -e "DELETE FROM jobs WHERE job_type = 'ocr'" on the database machine) and run it again for four PASSes.
What you should see: four PASS lines, and an exit code of 0 (echo $?). It exits 1 if anything fails, so you can run it from cron and get told.
Step 6: Make it permanent
Stop the foreground worker with Ctrl+C and make it a service, so it starts with the machine and comes back if it dies. Edit queue-worker.service: put your username in User= and your kit folder in the two paths. Then:
sudo cp queue-worker.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now queue-worker
Two lines in that file are worth knowing about. Restart=always with RestartSec=5 brings the worker back five seconds after it dies. I killed mine with kill -9 and it was back in exactly five. MemoryMax=4G and CPUQuota=75% stop a runaway job from taking the whole machine with it. They're the same limits the real worker on Osgiliath runs with.
If you don't have sudo on the worker and are tempted to run it as a user service (systemctl --user) instead, know one thing first: a user service stops when you log out, unless "lingering" is turned on for your account (loginctl enable-linger, which usually needs an administrator once). I found this out the obvious way. My test worker ran perfectly while I was logged in, passed the restart test, and was stopped cleanly by the system twelve seconds after I closed my session. Nothing failed. It just wasn't there any more.
Then, on the always-on machine, run the sweeper every five minutes. crontab -e and add:
*/5 * * * * cd /home/YOU/second-pair-of-hands && .venv/bin/python sweep.py
The sweeper looks for jobs that were taken more than fifteen minutes ago and never finished, which means the worker died mid-job, and puts them back, or gives up on them if they've had their three attempts. Fifteen minutes has to be longer than your slowest real job, or the sweeper will steal jobs that are still running. Don't guess it: status.py prints the longest run of each job type, so set it from that with plenty of room, using --stale. If you change it, change STALE_CLAIM in status.py to match.
What you should see: systemctl status queue-worker says active (running), with its memory limit shown, and status.py still shows a recent heartbeat.
Step 7: Add your own job
A job type is one Python function in worker.py that takes the job and returns a small dictionary. Here's the checksum one:
def do_sha256(job):
path = need_file(job) # check the input FIRST
h, n, t = hashlib.sha256(), 0, time.time()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1 << 20), b''):
h.update(chunk)
n += len(chunk)
return {'sha256': h.hexdigest(), 'bytes': n, 'seconds': round(time.time() - t, 2)}
HANDLERS = {'sha256': do_sha256, 'sleep': do_sleep}
Add yours to HANDLERS and restart the worker, and it starts offering the new type straight away. Three rules make the difference between a handler that's easy to live with and one that isn't:
- Check the input before doing anything. If the input can never work (no such file, not an image, a page number past the end), raise
Permanentwith a message a person can act on. The job fails once, clearly. Anything else you raise is treated as a temporary problem and gets another go. - Return something small. A path, a size, a checksum, a page count. The result column is for coordination, not storage. The thumbnail handler writes its image to disk and returns where it put it. Keep the queue table small and boring.
- If the tool can't run twice at once, lock inside the handler. LibreOffice, for one, corrupts its profile if two copies share it. My real worker converts documents one at a time behind a lock file. The queue doesn't need to know.
Don't register a job type you haven't written yet. A stand-in that says "not implemented" is a promise the worker can't keep, and the status check will believe it. If the function isn't there, the worker doesn't claim the job, and status.py says nobody handles it, which is true.
What you should see: after a restart, the worker's first line lists your new type, and so does its row in status.py.
How it works
The claim: eight words and a check
Everything depends on this. When two workers reach for the next job at the same moment, only one may get it. The obvious way (find the oldest queued job, then mark it taken) has a gap between the two steps, and two workers can both fall into it. The kit closes the gap like this:
SELECT id, job_type, input FROM jobs
WHERE status = 'queued' AND job_type IN (…the types this worker handles…)
ORDER BY priority, created_at
LIMIT 1 FOR UPDATE SKIP LOCKED;
UPDATE jobs SET status = 'claimed', claimed_by = ?, claimed_at = NOW(), attempts = attempts + 1
WHERE id = ? AND status = 'queued';
Both run inside one transaction. FOR UPDATE SKIP LOCKED tells the database: lock the row I picked, and if another worker has already locked one, don't wait for it, skip it and give me the next. Workers never queue up behind each other and never pick the same row. The AND status = 'queued' on the update, plus checking that it changed exactly one row, is the belt to go with those braces: claim it, then check you won.
I measured what that buys. Four workers, three on Osgiliath and one on the Pi, against 400 tiny jobs: all 400 finished in five seconds, and the workers' own logs show every job ran exactly once. The four workers took 124, 119, 117 and 40 of them. Then I ran the same test with the obvious version, no SKIP LOCKED and no check: 654 runs for 400 jobs. 226 jobs ran twice and 14 ran three times. And the table said all 400 were complete, with nothing to show anything had gone wrong. Those were deliberately tiny jobs, which is the worst case. With real jobs taking minutes the collisions are rarer, and that's worse, because rare is how a bug survives.
Counting attempts when a job is taken
A worker can die without any chance to record why: kill -9, a power cut, a kernel update. If attempts were counted when a job failed, a job that kills its worker would never fail. It would be rescued, retried, kill the worker again, forever. So the kit counts an attempt when a job is taken, and both the worker (when a job raises an error) and the sweeper (when a worker vanished) hand the job to the same function, finish_failed, which puts it back or gives up based on that count. There is exactly one place the rule lives, so nobody can skip it.
The heartbeat says what the worker can do
Every thirty seconds, and whenever it starts or finishes a job, the worker writes one row: busy or idle, which job, how many done and failed, and the list of job types it can handle. That's how the always-on machine can tell, without logging in to anything, that the worker is there and whether anyone can do the job you're about to send. That list is the best line in my real worker, and it was nearly an afterthought.
When the database goes away
The worker connects through connect(), which, when the database can't be reached, waits and tries again, doubling the wait each time up to a minute, for up to ten minutes before giving up. If a connection drops while it's running, the worker notices, reconnects and carries on. Why both matter is the first item in the next section.
The ways it lied to me
Every one of these reported success, reported nothing, or looked healthy while something was wrong. Most are from my real worker over the summer, and every fix is built into the kit. The last is from this afternoon.
- An outage turned into five thousand errors and no alarm. My worker connected to the database once, at startup, and if that failed it died. The service manager restarted it five seconds later, it died again, and round it went. I've counted the archived error log myself: 5,284 fatal errors, and 5,273 of them say one thing, that the database machine couldn't be reached. Nothing alerted, because from the service manager's point of view, restarting a crashed program is the restart policy working perfectly. Fix: when the database is away, wait for it. The kit's
connect()does. Started against a database that doesn't exist, it wrote seven lines in seventy seconds, each saying when it would try next, instead of a dozen crashes a minute. - The other eleven were one line in the wrong place. Under the noise were 11 errors of a different kind:
MySQL server has gone away, from a connection that had died while the worker was running. The code that began a transaction sat on the line just above thetryblock written to handle exactly that failure. And the obvious fix is a trap of its own: catch the error and carry on, and the worker stays up forever with a dead connection, heartbeat cheerful, claiming nothing, looking perfectly healthy. Fix: catch it and reconnect. I tested the kit the way the real fix was tested: I killed the worker's connection from the database side. It loggedlost the database … reconnectingand finished the next job in seven seconds, with no restart. - The fix existed, and nothing used it. One of my agents wrote a proper reconnecting helper for the real worker. It was correct and documented, and for days nothing called it. Everybody looks for the missing fix; almost nobody checks whether the one that exists is connected to anything. Fix: prove a fix by breaking the thing on purpose and watching it recover, as in the item above, not by reading the code.
- Two rescuers, two sets of rules. In my worker, a job that raised an error went through code that capped retries at three. A job that made the worker die was rescued by the sweeper, which had no cap at all and could only ever put the job back. So the jobs most likely to be poison were the ones that could recycle without limit. Fix: one function decides, and every rescuer calls it. I tested it with a job that I killed the worker on every time it ran: attempt one, back on the queue; attempt two, back on the queue; attempt three,
failed, for good. - Bad input failed three times, slowly. A job pointing at a file that didn't exist was claimed, failed, retried, failed, retried and failed. The producer deliberately didn't check the file, reasonably, since it couldn't see the worker's disk, so nobody did until the worker tripped over it. Fix: the worker checks input before working, and input that can never work fails once, permanently, with a message naming the machine.
- A job type that could never work was offered anyway. My worker registered a job type whose handler said "not yet implemented". Anything sent to it would have been tried three times by a worker that could never do it, and the queue had no way to tell "failed" from "can never succeed". Fix: in the kit, if the function isn't written, the type isn't offered, and the status check says nobody handles it. My real worker now fails that type once, as permanent.
- Mine, this afternoon: a test that didn't run looked like a test that failed. To test the poison job I killed the worker with
pkill -f "python worker.py"over SSH. The command running that kill had the words "python worker.py" in it too, so it matched and killed itself, and the step that should have restarted the worker never ran. Three rounds reported the job sitting there untouched, which looked exactly like the cap not working. Fix: put the start and kill commands in a small script so they don't match themselves, and check a test did what you think before believing what it says. The rerun is the one above.
The check that catches all of them
Every item in that list is a version of the same mistake: confusing "running" with "doing the job". A worker in a crash loop is running. A worker with a dead connection is running. A worker that can't handle the job you sent is running. So status.py doesn't ask whether the worker is running. It asks four questions about the work:
- Has a worker checked in within the last two minutes?
- Does every job type that's waiting have a live worker that can do it?
- Is the oldest waiting job less than ten minutes old? In other words, is work moving?
- Is anything stuck mid-job for longer than the sweeper allows?
Run it from cron on the always-on machine, every fifteen minutes say, and have cron mail you, or pipe it into whatever alerting you already have, when it exits 1. Then check the check. A check that has never failed hasn't been tested, so these are the drills I ran against the kit this afternoon. They're worth running against yours once, before you rely on it:
| What I did | What should happen | What happened |
|---|---|---|
| Sent a job type no worker handles | status.py fails | FAIL nobody handles: ocr |
| Sent a job for a file that doesn't exist | Fails once, permanently | failed, 1 attempt, message names the machine |
| Four workers, 400 jobs | Every job runs once | 400 runs, all once, in 5 seconds |
Same, without SKIP LOCKED | (the control) | 654 runs; table still said 400 complete |
kill -9 on the worker mid-job, then swept | Job goes back and finishes | finished on attempt 2 |
| Killed the worker every time one job ran | Gives up after 3 attempts | queued, queued, failed |
| Killed the worker's connection at the database | Reconnects, no restart | reconnected; next job done in 7 seconds |
| Started a worker with the database unreachable | Waits, doesn't crash | 7 lines in 70 seconds, backing off to a minute |
kill -9 on the worker service | Back within 5 seconds | back in exactly 5 |
What it costs
Money: nothing, if you have the machines. MariaDB, Python, PyMySQL and Pillow are free, and my second machine is Lynne's old all-in-one.
Setup: an evening. Most of it is step 1 and getting the two machines to talk. The software installs in ten seconds.
Running it: almost nothing. Idle, looking at the queue every five seconds, the worker on Osgiliath used 25MB of memory and 0.29 seconds of processor time in ten and a half minutes, which is about forty seconds a day. Busy, it uses whatever the job needs, up to the limits you set in step 6. The checksum of a 1GB file took two seconds; four workers got through 400 small jobs in five.
My real worker on Osgiliath, which carries eight job types and the heavier tools behind them, was using 10.9MB of memory and had used 32.6 seconds of processor time in the 23 hours since its last restart.
Getting an assistant to do this for you
You don't need to write any of it yourself. The useful prompts are about the rules, and an assistant will follow them well if you state them:
- "Add a job type
ocrtoworker.pythat runsocrmypdfoninput.pathand writes the result next to it. Check the file exists and is a PDF before starting, and raisePermanentif not. Return the output path and the page count, nothing else." - "My files are on the always-on machine, not the worker. Change the handler to fetch the file over
scpinto a temporary folder first, delete it afterwards, and treat a failed fetch as temporary, not permanent." - "Write me a test for the sweeper: queue a
sleepjob for 600 seconds, kill the worker when it's claimed, runsweep.py --stale 0, and repeat. Show me the attempts going 1, 2, 3 and the job ending upfailed."
The last one is the habit to keep. When an assistant writes recovery code, ask it to break the thing on purpose and show you the recovery. The real worker's reconnect fix was correct for days before anything called it, and reading it wouldn't have told you.
What I actually use it for
Nexus never renders anything. When one of my agents finishes a book, the PDF and the ebook are built on Osgiliath: 19 PDFs and 14 ebooks since July, each one a row I can look back at. When an agent makes a video, a picture or a map, it goes into a catalogue my agents call the Wharf, and Osgiliath makes the preview frames. That's 1,128 jobs since the middle of September, and it's the reason I can find a piece of footage from a thumbnail instead of reading filenames. This week a new job type for fetching media went in alongside the others, without touching the queue.
The point isn't speed. Osgiliath is slow. The point is that the always-on machine is never the one doing the heavy lifting, so it's always quick, and the old machine doesn't care how long anything takes because nobody's sitting at it. The job queue that makes that work is one table, and it'll outlast several fashions in message brokers.
The code
Everything is in the zip. These two files are the heart of it, here so you can read them before you run them, which you should do with anything from the internet, mine included.
worker.py
"""worker.py — runs on the second machine. Takes jobs off the queue and does them.
python worker.py # run until stopped
python worker.py --once # take one job if there is one, then exit (handy for testing)
"""
import hashlib
import json
import os
import socket
import sys
import time
import pymysql
from queue_common import connect, finish_failed
NAME = os.environ.get('WORKER_NAME') or socket.gethostname()
POLL = 5 # seconds between looks at an empty queue
HEARTBEAT = 30 # seconds between "I'm alive" updates
OUT = os.environ.get('WORKER_OUT') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')
class Permanent(Exception):
"""This job can never succeed (bad input, missing file). Don't retry it."""
def need_file(job):
path = job['input'].get('path')
if not path or not os.path.isfile(path):
raise Permanent(f'no such file on {NAME}: {path!r}')
return path
# ---- Handlers. One function per job type. Check the input FIRST, then do the work. ----------
def do_sha256(job):
path = need_file(job)
h, n, t = hashlib.sha256(), 0, time.time()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1 << 20), b''):
h.update(chunk)
n += len(chunk)
return {'sha256': h.hexdigest(), 'bytes': n, 'seconds': round(time.time() - t, 2)}
def do_sleep(job):
"""A job that takes as long as you tell it. For testing the queue, not for real work."""
s = float(job['input'].get('seconds', 1))
time.sleep(s)
return {'slept': s}
HANDLERS = {'sha256': do_sha256, 'sleep': do_sleep}
try: # Thumbnails need Pillow. If it isn't installed, this worker simply doesn't offer them.
from PIL import Image
def do_thumbnail(job):
path = need_file(job)
try:
img = Image.open(path)
img.thumbnail((int(job['input'].get('size', 320)),) * 2)
except OSError as e:
raise Permanent(f'not an image Pillow can read: {e}')
os.makedirs(OUT, exist_ok=True)
out = os.path.join(OUT, f"thumb-{job['id']}.jpg")
img.convert('RGB').save(out, quality=85)
return {'thumbnail': out, 'width': img.width, 'height': img.height, 'on': NAME}
HANDLERS['thumbnail'] = do_thumbnail
except ImportError:
pass
# ---- The loop ----------------------------------------------------------------------------
def claim(db):
"""Take the next job nobody else has. The two statements that make this safe:
FOR UPDATE SKIP LOCKED: lock the row I picked, and skip any row another worker has
locked, instead of waiting for it. Then claim it only if it's STILL queued, and only
treat it as mine if that update actually changed a row.
"""
types = list(HANDLERS) # only ask for work this machine can actually do
with db.cursor() as cur:
cur.execute('START TRANSACTION')
cur.execute(
f"""SELECT id, job_type, input FROM jobs
WHERE status = 'queued' AND job_type IN ({','.join(['%s'] * len(types))})
ORDER BY priority, created_at
LIMIT 1 FOR UPDATE SKIP LOCKED""", types)
job = cur.fetchone()
if not job:
cur.execute('ROLLBACK')
return None
cur.execute(
"""UPDATE jobs SET status = 'claimed', claimed_by = %s, claimed_at = NOW(),
attempts = attempts + 1
WHERE id = %s AND status = 'queued'""", (NAME, job['id']))
if cur.rowcount != 1: # somebody beat us to it
cur.execute('ROLLBACK')
return None
cur.execute('COMMIT')
job['input'] = json.loads(job['input'])
return job
def heartbeat(db, state, job, done, failed):
with db.cursor() as cur:
cur.execute(
"""INSERT INTO workers (name, heartbeat_at, state) VALUES (%s, NOW(), %s)
ON DUPLICATE KEY UPDATE heartbeat_at = NOW(), state = VALUES(state)""",
(NAME, json.dumps({'state': state, 'job': job, 'done': done, 'failed': failed,
'handlers': sorted(HANDLERS), 'pid': os.getpid()})))
def main():
once = '--once' in sys.argv
db = connect()
done = failed = 0
last_beat = 0
print(f'{NAME}: worker up, handling {", ".join(sorted(HANDLERS))}', flush=True)
while True:
try:
if time.time() - last_beat >= HEARTBEAT:
heartbeat(db, 'idle', None, done, failed)
last_beat = time.time()
job = claim(db)
if not job:
if once:
return
time.sleep(POLL)
continue
heartbeat(db, 'busy', job['id'], done, failed)
last_beat = time.time()
started = time.time()
try:
result = HANDLERS[job['job_type']](job)
with db.cursor() as cur:
cur.execute("""UPDATE jobs SET status = 'complete', completed_at = NOW(), result = %s,
error = NULL WHERE id = %s""", (json.dumps(result), job['id']))
done += 1
print(f"done {job['id']} {job['job_type']} in {time.time() - started:.1f}s", flush=True)
except Exception as e:
with db.cursor() as cur:
finish_failed(cur, job['id'], f'{type(e).__name__}: {e}', isinstance(e, Permanent))
failed += 1
print(f"FAILED {job['id']} {job['job_type']}: {e}", flush=True)
last_beat = 0 # report idle straight away, not up to 30 seconds later
if once:
return
except (pymysql.err.OperationalError, pymysql.err.InterfaceError) as e:
# The database went away under us. Catching this is only half the fix:
# a worker that catches it and carries on with the dead connection looks
# healthy forever and never claims anything again. Reconnect.
print(f'lost the database ({e}); reconnecting', flush=True)
try:
db.close()
except Exception:
pass
db = connect()
if __name__ == '__main__':
main()
queue_common.py
"""Shared by every script: how to reach the database, and the one rule about giving up."""
import json
import os
import sys
import time
import pymysql
HERE = os.path.dirname(os.path.abspath(__file__))
MAX_ATTEMPTS = 3 # a job gets this many goes, however it fails
CONNECT_PATIENCE = 600 # seconds to keep trying to reach the database before giving up
def config():
with open(os.environ.get('QUEUE_CONFIG') or os.path.join(HERE, 'config.json')) as f:
return json.load(f)
def connect(quiet=False):
"""Connect, and if the database is away, WAIT for it rather than dying.
A worker that crashes when the database is unreachable gets restarted, crashes again,
and turns a five-minute outage into thousands of identical errors. Waiting is the job.
The patience is bounded on purpose: a database that's gone for ten minutes is worth
someone noticing, and an exit is something a service manager can see.
"""
cfg = config()
delay, waited = 1, 0
while True:
try:
return pymysql.connect(host=cfg['host'], user=cfg['user'], password=cfg['password'],
database=cfg['database'], autocommit=True, connect_timeout=10,
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.OperationalError as e:
if waited >= CONNECT_PATIENCE:
print(f'database still unreachable after {waited}s, giving up: {e}', flush=True)
sys.exit(1)
if not quiet:
print(f'database unreachable ({e.args[1] if len(e.args) > 1 else e}); retrying in {delay}s', flush=True)
time.sleep(delay)
waited += delay
delay = min(delay * 2, 60)
def finish_failed(cur, job_id, error, permanent=False):
"""The ONLY place a failed or abandoned job is put back or given up on.
The worker calls it when a job throws. The sweeper calls it when a worker vanished
mid-job. Both go through here, so both obey the same limit. Attempts were counted
when the job was claimed, so a job that kills its worker every time still runs out.
"""
cur.execute(
"""UPDATE jobs
SET status = IF(%s OR attempts >= %s, 'failed', 'queued'),
error = %s, claimed_by = NULL, claimed_at = NULL,
completed_at = IF(%s OR attempts >= %s, NOW(), NULL)
WHERE id = %s""",
(permanent, MAX_ATTEMPTS, str(error)[:2000], permanent, MAX_ATTEMPTS, job_id))