Documentation
[vsys.git] / dirwatcher.ml
1 (** Watches directories for events. Agnostic to vsys semantics of backends and
2 frontends *)
3 open Inotify
4 open Fdwatcher
5 open Printf
6 open Globals
7
8 (* I don't know if a wd corresponding to a deleted directory is evicted or just
9  * leaks - fix implementation of rmdir accordingly
10  *)
11
12 let wdmap = Hashtbl.create 1024
13
14 let fd = Inotify.init ()
15
16 let handle_dir_event dirname evlist str = 
17     let fname = String.concat "/" [dirname;str] in
18         printf "File: %s. " fname;List.iter 
19                   (fun e -> 
20                      printf "Event: %s\n" (string_of_event e)) 
21                   evlist;
22         flush Pervasives.stdout
23
24 let add_watch dir events handler =
25   printf "Adding watch for %s\n" dir;flush Pervasives.stdout;
26   let wd = Inotify.add_watch fd dir events in
27       Hashtbl.add wdmap wd (dir,handler)
28
29 let asciiz s =
30   let rec findfirstnul str idx len =
31     if ((idx==len) || 
32       (str.[idx]==(char_of_int 0))) then idx
33       else
34         findfirstnul str (idx+1) len
35   in
36   let nulterm = findfirstnul s 0 (String.length s) in
37     String.sub s 0 nulterm
38
39 let receive_event (eventdescriptor:fname_and_fd) (bla:fname_and_fd) =
40   let (_,fd) = eventdescriptor in
41       let evs = Inotify.read fd in
42         List.iter (fun x->
43                 match x with
44                   | (wd,evlist,_,Some(str)) ->
45                       let purestr = asciiz(str) in
46                       let (dirname,handler) = 
47                         try Hashtbl.find wdmap wd with Not_found->printf "Unknown watch descriptor\n";raise Not_found
48                       in
49                         (
50                         match handler with
51                           | None->handle_dir_event dirname evlist purestr
52                           | Some(handler)->handler dirname evlist purestr
53                         )
54                   | _ -> ()) 
55           evs
56
57 let initialize () =
58   Fdwatcher.add_fd (None,fd) (None,fd) receive_event