Hands-on task
A distributed lock for cron scripts
Nightly jobs are run by cron on several servers, and sometimes the same job runs twice at the same time. Write a wrapper /usr/local/bin/with-lock (bash, executable) that takes a lock in Redis:
with-lock <name> <command...>
Requirements:
- the lock is the key
lock:<name>, its value is a unique token of this run; the key is set with a single atomic command, only if it doesn't exist yet, and with a TTL of 30 seconds (so a crashed process doesn't hold the lock forever); - if the lock is taken — exit immediately with a non-zero code, do not run the command and don't wait;
- otherwise — run the command and exit with its code;
- after the command, release the lock only if the token in the key is still yours (while the command ran, the TTL may have expired and another process may have taken the lock). The compare and delete must be atomic, a single
EVAL(a Lua script on the server), not aGET+DELpair.
Redis is already running on 127.0.0.1:6379.
- redis
- SET NX EX
- EVAL
- Lua
- distributed lock
- bash