Change whenjobs --set syntax (NOTE: breaks compatibility).
[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 set_type t =
79     typ :=
80       match t with
81       | "bool"|"boolean" -> `Bool
82       | "string" -> `String
83       | "int" -> `Int
84       | "float"|"double" -> `Float
85       | "unit" -> `Unit
86       | _ ->
87         eprintf "whenjobs: --type: unknown type (%s)\n" t;
88         exit 1
89   in
90
91   let display_version () =
92     printf "%s %s\n" Config.package_name Config.package_version;
93     exit 0
94   in
95
96   let argspec = Arg.align [
97     "--cancel", Arg.Unit (set_mode `Cancel), " Cancel a job";
98     "--daemon-start", Arg.Unit (set_mode `Daemon_start), " Start the daemon";
99     "--daemon-status", Arg.Unit (set_mode `Daemon_status), " Display the status of the daemon";
100     "--daemon-stop", Arg.Unit (set_mode `Daemon_stop), " Stop the daemon";
101     "--daemon-restart", Arg.Unit (set_mode `Daemon_restart), " Restart the daemon";
102     "-e", Arg.Unit (set_mode `Edit), " Edit and upload the script";
103     "--edit", Arg.Unit (set_mode `Edit), " Edit and upload the script";
104     "--get", Arg.Unit (set_mode `Get), "var Display the variable";
105     "--jobs", Arg.Unit (set_mode `Jobs), " List running jobs";
106     "-l", Arg.Unit (set_mode `List), " List the script";
107     "--list", Arg.Unit (set_mode `List), " List the script";
108     "--lib", Arg.Set_string libdir, "dir Specify directory that contains pa_when.cmo";
109     "--set", Arg.Unit (set_mode `Set), " Set the variable";
110     "--start", Arg.Unit (set_mode `Start), "name Start a job manually";
111     "--tail", Arg.Unit (set_mode `Tail), "serial Tail job output";
112     "--type", Arg.String set_type, "bool|int|float|string|.. Set the variable type";
113     "--upload", Arg.Unit (set_mode `Upload), " Upload the script";
114     "--variables", Arg.Unit (set_mode `Variables), " Display all variables and values";
115     "-V", Arg.Unit display_version, " Display version number and exit";
116     "--version", Arg.Unit display_version, " Display version number and exit";
117   ] in
118
119   (* anon_fun normally just collects up the anonymous arguments as
120    * strings, and most modes just use 'args' as a list of strings.
121    * However for `Set mode we need to record the type of each argument
122    * as well, so we keep that in a separate list (argtypes).
123    *)
124   let argtypes = ref [] in
125   let anon_fun str = argtypes := (str, !typ) :: !argtypes in
126
127   let usage_msg = "\
128 Whenjobs is a powerful but simple cron replacement.
129 Whenjobs copyright (C) 2012 Red Hat Inc.
130
131 Editing the script:
132
133   whenjobs -e | --edit
134   whenjobs -l | --list
135
136 Get and set variables:
137
138   whenjobs --get variable
139   whenjobs --set variable=value
140
141 Start and stop the per-user daemon:
142
143   whenjobs --daemon-start | --daemon-stop | --daemon-status
144
145 For documentation see the whenjobs(1) man page.
146
147 Options:
148 " in
149
150   Arg.parse argspec anon_fun usage_msg;
151
152   let mode = !mode in
153   let argtypes = List.rev !argtypes in
154   let args = List.map fst argtypes in
155   let nr_args = List.length args in
156   let arg1 = match args with [] -> "" | a::_ -> a in
157
158   (* Depending on the selected mode, perform a different action. *)
159   match mode with
160   | None ->
161     eprintf "whenjobs: no operation selected.\n";
162     suggest_help ();
163     exit 1
164
165   | Some `Edit ->
166     unused_error args "-e";
167     edit_file ()
168
169   | Some `List ->
170     unused_error args "-l";
171     list_file ()
172
173   | Some `Upload ->
174     unused_error args "--upload";
175     upload_file ()
176
177   | Some `Set ->
178     if nr_args = 2 && not (String.contains arg1 '=') then (
179       eprintf "'whenjobs --set variable value' is the old whenjobs <= 0.5 syntax!\n";
180       eprintf "You need to change this to:\n";
181       eprintf "  whenjobs --set variable=value\n";
182       suggest_help ();
183       exit 1
184     );
185     (* Just ignore the case where no variables are defined, to make
186      * it easier to write shell scripts.
187      *)
188     if nr_args > 0 then
189       set_variables argtypes
190
191   | Some `Get ->
192     if nr_args != 1 then (
193       eprintf "whenjobs --get variable\n";
194       suggest_help ();
195       exit 1
196     );
197     get_variable arg1
198
199   | Some `Variables ->
200     unused_error args "--variables";
201     list_variables ()
202
203   | Some `Daemon_start ->
204     unused_error args "--daemon-start";
205     daemon_start ()
206
207   | Some `Daemon_stop ->
208     unused_error args "--daemon-stop";
209     daemon_stop ()
210
211   | Some `Daemon_restart ->
212     unused_error args "--daemon-restart";
213     daemon_restart ()
214
215   | Some `Daemon_status ->
216     unused_error args "--daemon-status";
217     daemon_status ()
218
219   | Some `Jobs ->
220     unused_error args "--jobs";
221     jobs ()
222
223   | Some `Cancel ->
224     if nr_args != 1 then (
225       eprintf "whenjobs --cancel serial\n";
226       suggest_help ();
227       exit 1
228     );
229     cancel_job arg1
230
231   | Some `Start ->
232     if nr_args != 1 then (
233       eprintf "whenjobs --start jobname\n";
234       eprintf "If 'value' contains spaces, you may need to quote it.\n";
235       suggest_help ();
236       exit 1
237     );
238     start_job arg1
239
240   | Some `Tail ->
241     if nr_args != 1 then (
242       eprintf "whenjobs --tail serial\n";
243       suggest_help ();
244       exit 1
245     );
246     tail arg1
247
248 and edit_file () =
249   (* If there is no initial file, create an empty one containing the
250    * tutorial.
251    *)
252   let file = get_jobs_filename () in
253   if not (Sys.file_exists file) then
254     create_tutorial file;
255
256   (* Is $EDITOR set?  If not, use a default. *)
257   let editor = try getenv "EDITOR" with Not_found -> "vi" in
258
259   (* Get the (size, MD5) of the file to tell if it changed. *)
260   let file_stamp () =
261     try (lstat file).st_size, Digest.file file
262     with Unix_error (err, fn, _) ->
263       eprintf "whenjobs: %s: %s: %s\n" fn file (error_message err);
264       exit 1
265   in
266   let old_stamp = file_stamp () in
267
268   let cmd = sprintf "%s %s" editor file in
269   if Sys.command cmd != 0 then (
270     eprintf "whenjobs: error editing file (is $EDITOR set correctly?)\n";
271     exit 1
272   );
273
274   let new_stamp = file_stamp () in
275
276   if old_stamp <> new_stamp then
277     upload_file ()
278
279 and list_file () =
280   let file = get_jobs_filename () in
281   if not (Sys.file_exists file) then (
282     eprintf "whenjobs: there is no jobs file, use 'whenjobs -e' to create one\n";
283     exit 1
284   );
285   let chan = open_in file in
286   let rec loop () =
287     printf "%s\n" (input_line chan);
288     loop ()
289   in
290   (try loop () with End_of_file -> ());
291   close_in chan
292
293 and upload_file () =
294   (* Recompile the jobs file. *)
295   let file = get_jobs_filename () in
296   let cmo_file = sprintf "%s/jobs.cmo" jobsdir in
297   let cmd = sprintf "ocamlfind ocamlc -I +camlp4 -I %s -package unix,camlp4.lib -pp 'camlp4o %s/pa_when.cmo' -c %s -o %s"
298     !libdir !libdir file cmo_file in
299   if Sys.command cmd <> 0 then (
300     eprintf "whenjobs: could not compile jobs script, see earlier error messages\n";
301     eprintf "compile command was:\n%s\n" cmd;
302     exit 1
303   );
304
305   (* Test-load the jobs file to ensure it makes sense. *)
306   Whenfile.init Whenstate.empty;
307   (try
308      Dynlink.loadfile cmo_file
309    with
310      Dynlink.Error err ->
311        eprintf "whenjobs: %s\n" (Dynlink.error_message err);
312        (* Since it failed, unlink it. *)
313        (try unlink cmo_file with Unix_error _ -> ());
314        exit 1
315   );
316
317   (* OK now let's tell the daemon to reload it. *)
318   let client = start_client () in
319   (match Whenproto_clnt.When.V1.reload_file client () with
320   | `ok -> ()
321   | `error msg ->
322     eprintf "whenjobs: reload: %s\n" msg;
323     suggest_check_server_logs ();
324     exit 1
325   );
326   stop_client client
327
328 and set_variables argtypes =
329   let vars = List.map (
330     fun (def, typ) ->
331       (* 'def' should have the form "name=value".  The value part may
332        * be missing, but the equals sign is required.
333        *)
334       let i =
335         try String.index def '='
336         with Not_found ->
337           eprintf "whenjobs: set: missing = sign in variable definition\n";
338           suggest_help ();
339           exit 1 in
340       let name = String.sub def 0 i in
341       let value = String.sub def (i+1) (String.length def - (i+1)) in
342       let value = value_of_string value typ in
343       { Whenproto_aux.sv_name = name; sv_value = value }
344   ) argtypes in
345   let vars = Array.of_list vars in
346
347   let client = start_client () in
348   (match Whenproto_clnt.When.V1.set_variables client vars with
349   | `ok -> ()
350   | `error msg ->
351     eprintf "whenjobs: set: %s\n" msg;
352     suggest_check_server_logs ();
353     exit 1
354   );
355   stop_client client
356
357 and get_variable name =
358   let client = start_client () in
359   let value = Whenproto_clnt.When.V1.get_variable client name in
360   print_endline (string_of_variable value);
361   stop_client client
362
363 and list_variables () =
364   let client = start_client () in
365   let names = Whenproto_clnt.When.V1.get_variable_names client () in
366   Array.iter (
367     fun name ->
368       let value = Whenproto_clnt.When.V1.get_variable client name in
369       printf "%s=%s\n" name (string_of_variable value)
370   ) names;
371   stop_client client
372
373 and daemon_start () =
374   assert false
375
376 and daemon_stop () =
377   let client = start_client () in
378   (match Whenproto_clnt.When.V1.exit_daemon client () with
379   | `ok -> ()
380   | `error msg ->
381     eprintf "whenjobs: daemon-stop: %s\n" msg;
382     suggest_check_server_logs ();
383     exit 1
384   );
385   stop_client client
386
387 and daemon_restart () =
388   assert false
389
390 and daemon_status () =
391   assert false
392
393 and jobs () =
394   let client = start_client () in
395   let jobs = Whenproto_clnt.When.V1.get_jobs client () in
396   stop_client client;
397
398   let cmp { Whenproto_aux.job_name = name1; job_serial = serial1 }
399       { Whenproto_aux.job_name = name2; job_serial = serial2 } =
400     let i = compare name1 name2 in
401     if i <> 0 then i
402     else
403       compare_big_int (big_int_of_string serial1) (big_int_of_string serial2)
404   in
405   Array.sort cmp jobs;
406
407   Array.iter (
408     fun { Whenproto_aux.job_serial = serial; job_name = name;
409           job_tmpdir = tmpdir; job_start_time = time } ->
410       printf "%s %s\n\trunning in: %s\n\tstarted at: %s\n"
411         serial name tmpdir
412         (string_of_time_t ~localtime:true (Int64.to_float time))
413   ) jobs
414
415 and cancel_job serial =
416   let client = start_client () in
417   (match Whenproto_clnt.When.V1.cancel_job client serial with
418   | `ok -> ()
419   | `error msg ->
420     eprintf "whenjobs: cancel-job: %s\n" msg;
421     suggest_check_server_logs ();
422     exit 1
423   );
424   stop_client client
425
426 and start_job name =
427   let client = start_client () in
428   (match Whenproto_clnt.When.V1.start_job client name with
429   | `ok -> ()
430   | `error msg ->
431     eprintf "whenjobs: start-job: %s\n" msg;
432     suggest_check_server_logs ();
433     exit 1
434   );
435   stop_client client
436
437   (* This only works for local.  If we ever make whenjobs work
438    * remotely we'll have to change the implementation to use
439    * the server.
440    *)
441 and tail serial =
442   let client = start_client () in
443   let job = Whenproto_clnt.When.V1.get_job client serial in
444   stop_client client;
445   let cmd =
446     sprintf "tail -f %s/output.txt"
447       (Filename.quote job.Whenproto_aux.job_tmpdir) in
448   exit (Sys.command cmd)
449
450 and unused_error args op =
451   if args <> [] then (
452     eprintf "whenjobs %s: unused parameters on the command line.\n" op;
453     suggest_help ();
454     exit 1
455   )
456
457 and suggest_help () =
458   eprintf "Use 'whenjobs --help' for a summary of options or read whenjobs(1) man page.\n"
459
460 and suggest_check_server_logs () =
461   eprintf "Look at the server logs (/var/log/cron or /var/log/syslog usually) for\n";
462   eprintf "further information on why this daemon operation failed.\n"
463
464 and get_jobs_filename () =
465   sprintf "%s/jobs.ml" jobsdir
466
467 and create_tutorial file =
468   let chan = open_out file in
469   output_string chan Tutorial.tutorial;
470   close_out chan
471
472 and start_client () =
473   let addr = sprintf "%s/socket" jobsdir in
474   let client =
475     try
476       Whenproto_clnt.When.V1.create_client
477         (Rpc_client.Unix addr)
478         Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
479     with
480     | Unix_error ((ECONNREFUSED|ENOENT), _, _) ->
481       eprintf "whenjobs: error: the daemon ('whenjobsd') is not running\n";
482       eprintf "Use 'whenjobs --daemon-start' to start the daemon.\n";
483       exit 1
484     | Unix_error (err, fn, _) ->
485       eprintf "whenjobs: %s: %s: %s\n" fn addr (error_message err);
486       exit 1 in
487   client
488
489 and stop_client client =
490   Rpc_client.shut_down client
491
492 and string_of_variable = function
493   | `unit_t -> ""
494   | `bool_t b -> string_of_bool b
495   | `string_t s -> s
496   | `int_t i -> i (* passed on the wire as a string *)
497   | `float_t f -> string_of_float f
498
499 and value_of_string value = function
500   | `Bool ->
501     (match value with
502     | "true"|"t"|"yes"|"y"|"on"|"1" -> `bool_t true
503     | "false"|"f"|"no"|"n"|"off"|"0" -> `bool_t false
504     | _ ->
505       eprintf "whenjobs: variable does not have a boolean value\n";
506       exit 1
507     )
508   | `String -> `string_t value
509   | `Int ->
510     (try ignore (big_int_of_string value)
511      with Failure _ ->
512        eprintf "whenjobs: variable is not an integer\n";
513        exit 1
514     );
515     `int_t value (* the string is what we pass over the wire *)
516   | `Float ->
517     (try `float_t (float_of_string value)
518      with Failure _ ->
519        eprintf "whenjobs: variable is not a floating point number\n";
520        exit 1
521     )
522   | `Unit ->
523     if value <> "" then (
524       eprintf "whenjobs: unit variables must be empty strings\n";
525       exit 1
526     );
527     `unit_t
528
529 let () =
530   try main ()
531   with
532     (* Pretty print some of the exceptions that main can throw. *)
533   | Rpc.Rpc_server err ->
534     eprintf "whenjobs: rpc error: %s\n" (Rpc.string_of_server_error err);
535     suggest_check_server_logs ();
536     exit 1
537   | Failure msg ->
538     eprintf "whenjobs: error: %s\n" msg;
539     exit 1
540   | Invalid_argument msg ->
541     eprintf "whenjobs: invalid argument: %s\n" msg;
542     exit 1
543   | exn ->
544     eprintf "whenjobs: error: %s\n" (Printexc.to_string exn);
545     exit 1