bd265459b05350443538073bdd97090e3c939270
[whenjobs.git] / tools / whenjobs.ml
1 (* whenjobs daemon
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 open Big_int
20 open Unix
21 open Printf
22
23 open Whenutils
24
25 (* Ensures that Whentools module is linked to the whenjobs tool. *)
26 let _ = Whentools.set_variable
27
28 let libdir = ref Libdir.libdir
29
30 let jobsdir =
31   (* Running the program as root is a mistake.  It must be run as a
32    * non-root user.
33    *)
34   let euid = geteuid () in
35   if euid = 0 then (
36     eprintf "whenjobs: this program must not be run as root\n";
37     exit 1
38   );
39
40   (* $HOME must be defined and must exist and be a directory and must be
41    * owned by the current user.
42    *)
43   let home =
44     try getenv "HOME"
45     with Not_found ->
46       eprintf "whenjobs: $HOME environment variable must be defined\n";
47       exit 1 in
48
49   let stat =
50     try lstat home
51     with Unix_error (err, fn, _) ->
52       eprintf "whenjobs: %s: %s ($HOME): %s\n" fn home (error_message err);
53       exit 1 in
54   if stat.st_kind != S_DIR then (
55     eprintf "whenjobs: %s ($HOME): not a directory\n" home;
56     exit 1
57   );
58
59   if stat.st_uid != euid then (
60     eprintf "whenjobs: %s ($HOME): not owned by the current user (uid %d)\n"
61       home euid;
62     exit 1
63   );
64
65   (* Make the $HOME/.whenjobs directory if it doesn't exist. *)
66   let jobsdir = sprintf "%s/.whenjobs" home in
67   (try mkdir jobsdir 0o700 with Unix_error _ -> ());
68
69   jobsdir
70
71 let rec main () =
72   (* Parse the command line arguments. *)
73   let mode = ref None in
74   let typ = ref "string" in
75
76   let set_mode m () = mode := Some m in
77
78   let display_version () =
79     printf "%s %s\n" Config.package_name Config.package_version;
80     exit 0
81   in
82
83   let argspec = Arg.align [
84     "--cancel", Arg.Unit (set_mode `Cancel), " Cancel a job";
85     "--daemon-start", Arg.Unit (set_mode `Daemon_start), " Start the daemon";
86     "--daemon-status", Arg.Unit (set_mode `Daemon_status), " Display the status of the daemon";
87     "--daemon-stop", Arg.Unit (set_mode `Daemon_stop), " Stop the daemon";
88     "--daemon-restart", Arg.Unit (set_mode `Daemon_restart), " Restart the daemon";
89     "-e", Arg.Unit (set_mode `Edit), " Edit and upload the script";
90     "--edit", Arg.Unit (set_mode `Edit), " Edit and upload the script";
91     "--get", Arg.Unit (set_mode `Get), " Display the variable";
92     "--jobs", Arg.Unit (set_mode `Jobs), " List running jobs";
93     "-l", Arg.Unit (set_mode `List), " List the script";
94     "--list", Arg.Unit (set_mode `List), " List the script";
95     "--lib", Arg.Set_string libdir, "dir Specify directory that contains pa_when.cmo";
96     "--set", Arg.Unit (set_mode `Set), " Set the variable";
97     "--start", Arg.Unit (set_mode `Start), " Start a job manually";
98     "--type", Arg.Set_string typ, "bool|int|float|string|unit Set the variable type";
99     "--upload", Arg.Unit (set_mode `Upload), " Upload the script";
100     "--variables", Arg.Unit (set_mode `Variables), " Display all variables and values";
101     "-V", Arg.Unit display_version, " Display version number and exit";
102     "--version", Arg.Unit display_version, " Display version number and exit";
103   ] in
104
105   let args = ref [] in
106   let anon_fun str = args := str :: !args in
107
108   let usage_msg = "\
109 Whenjobs is a powerful but simple cron replacement.
110 Whenjobs copyright (C) 2012 Red Hat Inc.
111
112 Editing the script:
113
114   whenjobs -e | --edit
115   whenjobs -l | --list
116
117 Get and set variables:
118
119   whenjobs --get variable
120   whenjobs --set variable value
121
122 Start and stop the per-user daemon:
123
124   whenjobs --daemon-start | --daemon-stop | --daemon-status
125
126 For documentation see the whenjobs(1) man page.
127
128 Options:
129 " in
130
131   Arg.parse argspec anon_fun usage_msg;
132
133   let mode = !mode in
134   let args = List.rev !args in
135
136   let typ = match !typ with
137     | "bool"|"boolean" -> `Bool
138     | "string" -> `String
139     | "int" -> `Int
140     | "float"|"double" -> `Float
141     | "unit" -> `Unit
142     | t ->
143       eprintf "whenjobs: --type: unknown type (%s)\n" t;
144       exit 1 in
145
146   (* Depending on the selected mode, perform a different action. *)
147   match mode with
148   | None ->
149     eprintf "whenjobs: no operation selected.\n";
150     suggest_help ();
151     exit 1
152
153   | Some `Edit ->
154     unused_error args "-e";
155     edit_file ()
156
157   | Some `List ->
158     unused_error args "-l";
159     list_file ()
160
161   | Some `Upload ->
162     unused_error args "--upload";
163     upload_file ()
164
165   | Some `Set ->
166     if List.length args != 2 then (
167       eprintf "whenjobs --set variable value\n";
168       eprintf "If 'value' contains spaces, you may need to quote it.\n";
169       suggest_help ();
170       exit 1
171     );
172     set_variable (List.hd args) (List.hd (List.tl args)) typ
173
174   | Some `Get ->
175     if List.length args != 1 then (
176       eprintf "whenjobs --get variable\n";
177       suggest_help ();
178       exit 1
179     );
180     get_variable (List.hd args)
181
182   | Some `Variables ->
183     unused_error args "--variables";
184     list_variables ()
185
186   | Some `Daemon_start ->
187     unused_error args "--daemon-start";
188     daemon_start ()
189
190   | Some `Daemon_stop ->
191     unused_error args "--daemon-stop";
192     daemon_stop ()
193
194   | Some `Daemon_restart ->
195     unused_error args "--daemon-restart";
196     daemon_restart ()
197
198   | Some `Daemon_status ->
199     unused_error args "--daemon-status";
200     daemon_status ()
201
202   | Some `Jobs ->
203     unused_error args "--jobs";
204     jobs ()
205
206   | Some `Cancel ->
207     if List.length args != 1 then (
208       eprintf "whenjobs --cancel serial\n";
209       suggest_help ();
210       exit 1
211     );
212     cancel_job (List.hd args)
213
214   | Some `Start ->
215     if List.length args != 1 then (
216       eprintf "whenjobs --start jobname\n";
217       eprintf "If 'value' contains spaces, you may need to quote it.\n";
218       suggest_help ();
219       exit 1
220     );
221     start_job (List.hd args)
222
223 and edit_file () =
224   (* If there is no initial file, create an empty one containing the
225    * tutorial.
226    *)
227   let file = get_jobs_filename () in
228   if not (Sys.file_exists file) then
229     create_tutorial file;
230
231   (* Is $EDITOR set?  If not, use a default. *)
232   let editor = try getenv "EDITOR" with Not_found -> "vi" in
233
234   (* Get the (size, MD5) of the file to tell if it changed. *)
235   let file_stamp () =
236     try (lstat file).st_size, Digest.file file
237     with Unix_error (err, fn, _) ->
238       eprintf "whenjobs: %s: %s: %s\n" fn file (error_message err);
239       exit 1
240   in
241   let old_stamp = file_stamp () in
242
243   let cmd = sprintf "%s %s" editor file in
244   if Sys.command cmd != 0 then (
245     eprintf "whenjobs: error editing file (is $EDITOR set correctly?)\n";
246     exit 1
247   );
248
249   let new_stamp = file_stamp () in
250
251   if old_stamp <> new_stamp then
252     upload_file ()
253
254 and list_file () =
255   let file = get_jobs_filename () in
256   if not (Sys.file_exists file) then (
257     eprintf "whenjobs: there is no jobs file, use 'whenjobs -e' to create one\n";
258     exit 1
259   );
260   let chan = open_in file in
261   let rec loop () =
262     printf "%s\n" (input_line chan);
263     loop ()
264   in
265   (try loop () with End_of_file -> ());
266   close_in chan
267
268 and upload_file () =
269   (* Recompile the jobs file. *)
270   let file = get_jobs_filename () in
271   let cmo_file = sprintf "%s/jobs.cmo" jobsdir in
272   let cmd = sprintf "ocamlfind ocamlc -I +camlp4 -I %s -package unix,camlp4.lib -pp 'camlp4o %s/pa_when.cmo' -c %s -o %s"
273     !libdir !libdir file cmo_file in
274   if Sys.command cmd <> 0 then (
275     eprintf "whenjobs: could not compile jobs script, see earlier error messages\n";
276     eprintf "compile command was:\n%s\n" cmd;
277     exit 1
278   );
279
280   (* Test-load the jobs file to ensure it makes sense. *)
281   Whenfile.init Whenstate.empty;
282   (try
283      Dynlink.loadfile cmo_file
284    with
285      Dynlink.Error err ->
286        eprintf "whenjobs: %s\n" (Dynlink.error_message err);
287        (* Since it failed, unlink it. *)
288        (try unlink cmo_file with Unix_error _ -> ());
289        exit 1
290   );
291
292   (* OK now let's tell the daemon to reload it. *)
293   let client = start_client () in
294   (match Whenproto_clnt.When.V1.reload_file client () with
295   | `ok -> ()
296   | `error msg ->
297     eprintf "whenjobs: reload: %s\n" msg;
298     suggest_check_server_logs ();
299     exit 1
300   );
301   stop_client client
302
303 and set_variable name value typ =
304   let value = match typ with
305     | `Bool ->
306       (match value with
307       | "true"|"t"|"yes"|"y"|"on"|"1" -> `bool_t true
308       | "false"|"f"|"no"|"n"|"off"|"0" -> `bool_t false
309       | _ ->
310         eprintf "whenjobs: variable does not have a boolean value\n";
311         exit 1
312       )
313     | `String -> `string_t value
314     | `Int ->
315       (try ignore (big_int_of_string value)
316        with Failure _ ->
317          eprintf "whenjobs: variable is not an integer\n";
318          exit 1
319       );
320       `int_t value (* the string is what we pass over the wire *)
321     | `Float ->
322       (try `float_t (float_of_string value)
323        with Failure _ ->
324          eprintf "whenjobs: variable is not a floating point number\n";
325          exit 1
326       )
327     | `Unit ->
328       if value <> "" then (
329         eprintf "whenjobs: unit variables must be empty strings\n";
330         exit 1
331       );
332       `unit_t in
333
334   let client = start_client () in
335   (match Whenproto_clnt.When.V1.set_variable client (name, value) with
336   | `ok -> ()
337   | `error msg ->
338     eprintf "whenjobs: set: %s\n" msg;
339     suggest_check_server_logs ();
340     exit 1
341   );
342   stop_client client
343
344 and get_variable name =
345   let client = start_client () in
346   let value = Whenproto_clnt.When.V1.get_variable client name in
347   print_endline (string_of_variable value);
348   stop_client client
349
350 and list_variables () =
351   let client = start_client () in
352   let names = Whenproto_clnt.When.V1.get_variable_names client () in
353   Array.iter (
354     fun name ->
355       let value = Whenproto_clnt.When.V1.get_variable client name in
356       printf "%s=%s\n" name (string_of_variable value)
357   ) names;
358   stop_client client
359
360 and daemon_start () =
361   assert false
362
363 and daemon_stop () =
364   let client = start_client () in
365   (match Whenproto_clnt.When.V1.exit_daemon client () with
366   | `ok -> ()
367   | `error msg ->
368     eprintf "whenjobs: daemon-stop: %s\n" msg;
369     suggest_check_server_logs ();
370     exit 1
371   );
372   stop_client client
373
374 and daemon_restart () =
375   assert false
376
377 and daemon_status () =
378   assert false
379
380 and jobs () =
381   let client = start_client () in
382   let jobs = Whenproto_clnt.When.V1.get_jobs client () in
383   stop_client client;
384
385   let cmp { Whenproto_aux.job_name = name1; job_serial = serial1 }
386       { Whenproto_aux.job_name = name2; job_serial = serial2 } =
387     let i = compare name1 name2 in
388     if i <> 0 then i
389     else
390       compare_big_int (big_int_of_string serial1) (big_int_of_string serial2)
391   in
392   Array.sort cmp jobs;
393
394   Array.iter (
395     fun { Whenproto_aux.job_serial = serial; job_name = name;
396           job_tmpdir = tmpdir; job_start_time = time } ->
397       printf "%s %s\n\trunning in: %s\n\tstarted at: %s\n"
398         serial name tmpdir
399         (string_of_time_t ~localtime:true (Int64.to_float time))
400   ) jobs
401
402 and cancel_job serial =
403   let client = start_client () in
404   (match Whenproto_clnt.When.V1.cancel_job client serial with
405   | `ok -> ()
406   | `error msg ->
407     eprintf "whenjobs: cancel-job: %s\n" msg;
408     suggest_check_server_logs ();
409     exit 1
410   );
411   stop_client client
412
413 and start_job name =
414   let client = start_client () in
415   (match Whenproto_clnt.When.V1.start_job client name with
416   | `ok -> ()
417   | `error msg ->
418     eprintf "whenjobs: start-job: %s\n" msg;
419     suggest_check_server_logs ();
420     exit 1
421   );
422   stop_client client
423
424 and unused_error args op =
425   if args <> [] then (
426     eprintf "whenjobs %s: unused parameters on the command line.\n" op;
427     suggest_help ();
428     exit 1
429   )
430
431 and suggest_help () =
432   eprintf "Use 'whenjobs --help' for a summary of options or read whenjobs(1) man page.\n"
433
434 and suggest_check_server_logs () =
435   eprintf "Look at the server logs (/var/log/cron or /var/log/syslog usually) for\n";
436   eprintf "further information on why this daemon operation failed.\n"
437
438 and get_jobs_filename () =
439   sprintf "%s/jobs.ml" jobsdir
440
441 and create_tutorial file =
442   let chan = open_out file in
443   output_string chan Tutorial.tutorial;
444   close_out chan
445
446 and start_client () =
447   let addr = sprintf "%s/socket" jobsdir in
448   let client =
449     try
450       Whenproto_clnt.When.V1.create_client
451         (Rpc_client.Unix addr)
452         Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
453     with
454     | Unix_error ((ECONNREFUSED|ENOENT), _, _) ->
455       eprintf "whenjobs: error: the daemon ('whenjobsd') is not running\n";
456       eprintf "Use 'whenjobs --daemon-start' to start the daemon.\n";
457       exit 1
458     | Unix_error (err, fn, _) ->
459       eprintf "whenjobs: %s: %s: %s\n" fn addr (error_message err);
460       exit 1 in
461   client
462
463 and stop_client client =
464   Rpc_client.shut_down client
465
466 and string_of_variable = function
467   | `unit_t -> ""
468   | `bool_t b -> string_of_bool b
469   | `string_t s -> s
470   | `int_t i -> i (* passed on the wire as a string *)
471   | `float_t f -> string_of_float f
472
473 let () =
474   try main ()
475   with
476     (* Pretty print some of the exceptions that main can throw. *)
477   | Rpc.Rpc_server err ->
478     eprintf "whenjobs: rpc error: %s\n" (Rpc.string_of_server_error err);
479     suggest_check_server_logs ();
480     exit 1
481   | Failure msg ->
482     eprintf "whenjobs: error: %s\n" msg;
483     exit 1
484   | Invalid_argument msg ->
485     eprintf "whenjobs: invalid argument: %s\n" msg;
486     exit 1
487   | exn ->
488     eprintf "whenjobs: error: %s\n" (Printexc.to_string exn);
489     exit 1