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