-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcronsul
executable file
·47 lines (38 loc) · 1 KB
/
cronsul
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/bin/bash
set -eu
CONSUL_HOST="${CONSUL_HOST:-localhost}"
CONSUL_PORT="${CONSUL_PORT:-8500}"
CONSUL_ADDR="http://${CONSUL_HOST}:${CONSUL_PORT}"
usage() {
echo "Usage:"
echo " ${0##*/} <task id> [--period=<seconds>] <command>..."
exit 1
}
grab_lock_or_die() {
local task_id="$1"
local schedule_date="$2"
local period="$3"
ret="$(curl -sS -X PUT -d "${HOSTNAME}" "${CONSUL_ADDR}/v1/kv/cronsul/${task_id}/${period}/${schedule_date}?cas=0")"
if [[ "$ret" != "true" ]]; then
if [[ "$ret" != "false" ]]; then
echo $ret
fi
exit 1
fi
}
# Parse command line arguments.
if [[ "$#" -lt 2 ]]; then
usage
fi
task_id="$1"
shift
case "$1" in
--period) period="$2"; shift 2;;
--period=*) period="${1##--period=}"; shift;;
*) period=60;
esac
command=("$@")
# This will be wrong if cron starts our job really late.
schedule_date="$(( ($(date '+%s') / period) * period ))"
grab_lock_or_die "$task_id" "$schedule_date" "$period"
"${command[@]}"