e83f00e87ae8e2cf53eb2b0be89058b4080dfa95
[goaljobs.git] / goaljobs.ml
1 (* goaljobs
2  * Copyright (C) 2013 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *)
18
19 open CalendarLib
20
21 open Unix
22 open Printf
23
24 open Goaljobs_config
25
26 let (//) = Filename.concat
27 let quote = Filename.quote
28
29 type goal_result_t = Goal_OK | Goal_failed of string
30 exception Goal_result of goal_result_t
31
32 let goal_failed msg = raise (Goal_result (Goal_failed msg))
33
34 let target v =
35   if v then raise (Goal_result Goal_OK)
36 let target_all vs = target (List.fold_left (&&) true vs)
37 let target_exists vs = target (List.fold_left (||) false vs)
38 let require f = f ()
39
40 type period_t = Seconds | Days | Months | Years
41 let seconds = (1, Seconds)
42 let sec = seconds and secs = seconds and second = seconds
43 let minutes = (60, Seconds)
44 let min = minutes and mins = minutes and minute = minutes
45 let hours = (3600, Seconds)
46 let hour = hours
47 let days = (1, Days)
48 let day = days
49 let weeks = (7, Days)
50 let week = weeks
51 let months = (1, Months)
52 let month = months
53 let years = (1, Years)
54 let year = years
55
56 let periodic_jobs = ref []
57
58 (* Register a periodic job. *)
59 let every ?name i (j, t) f =
60   let period = i*j, t in (* 5 minutes -> ((5 * 60), Seconds) *)
61   periodic_jobs := (period, (name, f)) :: !periodic_jobs
62
63 (* [next_time t period] returns the earliest event of [period]
64    strictly after time [t].
65
66    Visualising periods as repeated events on a timeline, this
67    returns [t']:
68
69    {v
70    events:  ---+---------+---------+---------+---------+---------+-----
71    times:          t     t'
72    }
73
74    Note that [period_t] events are not necessarily regular.
75    eg. The start of a month is not a fixed number of seconds
76    after the start of the previous month.  'Epoch' refers
77    to the Unix Epoch (ie. 1970-01-01 00:00:00 UTC).
78
79    If [period = i, Seconds i] then events are when
80    [t' mod i == 0] when t' is the number of seconds since
81    the Epoch.  This returns the next t' > t.
82
83    If [period = i, Days] then events happen at
84    midnight UTC every [i] days since the Epoch.
85    This returns the next midnight > t.
86
87    If [period = i, Months] then events happen at
88    midnight UTC on the 1st day of the month every [i] months
89    since the Epoch.  This returns midnight on the
90    1st day of the next month > t.
91
92    If [period = i, Years] then events happen at
93    midnight UTC on the 1st day of the year when
94    [(y - 1970) mod i == 0].  This returns midnight on the
95    1st day of the next year > t. *)
96
97 let next_time =
98   (* Round up 'a' to the next multiple of 'i'. *)
99   let round_up_float a i =
100     let r = mod_float a i in
101     if r = 0. then a +. i else a +. (i -. r)
102   and round_up a i =
103     let r = a mod i in
104     if r = 0 then a + i else a + (i - r)
105   in
106
107   fun t -> function
108   | (i, Seconds) ->
109     let i = float_of_int i in
110     round_up_float t i
111
112   | (i, Years) ->
113     let tm = gmtime t in
114
115     (* Round 'tm' up to the first day of the next year. *)
116     let year = round_up tm.tm_year i in
117     let tm = { tm with tm_sec = 0; tm_min = 0; tm_hour = 0;
118                        tm_mday = 1; tm_mon = 0; tm_year = year } in
119     fst (mktime tm)
120
121   | (i, Days) ->
122     let t = Date.from_unixfloat t in
123     let t0 = Date.make 1970 1 1 in
124
125     (* Number of whole days since Unix Epoch. *)
126     let nb_days = Date.Period.safe_nb_days (Date.sub t t0) in
127
128     let nb_days = round_up nb_days i in
129     let t' = Date.add t0 (Date.Period.day nb_days) in
130     Date.to_unixfloat t'
131
132   | (i, Months) ->
133     (* Calculate number of whole months since Unix Epoch. *)
134     let tm = gmtime t in
135     let months = 12 * (tm.tm_year - 70) + tm.tm_mon in
136
137     let months = round_up months i in
138     let t0 = Date.make 1970 1 1 in
139     let t' = Date.add t0 (Date.Period.month months) in
140     Date.to_unixfloat t'
141
142 let file_exists = Sys.file_exists
143
144 let directory_exists path =
145   let s =
146     try Some (stat path)
147     with
148     | Unix_error (ENOENT, _, _) -> None
149     | Unix_error (err, _, _) ->
150       let msg = sprintf "directory_exists: %s: %s" path (error_message err) in
151       goal_failed msg in
152   match s with
153   | Some s -> s.st_kind = S_DIR
154   | None -> false
155
156 let file_newer_than f1 f2 =
157   let stat f =
158     try Some (stat f)
159     with
160     | Unix_error (ENOENT, _, _) -> None
161     | Unix_error (err, _, _) ->
162       let msg = sprintf "file_newer_than: %s: %s" f (error_message err) in
163       goal_failed msg
164   in
165   let s1 = stat f1 and s2 = stat f2 in
166   match s1 with
167   | None -> false
168   | Some s1 ->
169     match s2 with
170     | None ->
171       let msg = sprintf "file_newer_than: %s: file does not exist" f2 in
172       goal_failed msg
173     | Some s2 ->
174       s1.st_mtime >= s2.st_mtime
175
176 let more_recent objs srcs =
177   if not (List.for_all file_exists objs) then false
178   else (
179     List.for_all (
180       fun obj -> List.for_all (file_newer_than obj) srcs
181     ) objs
182   )
183
184 let url_exists url =
185   (* http://stackoverflow.com/questions/12199059/how-to-check-if-an-url-exists-with-the-shell-and-probably-curl *)
186   let cmd =
187     sprintf "curl --output /dev/null --silent --head --fail %s" (quote url) in
188   match Sys.command cmd with
189   | 0 -> true
190   | 19|22 -> false
191   | r ->
192     let msg = sprintf "curl error testing '%s': exit code %d, see curl(1)"
193       url r in
194     goal_failed msg
195
196 let file_contains_string filename str =
197   let cmd = sprintf "grep -q %s %s" (quote str) (quote filename) in
198   match Sys.command cmd with
199   | 0 -> true
200   | 1 -> false
201   | r ->
202     let msg = sprintf "grep error testing for '%s' in '%s' (exit code %d)"
203       str filename r in
204     goal_failed msg
205
206 let url_contains_string url str =
207   let tmp = Filename.temp_file "goaljobsurl" "" in
208   let cmd =
209     sprintf "curl --output %s --silent --fail %s" (quote tmp) (quote url) in
210   (match Sys.command cmd with
211   | 0 -> ()
212   | 19|22 ->
213     let msg = sprintf "curl failed to download URL '%s'" url in
214     goal_failed msg
215   | r ->
216     let msg = sprintf "curl error testing '%s': exit code %d, see curl(1)"
217       url r in
218     goal_failed msg
219   );
220   let r = file_contains_string tmp str in
221   unlink tmp;
222   r
223
224 (* Create a temporary directory.  It is *not* deleted on exit. *)
225 let tmpdir () =
226   let chan = open_in "/dev/urandom" in
227   let data = String.create 16 in
228   really_input chan data 0 (String.length data);
229   close_in chan;
230   let data = Digest.to_hex (Digest.string data) in
231   let dir = Filename.temp_dir_name // sprintf "goaljobstmp%s" data in
232   mkdir dir 0o700;
233   dir
234
235 (* Recursively remove directory. *)
236 let rm_rf dir =
237   let cmd = sprintf "rm -rf %s" (quote dir) in
238   ignore (Sys.command cmd)
239
240 let shell = ref "/bin/sh"
241
242 (* Used by sh, shout etc.  Create a temporary directory and a
243  * 'script.sh' inside it containing the script to run.  Returns the
244  * temporary directory and command to run.
245  *)
246 let create_script script =
247   let dir = tmpdir () in
248   let script_file = dir // "script.sh" in
249   let chan = open_out script_file in
250   fprintf chan "#!%s\n" !shell;
251   fprintf chan "set -e\n"; (* so that job exits on error *)
252   fprintf chan "set -x\n"; (* echo commands (must be last) *)
253   fprintf chan "\n";
254   output_string chan script;
255   close_out chan;
256   chmod script_file 0o700;
257   let cmd = sprintf "cd %s && exec %s" (quote dir) (quote script_file) in
258   dir, cmd
259
260 let sh fs =
261   let do_sh script =
262     let dir, cmd = create_script script in
263     let r = Sys.command cmd in
264     rm_rf dir;
265     if r <> 0 then (
266       let msg = sprintf "external command failed with code %d" r in
267       goal_failed msg
268     )
269   in
270   ksprintf do_sh fs
271
272 let do_shlines script =
273   let dir, cmd = create_script script in
274   let chan = open_process_in cmd in
275   let lines = ref [] in
276   let rec loop () =
277     let line = input_line chan in
278     eprintf "%s\n%!" line;
279     lines := line :: !lines;
280     loop ()
281   in
282   (try loop () with End_of_file -> ());
283   let r = close_process_in chan in
284   rm_rf dir;
285   match r with
286   | WEXITED 0 -> List.rev !lines
287   | WEXITED i ->
288     let msg = sprintf "external command failed with code %d" i in
289     goal_failed msg
290   | WSIGNALED i ->
291     let msg = sprintf "external command was killed by signal %d" i in
292     goal_failed msg
293   | WSTOPPED i ->
294     let msg = sprintf "external command was stopped by signal %d" i in
295     goal_failed msg
296 let shlines fs = ksprintf do_shlines fs
297
298 let do_shout script =
299   let lines = do_shlines script in
300   String.concat "\n" lines
301 let shout fs = ksprintf do_shout fs
302
303 (*
304 val replace_substring : string -> string -> string -> string
305 *)
306
307 let change_file_extension ext filename =
308   let i =
309     try String.rindex filename '.'
310     with Not_found -> String.length filename in
311   String.sub filename 0 i ^ "." ^ ext
312
313 (*
314 val filter_file_extension : string -> string list -> string
315 *)
316
317 (* Persistent memory is stored in $HOME/.goaljobs-memory.  We have to
318  * lock this file each time we read or write because multiple concurrent
319  * jobs may access it at the same time.
320  *
321  * XXX Replace this with a more efficient and less fragile implementation.
322  *)
323
324 type ('a, 'b) alternative = Either of 'a | Or of 'b
325 let with_memory_locked ?(write = false) f =
326   let filename = getenv "HOME" // ".goaljobs-memory" in
327   let fd = openfile filename [O_RDWR; O_CREAT] 0o644 in
328   lockf fd (if write then F_LOCK else F_RLOCK) 0;
329   (* If the file is newly created with zero size, write an
330    * empty hash table.
331    *)
332   if (fstat fd).st_size = 0 then (
333     let empty : (string, string) Hashtbl.t = Hashtbl.create 13 in
334     let chan = out_channel_of_descr fd in
335     output_value chan empty;
336     Pervasives.flush chan;
337     ignore (lseek fd 0 SEEK_SET)
338   );
339
340   (* Run the function. *)
341   let r = try Either (f fd) with exn -> Or (exn) in
342   lockf fd F_ULOCK 0;
343   match r with
344   | Either x -> x
345   | Or exn -> raise exn
346
347 let memory_exists key =
348   with_memory_locked (
349     fun fd ->
350       let chan = in_channel_of_descr fd in
351       let memory : (string, string) Hashtbl.t = input_value chan in
352       Hashtbl.mem memory key
353   )
354
355 let memory_get key =
356   with_memory_locked (
357     fun fd ->
358       let chan = in_channel_of_descr fd in
359       let memory : (string, string) Hashtbl.t = input_value chan in
360       try Some (Hashtbl.find memory key) with Not_found -> None
361   )
362
363 let memory_set key value =
364   with_memory_locked ~write:true (
365     fun fd ->
366       let chan = in_channel_of_descr fd in
367       let memory : (string, string) Hashtbl.t = input_value chan in
368       Hashtbl.replace memory key value;
369       let chan = out_channel_of_descr fd in
370       seek_out chan 0;
371       output_value chan memory;
372       Pervasives.flush chan;
373   )
374
375 let memory_delete key =
376   with_memory_locked ~write:true (
377     fun fd ->
378       let chan = in_channel_of_descr fd in
379       let memory : (string, string) Hashtbl.t = input_value chan in
380       Hashtbl.remove memory key;
381       let chan = out_channel_of_descr fd in
382       seek_out chan 0;
383       output_value chan memory;
384       Pervasives.flush chan;
385   )
386
387 let published_goals = ref []
388 let publish name fn = published_goals := (name, fn) :: !published_goals
389 let get_goal name =
390   try Some (List.assoc name !published_goals) with Not_found -> None
391
392 let goal_file_exists filename =
393   if not (file_exists filename) then (
394     let msg = sprintf "file '%s' required but not found" filename in
395     goal_failed msg
396   )
397 let goal_directory_exists path =
398   if not (directory_exists path) then (
399     let msg = sprintf "directory '%s' required but not found" path in
400     goal_failed msg
401   )
402 let goal_file_newer_than f1 f2 =
403   if not (file_newer_than f1 f2) then (
404     let msg = sprintf "file %s is required to be newer than %s" f1 f2 in
405     goal_failed msg
406   )
407 let goal_more_recent objs srcs =
408   if not (more_recent objs srcs) then (
409     let msg = sprintf "object(s) %s are required to be newer than source(s) %s"
410       (String.concat " " objs) (String.concat " " srcs) in
411     goal_failed msg
412   )
413 let goal_url_exists url =
414   if not (url_exists url) then (
415     let msg = sprintf "url_exists: URL '%s' required but does not exist" url in
416     goal_failed msg
417   )
418 let goal_file_contains_string filename str =
419   if not (file_contains_string filename str) then (
420     let msg = sprintf "file_contains_string: file '%s' is required to contain string '%s'" filename str in
421     goal_failed msg
422   )
423 let goal_url_contains_string url str =
424   if not (url_contains_string url str) then (
425     let msg = sprintf "url_contains_string: URL '%s' is required to contain string '%s'" url str in
426     goal_failed msg
427   )
428 let goal_memory_exists k =
429   if not (memory_exists k) then (
430     let msg = sprintf "memory_exists: key '%s' required but does not exist" k in
431     goal_failed msg
432   )
433
434 let guard fn arg =
435   try fn arg; true
436   with
437   | Goal_result (Goal_failed msg) ->
438     prerr_endline ("error: " ^ msg);
439     false
440   | exn ->
441     prerr_endline (Printexc.to_string exn);
442     false
443
444 (* Run the program. *)
445 let rec init () =
446   let prog = Sys.executable_name in
447   let prog = Filename.basename prog in
448
449   (* Save the current working directory when the program started. *)
450   putenv "builddir" (getcwd ());
451
452   let args = ref [] in
453
454   let display_version () =
455     printf "%s %s\n" package_name package_version;
456     exit 0
457   in
458
459   let list_goals () =
460     let names = !published_goals in
461     let names = List.map fst names in
462     let names = List.sort compare names in
463     List.iter print_endline names;
464     exit 0
465   in
466
467   let argspec = Arg.align [
468     "--goals", Arg.Unit list_goals, " List all goals";
469     "-l", Arg.Unit list_goals, " List all goals";
470     "-V", Arg.Unit display_version, " Display version number and exit";
471     "--version", Arg.Unit display_version, " Display version number and exit";
472   ] in
473   let anon_fun str = args := str :: !args in
474   let usage_msg = sprintf "\
475 %s: a script generated by goaljobs
476
477 List all goals:                %s -l
478 Run a single goal like this:   %s <name-of-goal> [<goal-args ...>]
479
480 For more information see the goaljobs(1) man page.
481
482 Options:
483 " prog prog prog in
484
485   Arg.parse argspec anon_fun usage_msg;
486
487   let args = List.rev !args in
488
489   (* Was a goal named on the command line? *)
490   (match args with
491   | name :: args ->
492     (match get_goal name with
493     | Some fn ->
494       exit (if guard fn args then 0 else 1)
495     | None ->
496       eprintf "error: no goal called '%s' was found.\n" name;
497       eprintf "Use %s -l to list all published goals in this script.\n" name;
498       exit 1
499     )
500   | [] ->
501     (* If periodic jobs exist, fall through. *)
502     if !periodic_jobs = [] then (
503       (* Does a published 'all' goal exist? *)
504       match get_goal "all" with
505       | Some fn ->
506         exit (if guard fn [] then 0 else 1)
507       | None ->
508         (* No published 'all' goal. *)
509         eprintf "error: no goal called 'all' was found.\n";
510         exit 1
511     )
512   );
513
514   assert (!periodic_jobs <> []);
515
516   (* Run the periodic jobs.  Note these run forever, or until killed. *)
517   while true do
518     (* Find the next job to run. *)
519     let now = time () in
520     let jobs = List.map (
521       fun (period, (_, _ as name_f)) ->
522         next_time now period, name_f
523     ) !periodic_jobs in
524     let jobs = List.sort (fun (t1,_) (t2,_) -> compare t1 t2) jobs in
525
526     (* Find all jobs that have the same next time.
527      * XXX When we can handle parallel jobs we can do better here,
528      * but until them run all the ones which have the same time
529      * in series.
530      *)
531     let next_t = int_of_float (fst (List.hd jobs)) in
532     let jobs = List.filter (fun (t, _) -> int_of_float t = next_t) jobs in
533
534     (* Run next job(s) after waiting for the appropriate amount of time. *)
535     let seconds = next_t - int_of_float now in
536     eprintf "next job will run in %s\n%!" (printable_seconds seconds);
537     sleep seconds;
538
539     List.iter (
540       fun (_, (name, f)) ->
541         eprintf "running job: %s\n%!"
542           (match name with Some name -> name | None -> "[unnamed]");
543         ignore (guard f ())
544     ) jobs
545   done
546
547 and printable_seconds s =
548   if s < 60 then sprintf "%d seconds" s
549   else if s < 6000 then sprintf "%d minutes, %d seconds" (s/60) (s mod 60)
550   else if s < 86400 then sprintf "%d hours, %d minutes" (s/3600) (s/60)
551   else sprintf "about %d days" (s/86400)