2 * Copyright (C) 2012 Red Hat Inc.
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.
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.
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.
25 (* Ensures that Whentools module is linked to the whenjobs tool. *)
26 let _ = Whentools.set_variable
28 let libdir = ref Libdir.libdir
31 (* Running the program as root is a mistake. It must be run as a
34 let euid = geteuid () in
36 eprintf "whenjobs: this program must not be run as root\n";
40 (* $HOME must be defined and must exist and be a directory and must be
41 * owned by the current user.
46 eprintf "whenjobs: $HOME environment variable must be defined\n";
51 with Unix_error (err, fn, _) ->
52 eprintf "whenjobs: %s: %s ($HOME): %s\n" fn home (error_message err);
54 if stat.st_kind != S_DIR then (
55 eprintf "whenjobs: %s ($HOME): not a directory\n" home;
59 if stat.st_uid != euid then (
60 eprintf "whenjobs: %s ($HOME): not owned by the current user (uid %d)\n"
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 _ -> ());
72 (* Parse the command line arguments. *)
73 let mode = ref None in
74 let typ = ref `String in
76 let set_mode m () = mode := Some m in
81 | "bool"|"boolean" -> `Bool
84 | "float"|"double" -> `Float
87 eprintf "whenjobs: --type: unknown type (%s)\n" t;
91 let display_version () =
92 printf "%s %s\n" Config.package_name Config.package_version;
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";
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
128 let argtypes = ref [] in
129 let anon_fun str = argtypes := (str, !typ) :: !argtypes in
132 Whenjobs is a powerful but simple cron replacement.
133 Whenjobs copyright (C) 2012 Red Hat Inc.
140 Get and set variables:
142 whenjobs --get variable
143 whenjobs --set variable=value
145 Start and stop the per-user daemon:
147 whenjobs --daemon-start | --daemon-stop | --daemon-status
149 For documentation see the whenjobs(1) man page.
154 Arg.parse argspec anon_fun usage_msg;
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
162 (* Depending on the selected mode, perform a different action. *)
165 eprintf "whenjobs: no operation selected.\n";
170 unused_error args "-e";
174 unused_error args "-l";
178 unused_error args "--upload";
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";
189 (* Just ignore the case where no variables are defined, to make
190 * it easier to write shell scripts.
193 set_variables argtypes
197 test_variables argtypes
201 whisper_variables argtypes
204 if nr_args != 1 then (
205 eprintf "whenjobs --get variable\n";
212 unused_error args "--variables";
215 | Some `Daemon_start ->
216 unused_error args "--daemon-start";
219 | Some `Daemon_stop ->
220 unused_error args "--daemon-stop";
223 | Some `Daemon_restart ->
224 unused_error args "--daemon-restart";
227 | Some `Daemon_status ->
228 unused_error args "--daemon-status";
232 unused_error args "--jobs";
236 if nr_args != 1 then (
237 eprintf "whenjobs --cancel serial\n";
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";
253 if nr_args != 1 then (
254 eprintf "whenjobs --tail serial\n";
261 unused_error args "--job-names";
265 (* If there is no initial file, create an empty one containing the
268 let file = get_jobs_filename () in
269 if not (Sys.file_exists file) then
270 create_tutorial file;
272 (* Is $EDITOR set? If not, use a default. *)
273 let editor = try getenv "EDITOR" with Not_found -> "vi" in
275 (* Get the (size, MD5) of the file to tell if it changed. *)
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);
282 let old_stamp = file_stamp () in
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";
290 let new_stamp = file_stamp () in
292 if old_stamp <> new_stamp then
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";
301 let chan = open_in file in
303 printf "%s\n" (input_line chan);
306 (try loop () with End_of_file -> ());
310 (* Recompile the jobs file(s). *)
311 let files = get_multijobs_filenames () in
315 if not Config.have_ocamlopt then
317 sprintf "%s c -I +camlp4 -I %s -package unix,camlp4.lib -pp 'camlp4o %s/pa_when.cmo' -c %s"
318 Config.ocamlfind !libdir !libdir file
321 let base = Filename.chop_extension file in (* without .ml suffix *)
322 sprintf "%s opt -I +camlp4 -I %s -package unix,camlp4.lib -pp 'camlp4o %s/pa_when.cmo' -c %s &&\n%s opt -shared -linkall %s.cmx -o %s.cmxs"
323 Config.ocamlfind !libdir !libdir file
324 Config.ocamlfind base base
326 if Sys.command cmd <> 0 then (
327 eprintf "whenjobs: %s: could not compile jobs script, see earlier errors\n"
329 eprintf "compile command was:\n%s\n" cmd;
334 let suffix = if not Dynlink.is_native then "cmo" else "cmxs" in
336 let compiled_files = List.map (
338 let n = String.length file in
339 if n < 4 then assert false;
340 sprintf "%s.%s" (String.sub file 0 (n-3)) suffix
343 (* Test-load the jobs files to ensure they make sense. *)
344 Whenfile.init Whenstate.empty;
346 List.iter Dynlink.loadfile compiled_files
349 eprintf "whenjobs: dynlink: %s\n" (Dynlink.error_message err);
350 (* Since it failed, unlink the compiled files. *)
351 List.iter (fun f -> try unlink f with Unix_error _ -> ()) compiled_files;
355 (* OK now let's tell the daemon to reload it. *)
356 let client = start_client () in
357 (match Whenproto_clnt.When.V1.reload_file client () with
360 eprintf "whenjobs: reload: %s\n" msg;
361 suggest_check_server_logs ();
366 and set_variables argtypes =
367 let vars = List.map (
369 (* 'def' should have the form "name=value". The value part may
370 * be missing, but the equals sign is required.
373 try String.index def '='
375 eprintf "whenjobs: set: missing = sign in variable definition\n";
378 let name = String.sub def 0 i in
379 let value = String.sub def (i+1) (String.length def - (i+1)) in
380 let value = value_of_string value typ in
381 { Whenproto_aux.sv_name = name; sv_value = value }
383 let vars = Array.of_list vars in
385 let client = start_client () in
386 (match Whenproto_clnt.When.V1.set_variables client vars with
389 eprintf "whenjobs: set: %s\n" msg;
390 suggest_check_server_logs ();
395 and test_variables argtypes =
396 let vars = List.map (
398 (* 'def' should have the form "name=value". The value part may
399 * be missing, but the equals sign is required.
402 try String.index def '='
404 eprintf "whenjobs: test: missing = sign in variable definition\n";
407 let name = String.sub def 0 i in
408 let value = String.sub def (i+1) (String.length def - (i+1)) in
409 let value = value_of_string value typ in
410 { Whenproto_aux.sv_name = name; sv_value = value }
412 let vars = Array.of_list vars in
414 let client = start_client () in
415 let jobnames = Whenproto_clnt.When.V1.test_variables client vars in
418 Array.iter print_endline jobnames
420 and whisper_variables argtypes =
421 let vars = List.map (
423 (* 'def' should have the form "name=value". The value part may
424 * be missing, but the equals sign is required.
427 try String.index def '='
429 eprintf "whenjobs: whisper: missing = sign in variable definition\n";
432 let name = String.sub def 0 i in
433 let value = String.sub def (i+1) (String.length def - (i+1)) in
434 let value = value_of_string value typ in
435 { Whenproto_aux.sv_name = name; sv_value = value }
437 let vars = Array.of_list vars in
439 let client = start_client () in
440 (match Whenproto_clnt.When.V1.whisper_variables client vars with
443 eprintf "whenjobs: whisper: %s\n" msg;
444 suggest_check_server_logs ();
449 and get_variable name =
450 let client = start_client () in
451 let value = Whenproto_clnt.When.V1.get_variable client name in
452 print_endline (string_of_variable value);
455 and list_variables () =
456 let client = start_client () in
457 let names = Whenproto_clnt.When.V1.get_variable_names client () in
460 let value = Whenproto_clnt.When.V1.get_variable client name in
461 printf "%s=%s\n" name (string_of_variable value)
465 and daemon_start () =
466 exit (Sys.command "whenjobsd")
469 let client = start_client () in
470 (match Whenproto_clnt.When.V1.exit_daemon client () with
473 eprintf "whenjobs: daemon-stop: %s\n" msg;
474 suggest_check_server_logs ();
479 and daemon_restart () =
481 let client = start_client_no_exit () in
482 ignore (Whenproto_clnt.When.V1.exit_daemon client ());
489 and daemon_status () =
492 let client = start_client_no_exit () in
493 let r = Whenproto_clnt.When.V1.ping_daemon client () in
498 print_endline (if r then "up" else "down")
501 let client = start_client () in
502 let jobs = Whenproto_clnt.When.V1.get_jobs client () in
505 let cmp { Whenproto_aux.job_name = name1; job_serial = serial1 }
506 { Whenproto_aux.job_name = name2; job_serial = serial2 } =
507 let i = compare name1 name2 in
510 compare_big_int (big_int_of_string serial1) (big_int_of_string serial2)
515 fun { Whenproto_aux.job_serial = serial; job_name = name;
516 job_tmpdir = tmpdir; job_start_time = time } ->
517 printf "%s %s\n\trunning in: %s\n\tstarted at: %s\n"
519 (string_of_time_t ~localtime:true (Int64.to_float time))
522 and cancel_job serial =
523 let client = start_client () in
524 (match Whenproto_clnt.When.V1.cancel_job client serial with
527 eprintf "whenjobs: cancel-job: %s\n" msg;
528 suggest_check_server_logs ();
534 let client = start_client () in
535 (match Whenproto_clnt.When.V1.start_job client name with
538 eprintf "whenjobs: start-job: %s\n" msg;
539 suggest_check_server_logs ();
544 (* This only works for local. If we ever make whenjobs work
545 * remotely we'll have to change the implementation to use
549 let client = start_client () in
550 let job = Whenproto_clnt.When.V1.get_job client serial in
553 sprintf "tail -f %s/output.txt"
554 (Filename.quote job.Whenproto_aux.job_tmpdir) in
555 exit (Sys.command cmd)
558 let client = start_client () in
559 let names = Whenproto_clnt.When.V1.get_job_names client () in
561 Array.iter print_endline names
563 and unused_error args op =
565 eprintf "whenjobs %s: unused parameters on the command line.\n" op;
570 and suggest_help () =
571 eprintf "Use 'whenjobs --help' for a summary of options or read whenjobs(1) man page.\n"
573 and suggest_check_server_logs () =
574 eprintf "Look at the server logs (/var/log/cron or /var/log/syslog usually) for\n";
575 eprintf "further information on why this daemon operation failed.\n"
577 and get_jobs_filename () =
578 sprintf "%s/jobs.ml" jobsdir
580 and get_multijobs_filenames () =
582 let files = Array.to_list (Sys.readdir jobsdir) in
583 let files = List.filter (fun file -> string_endswith file ".ml") files in
584 let files = List.map (fun file -> jobsdir // file) files in
585 List.sort compare files
587 and create_tutorial file =
588 let chan = open_out file in
589 output_string chan Tutorial.tutorial;
592 and start_client () =
593 let addr = sprintf "%s/socket" jobsdir in
595 try start_client_no_exit ()
597 | Unix_error ((ECONNREFUSED|ENOENT), _, _) ->
598 eprintf "whenjobs: error: the daemon ('whenjobsd') is not running\n";
599 eprintf "Use 'whenjobs --daemon-start' to start the daemon.\n";
601 | Unix_error (err, fn, _) ->
602 eprintf "whenjobs: %s: %s: %s\n" fn addr (error_message err);
606 and start_client_no_exit () =
607 let addr = sprintf "%s/socket" jobsdir in
608 Whenproto_clnt.When.V1.create_client
609 (Rpc_client.Unix addr)
610 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
612 and stop_client client =
613 Rpc_client.shut_down client
615 and string_of_variable = function
617 | `bool_t b -> string_of_bool b
619 | `int_t i -> i (* passed on the wire as a string *)
620 | `float_t f -> string_of_float f
622 and value_of_string value = function
625 | "true"|"t"|"yes"|"y"|"on"|"1" -> `bool_t true
626 | "false"|"f"|"no"|"n"|"off"|"0" -> `bool_t false
628 eprintf "whenjobs: variable does not have a boolean value\n";
631 | `String -> `string_t value
633 (try ignore (big_int_of_string value)
635 eprintf "whenjobs: variable is not an integer\n";
638 `int_t value (* the string is what we pass over the wire *)
640 (try `float_t (float_of_string value)
642 eprintf "whenjobs: variable is not a floating point number\n";
646 if value <> "" then (
647 eprintf "whenjobs: unit variables must be empty strings\n";
655 (* Pretty print some of the exceptions that main can throw. *)
656 | Rpc.Rpc_server err ->
657 eprintf "whenjobs: rpc error: %s\n" (Rpc.string_of_server_error err);
658 suggest_check_server_logs ();
661 eprintf "whenjobs: error: %s\n" msg;
663 | Invalid_argument msg ->
664 eprintf "whenjobs: invalid argument: %s\n" msg;
667 eprintf "whenjobs: error: %s\n" (Printexc.to_string exn);