daemon: On fork, open stdin/stdout/stderr on /dev/null.
[whenjobs.git] / lib / pa_when.ml
1 (* whenjobs
2  * Copyright (C) 2012 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 (* For general information about camlp4, see:
20  * http://brion.inria.fr/gallium/index.php/Camlp4
21  *
22  * For information about quotations, see:
23  * http://brion.inria.fr/gallium/index.php/Quotation
24  *)
25
26 open Printf
27
28 open Camlp4.PreCast
29 open Syntax
30 open Ast
31
32 let unique = let i = ref 0 in fun () -> incr i; !i
33
34 let unique_job_name () = sprintf "job$%d" (unique ())
35
36 let rec find s sub =
37   let len = String.length s in
38   let sublen = String.length sub in
39   let rec loop i =
40     if i <= len-sublen then (
41       let rec loop2 j =
42         if j < sublen then (
43           if s.[i+j] = sub.[j] then loop2 (j+1)
44           else -1
45         ) else
46           i (* found *)
47       in
48       let r = loop2 0 in
49       if r = -1 then loop (i+1) else r
50     ) else
51       -1 (* not found *)
52   in
53   loop 0
54
55 let rec replace_str s s1 s2 =
56   let len = String.length s in
57   let sublen = String.length s1 in
58   let i = find s s1 in
59   if i = -1 then s
60   else (
61     let s' = String.sub s 0 i in
62     let s'' = String.sub s (i+sublen) (len-i-sublen) in
63     s' ^ s2 ^ replace_str s'' s1 s2
64   )
65
66 (* Convert a _loc to an AST. *)
67 let expr_of_loc _loc loc =
68   let file_name,
69     start_line, start_bol, start_off,
70     stop_line, stop_bol, stop_off,
71     ghost = Loc.to_tuple loc in
72   <:expr< Camlp4.PreCast.Loc.of_tuple
73     ($str:file_name$,
74      $`int:start_line$, $`int:start_bol$, $`int:start_off$,
75      $`int:stop_line$, $`int:stop_bol$, $`int:stop_off$,
76      $`bool:ghost$) >>
77
78 (* "Lift" an expression, turning it from an expression into an OCaml
79  * abstract syntax tree in the output.  This is pretty obscure.
80  * http://caml.inria.fr/pub/ml-archives/caml-list/2008/09/591f7c4a8df9295d675a5adcb6802748.en.html
81  *)
82 module M = Ast.Meta.Make (Ast.Meta.MetaGhostLoc)
83 let lift_expr = M.Expr.meta_expr
84
85 (* Handle a top level statement. *)
86 let rec call_stmt name (_loc, stmt, sh) =
87   let name =
88     match name with
89     | None -> let name = unique_job_name () in <:expr< $str:name$ >>
90     | Some name -> name in
91   match stmt with
92   | `When e -> when_stmt _loc name e sh
93   | `Every p -> every_stmt _loc name p sh
94
95 (* Handle a top level "when" statement.
96  * e -> when expression
97  * sh -> the shell script to run
98  * Returns a top level statement (str_item) which when executed just
99  * adds the statement to a global list.
100  *)
101 and when_stmt _loc name e sh =
102   let loc = expr_of_loc _loc _loc in
103   let e = lift_expr _loc e in
104   <:str_item<
105     open Camlp4.PreCast
106     Whenfile.add_when_job $loc$ $name$ $e$ $sh$
107   >>
108
109 (* Handle a top level "every" statement. *)
110 and every_stmt _loc name period sh =
111   let loc = expr_of_loc _loc _loc in
112   <:str_item<
113     open Camlp4.PreCast
114     Whenfile.add_every_job $loc$ $name$ $period$ $sh$
115   >>
116
117 let () =
118   (* Quotation expander for shell script. *)
119   let sh_quotation_expander _loc _ sh =
120     let loc = expr_of_loc _loc _loc in
121
122     (* Convert ">\>" to ">>" in code. *)
123     let sh = replace_str sh ">\\>" ">>" in
124
125     <:expr< { Whenexpr.sh_loc = $loc$;
126               sh_script = $str:sh$ } >>
127   in
128   Quotation.add "sh" Quotation.DynAst.expr_tag sh_quotation_expander;
129
130   (* Default quotation expander (<< .. >>) should be shell script ("sh"). *)
131   Quotation.default := "sh"
132
133 (* For period expressions "<NN> (secs|mins|hours|...)" we cannot use
134  * the ordinary camlp4 parser since it only looks ahead by 1 symbol, so
135  * it gets "stuck" on the integer.  Write a custom parser instead.
136  *
137  * Note the EXTEND macro implicitly reserves KEYWORDs.
138  *)
139 let period_parser =
140   Gram.Entry.of_parser "period"
141     (fun stream ->
142       match Stream.peek stream with
143       | Some (INT (_, i), info) ->
144         let i = int_of_string i in
145         let _loc = Gram.token_location info in
146         Stream.junk stream;
147         (match Stream.next stream with
148         | KEYWORD ("sec"|"secs"|"second"|"seconds"), _ ->
149           <:expr< Whenexpr.Every_seconds $`int:i$ >>
150         | KEYWORD ("min"|"mins"|"minute"|"minutes"), _ ->
151           let i = 60 * i in
152           <:expr< Whenexpr.Every_seconds $`int:i$ >>
153         | KEYWORD ("hour"|"hours"), _ ->
154           let i = 3600 * i in
155           <:expr< Whenexpr.Every_seconds $`int:i$ >>
156         | KEYWORD ("day"|"days"), _ ->
157           <:expr< Whenexpr.Every_days $`int:i$ >>
158         | KEYWORD ("week"|"weeks"), _ ->
159           let i = 7 * i in
160           <:expr< Whenexpr.Every_days $`int:i$ >>
161         | KEYWORD ("month"|"months"), _ ->
162           <:expr< Whenexpr.Every_months $`int:i$ >>
163         | KEYWORD ("year"|"years"), _ ->
164           <:expr< Whenexpr.Every_years $`int:i$ >>
165         | KEYWORD ("decade"|"decades"), _ ->
166           let i = 10 * i in
167           <:expr< Whenexpr.Every_years $`int:i$ >>
168         | KEYWORD ("century"|"centuries"|"centurys"), _ ->
169           let i = 100 * i in
170           <:expr< Whenexpr.Every_years $`int:i$ >>
171         | KEYWORD ("millenium"|"millenia"|"milleniums"), _ ->
172           let i = 1000 * i in
173           <:expr< Whenexpr.Every_years $`int:i$ >>
174         | (KEYWORD s | LIDENT s), _ ->
175           eprintf "period: failed to parse %d %s\n%!" i s;
176           raise Stream.Failure
177         | _ ->
178           raise Stream.Failure
179         )
180       | _ -> raise Stream.Failure
181     )
182 ;;
183
184 EXTEND Gram
185   GLOBAL: str_item;
186
187   (* A period expression (used in "every"). *)
188   periodexpr: [
189     [ ["sec"|"secs"|"second"|"seconds"] ->
190       <:expr< Whenexpr.Every_seconds 1 >> ]
191   | [ ["min"|"mins"|"minute"|"minutes"] ->
192       <:expr< Whenexpr.Every_seconds 60 >> ]
193   | [ ["hour"|"hours"] -> <:expr< Whenexpr.Every_seconds 3600 >> ]
194   | [ ["day"|"days"] -> <:expr< Whenexpr.Every_days 1 >> ]
195   | [ ["week"|"weeks"] -> <:expr< Whenexpr.Every_days 7 >> ]
196   | [ ["month"|"months"] -> <:expr< Whenexpr.Every_months 1 >> ]
197   | [ ["year"|"years"] -> <:expr< Whenexpr.Every_years 1 >> ]
198   | [ ["decade"|"decades"] -> <:expr< Whenexpr.Every_years 10 >> ]
199   | [ ["century"|"centuries"|"centurys"] ->
200       <:expr< Whenexpr.Every_years 100 >> ]
201   | [ ["millenium"|"millenia"|"milleniums"] ->
202       <:expr< Whenexpr.Every_years 1000 >> ]
203   | [ e = period_parser -> e ]
204   ];
205
206   (* Top level statements. *)
207   statement: [
208     [ "when"; e = expr; ":"; sh = expr ->
209       (_loc, `When e, sh) ]
210   | [ "every"; p = periodexpr; ":"; sh = expr ->
211       (_loc, `Every p, sh) ]
212   ];
213
214   (* "str_item" is a top level statement in an OCaml program. *)
215   str_item: LEVEL "top" [
216     [ s = statement -> call_stmt None s ]
217   | [ "job"; name = expr; s = statement -> call_stmt (Some name) s ]
218   ];
219
220 END