-
Notifications
You must be signed in to change notification settings - Fork 0
/
supercron.scm
421 lines (378 loc) · 14.7 KB
/
supercron.scm
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
(use-modules
(oop goops)
(srfi srfi-1)
(ice-9 format)
(ice-9 getopt-long)
(sqlite3))
(define ULONG_MAX 18446744073709551615)
(define %iso-date "%Y-%m-%dT%H:%M:%S%z")
(define %min-timestamp 0)
(define %max-timestamp ULONG_MAX)
(define %default-period 60)
(define %version "0.4.0")
(define %verbose? #f)
(define %dry-run? #f)
(define %sqlite-url "supercron.sqlite3")
(define %connection #f)
(define-class <task> ()
(name #:init-keyword #:name #:accessor task-name #:init-value #f)
(arguments #:init-keyword #:arguments #:accessor task-arguments)
(environment #:init-keyword #:environment #:accessor task-environment #:init-value '())
(uid #:init-keyword #:uid #:accessor task-uid #:init-value #f)
(gid #:init-keyword #:gid #:accessor task-gid #:init-value #f)
(nice #:init-keyword #:nice #:accessor task-nice #:init-value #f)
(procedure #:init-keyword #:procedure #:accessor task-procedure #:init-value #f)
(schedule #:init-keyword #:schedule #:accessor task-schedule #:init-value '()))
(define-method (task-name/human (task <task>))
(define name (task-name task))
(if name name (string-join (task-arguments task) " ")))
(define-method (write (task <task>) port)
(format port "~a" (task-name/human task)))
(define-class <interval> ()
(start #:init-keyword #:start #:accessor interval-start #:init-value %min-timestamp)
(end #:init-keyword #:end #:accessor interval-end #:init-value %max-timestamp)
(period #:init-keyword #:period #:accessor interval-period #:init-value 0))
(define-method (write (interval <interval>) port)
(define start (interval-start interval))
(define end (interval-end interval))
(format port "[from ~a to ~a period ~a]"
(if (not (= start %min-timestamp)) (timestamp->string start))
(if (not (= end %max-timestamp)) (timestamp->string end))
(interval-period interval)))
(define-method (interval-start-time (interval <interval>))
(define t (interval-start interval))
(if t t %min-timestamp))
(define-method (interval-end-time (interval <interval>))
(define t (interval-end interval))
(if t t %max-timestamp))
(define-method (interval-null? (interval <interval>))
(> (interval-start interval) (interval-end interval)))
(define-method (interval-closed? (interval <interval>))
(and (not (= (interval-start interval) %min-timestamp))
(not (= (interval-end interval) %max-timestamp))))
(define-method (interval-count (interval <interval>))
(define period (interval-period interval))
(cond
((= period 0) 0)
(else (truncate (/ (- (interval-end interval) (interval-start interval)) period)))))
(define-method (interval-timestamps (interval <interval>))
(reverse
(fold
(lambda (x prev) (cons (+ x (car prev)) prev))
(list (interval-start interval))
(make-list (interval-count interval) (interval-period interval)))))
(define-method (intersect? (a <interval>) (b <interval>))
(define a0 (interval-start-time a))
(define a1 (interval-end-time a))
(define b0 (interval-start-time b))
(define b1 (interval-end-time b))
(or (<= b0 a0 b1)
(<= b0 a1 b1)
(<= a0 b0 a1)
(<= a0 b1 a1)))
(define-method (intersection (a <interval>) (b <interval>))
(define a0 (interval-start-time a))
(define a1 (interval-end-time a))
(define b0 (interval-start-time b))
(define b1 (interval-end-time b))
(define c-1 (min a0 b0))
(define c0 (max a0 b0))
(define c1 (min a1 b1))
(define period (interval-period a))
(define n (ceiling (/ (- c0 c-1) period)))
;; new start timestamp is aligned with the period
(make <interval>
#:start (+ c-1 (* n period))
#:end c1
#:period period))
;; generate timestamps in the intersection of the intervals
(define-method (interval-intersection-timestamps (a <interval>) (b <interval>))
(cond
((intersect? a b)
(let ((c (intersection a b)))
(if (and (not (interval-null? c)) (interval-closed? c))
(interval-timestamps c)
'())))
(else '())))
;; generate timestamps in the interval
(define-method (task-timestamps (task <task>) (interval <interval>))
(define tmp
(sort!
(append-map
(lambda (interval-b)
(interval-intersection-timestamps interval-b interval))
(task-schedule task))
(lambda (a b) (< a b))))
tmp)
(define-method (task-active? (task <task>))
(define active #f)
(let ((statement (sqlite-prepare %connection
"SELECT process_id FROM active_tasks WHERE task_id=?")))
(sqlite-bind statement 1 (task-name task))
(if (not (null? (sqlite-map (lambda (row) row) statement)))
(set! active #t))
(sqlite-finalize statement))
active)
(define-method (task-launch (task <task>))
(cond
((task-procedure task)
(catch #t
(lambda ()
(if %verbose?
(message "Launched task ~a\n" task))
(let ((result ((task-procedure task))))
(if %verbose?
(message "Finished task ~a: return value ~a\n" task result))))
(lambda (key . parameters)
(message "Failed to execute ~a: ~a\n" task (cons key parameters)))))
((task-active? task)
(if %verbose?
(message "Not launching task ~a, it is already active.\n" task)))
(else
(let ((id (primitive-fork)))
(cond
((= id 0)
(let ((argv (task-arguments task)))
(catch #t
(lambda ()
(if (task-gid task) (setgid (task-gid task)))
(if (task-uid task) (setuid (task-uid task)))
(if (task-nice task) (nice (task-nice task)))
(if %dry-run? (exit))
(apply execle `(,(car argv) ,(task-environment task) ,@argv)))
(lambda (key . parameters)
(if (eq? key 'quit) (exit))
(message "Failed to execute ~a: ~a\n" argv (cons key parameters))
(exit #f)))))
(else
(let ((statement (sqlite-prepare %connection
"INSERT INTO active_tasks (process_id,task_id) VALUES (?,?)")))
(sqlite-bind statement 1 id)
(sqlite-bind statement 2 (task-name task))
(sqlite-step statement)
(sqlite-finalize statement))
(if %verbose?
(message "Launched process ~a: ~a\n" id (task-arguments task))))
)))))
(define (status->string status)
(define (field key value)
(if value
(list (format #f "~a ~a" key value))
'()))
(string-join
(append
(field "exit code" (status:exit-val status))
(field "termination signal" (status:term-sig status))
(field "stop signal" (status:stop-sig status)))
", "))
(define (check-child-processes)
(define result
(catch #t
(lambda ()
(waitpid WAIT_ANY WNOHANG))
(lambda (key . parameters)
;; waitpid throws ENOENT even when WNOHANG is specified
;;(message "waitpid: ~a\n" (cons key parameters))
(cons 0 0))))
(define id (car result))
(define status (cdr result))
(if (not (= id 0))
(begin
(let ((statement (sqlite-prepare %connection
"DELETE FROM active_tasks WHERE process_id=?")))
(sqlite-bind statement 1 id)
(sqlite-step statement)
(sqlite-finalize statement))
(if %verbose?
(message "Terminated process ~a: ~a\n" id (status->string status)))
(check-child-processes))))
(define (store-current-timestamp current-timestamp)
(let ((statement (sqlite-prepare %connection
"INSERT INTO timestamps (timestamp) VALUES (?)")))
(sqlite-bind statement 1 current-timestamp)
(sqlite-step statement)
(sqlite-finalize statement))
(let ((statement (sqlite-prepare %connection
"DELETE FROM timestamps WHERE timestamp <> ?")))
(sqlite-bind statement 1 current-timestamp)
(sqlite-step statement)
(sqlite-finalize statement)))
(define (launch-new-tasks tasks old-timestamp current-timestamp)
(define interval
(make <interval>
#:start old-timestamp
#:end current-timestamp))
(define current-tasks
(filter
(lambda (task) (not (null? (task-timestamps task interval))))
tasks))
(sqlite-exec %connection "BEGIN TRANSACTION")
(for-each task-launch current-tasks)
(store-current-timestamp current-timestamp)
(sqlite-exec %connection "COMMIT"))
(define (agenda tasks interval max-count)
(define entries
(sort!
(append-map
(lambda (task)
(map
(lambda (timestamp) (cons timestamp task))
(task-timestamps task interval)))
tasks)
(lambda (a b) (< (car a) (car b)))))
(take entries (min max-count (length entries))))
(define (timestamp->string t)
(if (= t %max-timestamp)
"+infinity"
(strftime %iso-date (localtime t))))
(define (string->timestamp str)
(let ((tm (car (strptime %iso-date str))))
(set-tm:zone tm (tm:zone (localtime (current-time))))
(car (mktime tm))))
(define (message format-string . rest)
(define msg
(apply format
`(#f
,(string-append "~a " format-string)
,(strftime %iso-date (localtime (current-time)))
,@rest)))
(display msg (current-error-port))
(force-output (current-error-port)))
(define (database-open)
(define conn (sqlite-open %sqlite-url (logior SQLITE_OPEN_CREATE SQLITE_OPEN_READWRITE)))
(set! %connection conn)
;; Optimise sqlite performance.
;; See: D. Purohith, J. Mohan, V. Chidambaram "The Dangers and Complexities of SQLite Benchmarking"
;; https://www.cs.utexas.edu/~jaya/pdf/apsys17-sqlite.pdf
(sqlite-exec conn "PRAGMA auto_vacuum=INCREMENTAL")
(sqlite-exec conn "PRAGMA journal_mode=WAL")
(sqlite-exec conn "PRAGMA synchronous=NORMAL")
;; create tables
(sqlite-exec conn "CREATE TABLE IF NOT EXISTS active_tasks (process_id INTEGER NOT NULL, task_id TEXT NOT NULL); CREATE TABLE IF NOT EXISTS timestamps (timestamp INTEGER NOT NULL);")
;; remove stale processes
(sqlite-exec conn "DELETE FROM active_tasks")
;; run all tasks that should have been run while supercron was inactive
(let ((statement (sqlite-prepare conn "SELECT MAX(timestamp) FROM timestamps")))
(define (first-or-false lst) (if (null? lst) #f (car lst)))
(define old-timestamp (first-or-false (sqlite-map (lambda (row) (vector-ref row 0)) statement)))
(sqlite-finalize statement)
(if old-timestamp
(launch-new-tasks tasks old-timestamp (current-time))))
;; optimise sqlite
(database-optimize)
conn)
(define (database-optimize)
(sqlite-exec %connection "PRAGMA incremental_vacuum")
(sqlite-exec %connection "PRAGMA optimize"))
(define (period str)
(define s (string-trim-both str))
(define n (string-length s))
(define (parse suffix-size multiplier)
(* multiplier (string->number (substring s 0 (- n suffix-size)))))
(max 1
(cond
((string-suffix? "s" s) (parse 1 1))
((string-suffix? "m" s) (parse 1 60))
((string-suffix? "h" s) (parse 1 (* 60 60)))
((string-suffix? "d" s) (parse 1 (* 60 60 24)))
((string-suffix? "M" s) (parse 1 (* 60 60 24 31)))
((string-suffix? "y" s) (parse 1 (* 60 60 24 31 12)))
(else (let ((result (string->number s)))
(if result result 0))))))
(define seconds 1)
(define minutes 60)
(define hours (* 60 60))
(define days (* 60 60 24))
(define months (* 60 60 24 31))
(define years (* 60 60 24 31 12))
(define time string->timestamp)
(define (load-tasks filename)
(load filename))
(define (usage)
(define name (car (command-line)))
(format #t "usage: ~a [--period duration] [--verbose] [--dry-run] filename...\n" name)
(format #t "usage: ~a --schedule [--from timestamp] [--to timestamp] [--limit max-entries] filename...\n" name)
(format #t "usage: ~a --trigger --task task-name filename...\n" name))
(if (= (length (command-line)) 1)
(begin
(usage)
(exit #f)))
(define options
(getopt-long (command-line)
`((schedule (required? #f) (value #f))
(from (required? #f) (value #t))
(to (required? #f) (value #t))
(limit (required? #f) (value #t))
(trigger (required? #f) (value #f))
(task (required? #f) (value #t))
(period (required? #f) (value #t))
(verbose (single-char #\v) (required? #f) (value #f))
(dry-run (single-char #\n) (required? #f) (value #f))
(help (single-char #\h) (required? #f))
(version (required? #f)))))
(define files (option-ref options '() '()))
(if (option-ref options 'help #f)
(begin
(usage)
(exit)))
(if (option-ref options 'version #f)
(begin
(format #t "~a" %version)
(exit)))
(define tasks
(cons
(make <task>
#:name "supercron-optimise-database"
#:schedule (list (make <interval> #:period (period "24h")))
#:procedure database-optimize)
(append-map
(lambda (filename) (load-tasks filename))
files)))
(if (option-ref options 'schedule #f)
(let ((from-str (option-ref options 'from #f))
(to-str (option-ref options 'to #f))
(limit-str (option-ref options 'limit #f)))
(define from (if from-str (string->timestamp from-str) (current-time)))
(define to (if to-str (string->timestamp to-str) (+ from (* 60 60 24))))
(define limit (if limit-str (string->number limit-str) 1000))
(format #t "Schedule from ~a to ~a (showing at most ~a entries):\n"
(timestamp->string from) (timestamp->string to) limit)
(for-each
(lambda (pair)
(define timestamp (car pair))
(define task (cdr pair))
(format #t "~a ~a\n" (timestamp->string timestamp) (task-name/human task)))
(agenda tasks (make <interval> #:start from #:end to) limit))
(exit)))
(database-open)
(if (option-ref options 'trigger #f)
(let ((opt-task-name (option-ref options 'task "")))
(define selected-tasks
(filter
(lambda (task) (string=? (task-name task) opt-task-name))
tasks))
(if (null? selected-tasks)
(begin
(format (current-error-port) "Unable to find task \"~a\".\n" opt-task-name)
(exit #f)))
(for-each task-launch selected-tasks)
(check-child-processes)
(exit)))
(set! %verbose? (option-ref options 'verbose #f))
(set! %dry-run? (option-ref options 'dry-run #f))
(define %period
(let ((period-str (option-ref options 'period #f)))
(if period-str (period period-str) %default-period)))
(define old-timestamp (current-time))
(define current-timestamp old-timestamp)
(while #t
(sleep %period)
(check-child-processes)
;; intervals are all closed, so we add 1 second here
;; to not repeat the same task twice
(set! old-timestamp (+ 1 current-timestamp))
(set! current-timestamp (current-time))
(launch-new-tasks tasks old-timestamp current-timestamp)
(check-child-processes)
(gc))
;; vim:lispwords+=sqlite-prepare