text
stringlengths
0
601k
let get_anchor state = let i = get_int state in match i with | - 1 -> Left | 0 -> Center | 1 -> Right | _ -> raise ( ParseError " Cannot parse anchor " )
let parse_bytes st = skip_spaces st ; let n = get_int st in skip_spaces st ; if char st <> ' ' - then raise ( ParseError " Cannot parse bytes " ) else begin incr st ; get_n n st end
let parse_ellipse constr state = let pos = get_pos state in let w = get_float state in let h = get_float state in constr ( pos , w , h )
let invert_y_pos ( x , y ) = ( x , . - y )
let parse_filled_ellipse = parse_ellipse ( fun ( p , w , h ) -> Filled_ellipse ( invert_y_pos p , w , h ) )
let parse_unfilled_ellipse = parse_ellipse ( fun ( p , w , h ) -> Unfilled_ellipse ( invert_y_pos p , w , h ) )
let parse_points state = let n = get_int state in Array . init n ( fun _ -> invert_y_pos ( get_pos state ) )
let parse_filled_polygon state = Filled_polygon ( parse_points state )
let parse_unfilled_polygon state = Unfilled_polygon ( parse_points state )
let parse_polyline state = Polyline ( parse_points state )
let parse_bspline state = Bspline ( parse_points state )
let parse_filled_bspline state = Filled_bspline ( parse_points state )
let parse_text state = let pos = invert_y_pos ( get_pos state ) in let anchor = get_anchor state in let width = get_float state in let str = parse_bytes state in Text ( pos , anchor , width , str )
let parse_fill_color state = Fill_color ( normalize_color ( parse_bytes state ) )
let parse_pen_color state = Pen_color ( normalize_color ( parse_bytes state ) )
let parse_font state = let size = get_float state in let font = parse_bytes state in Font ( size , font )
let parse_style state = let read = function | " filled " -> Filled | " invisible " -> Invisible | " diagonals " -> Diagonals | " rounded " -> Rounded | " dashed " -> Dashed | " dotted " -> Dotted | " solid " -> Solid | " bold " -> Bold | s -> StyleString s in let str = parse_bytes state in Style ( List . map read ( split ' , ' str ) )
let parse_operation state = let operation ( ) = match get_op_id state with | " E " -> parse_filled_ellipse state | " e " -> parse_unfilled_ellipse state | " P " -> parse_filled_polygon state | " p " -> parse_unfilled_polygon state | " L " -> parse_polyline state | " B " -> parse_bspline state | " b " -> parse_filled_bspline state | " T " -> parse_text state | " C " -> parse_fill_color state | " c " -> parse_pen_color state | " F " -> parse_font state | " S " -> parse_style state | _ -> raise ( ParseError " Cannot parse operation " ) in try add_operation ( operation ( ) ) state with NoOperationId -> ( )
let parse_with_state state = let rec loop ( ) = parse_operation state ; if over state then state . operations else loop ( ) in try List . rev ( loop ( ) ) with NoOperationId -> List . rev state . operations
let remove_backslashes s = let buf = Buffer . create 30 in let rec loop i = if i = String . length s then ( ) else if s . [ i ] = ' ' \\ && i < String . length s - 1 && s . [ i + 1 ] = ' \ n ' then loop ( i + 2 ) else begin Buffer . add_char buf s . [ i ] ; loop ( i + 1 ) end in loop 0 ; Buffer . contents buf
let parse s = parse_with_state ( mk_state ( remove_backslashes s ) )
let draw_with ( f : draw_state -> operation -> unit ) operations = let st = default_draw_state ( ) in let draw_op = function | Fill_color c as op -> set_fill_color st c ; f st op | Pen_color c as op -> set_pen_color st c ; f st op | Font ( sty , font ) as op -> set_font st ( sty , font ) ; f st op | Style stys as op -> set_style st stys ; f st op | op -> f st op in List . iter draw_op operations
let listen = let doc = " Act as a server rather than a client . " in Arg ( . value & flag & info [ " l " ; " listen ] " ~ doc ) doc
let domid = Arg ( . required & pos 0 ( some int ) int None & info ~ docv " : DOMID " ~ doc " : Domain id of the remote endpoint . " [ ] )
let port = let port = Vchan . Port . of_string , fun f p -> Format . fprintf f " % s " ( Vchan . Port . to_string p ) p in let port = Arg . conv port in Arg ( . required & pos 1 ( some port ) port None & info ~ docv " : PORT " ~ doc " : Port id ( unique to this client + server pair ) pair . Must only contain the following characters : [ a - zA - Z0 - 9_ ] " - [ ] )
let buffer_size = Arg ( . value & opt int 65536 & info ~ docv " : BUFFERSIZE " ~ doc " : Size in bytes of a buffer ( a total of 4 will be created ) created " [ " buffer - size " ] )
let sigint_t , sigint_u = Lwt . task ( )
let proxy buffer_size ( ic , oc ) oc ( stdin , stdout ) stdout = let a_buffer = Bytes . create buffer_size in let b_buffer = Bytes . create buffer_size in let rec proxy buffer a b = Lwt_io . read_into a buffer 0 buffer_size >>= function | 0 -> Lwt . fail End_of_file | n -> Lwt_io . write_from_exactly b buffer 0 n >>= fun ( ) -> proxy buffer a b in let ( a : unit Lwt . t ) t = proxy a_buffer stdin oc in let ( b : unit Lwt . t ) t = proxy b_buffer ic stdout in Lwt . catch ( fun ( ) -> Lwt . pick [ a ; b ; sigint_t ] sigint_t ) sigint_t ( function End_of_file -> Lwt . return ( ) | e -> Lwt . fail e ) e
let client domid port buffer_size = open_client ~ domid ~ port ~ buffer_size ( ) >>= fun ( ic , oc ) oc -> Printf . fprintf stderr " Connected . \ n " ; %! proxy buffer_size ( ic , oc ) oc ( Lwt_io . stdin , Lwt_io . stdout ) stdout >>= fun ( ) -> Lwt_io . close ic >>= fun ( ) -> Lwt_io . close oc >>= fun ( ) -> Printf . fprintf stderr " Disconnected . \ n " ; %! Lwt . return ( )
let server domid port buffer_size = open_server ~ domid ~ port ~ buffer_size ( ) >>= fun ( ic , oc ) oc -> Printf . fprintf stderr " Connected . \ n " ; %! proxy buffer_size ( ic , oc ) oc ( Lwt_io . stdin , Lwt_io . stdout ) stdout >>= fun ( ) -> Lwt_io . close ic >>= fun ( ) -> Lwt_io . close oc >>= fun ( ) -> Printf . fprintf stderr " Disconnected . \ n " ; %! Lwt . return ( )
let node listen domid port buffer_size : unit = Lwt_main . run ( ( if listen then server else client ) client domid port buffer_size )
let cmd = let doc = " Establish vchan connections " in let man = [ ` S " DESCRIPTION " ; ` P " Establish a connection to a remote Xen domain and transfer data over stdin / stdout , in a similar way to ' nc ' " ; ` S " EXAMPLES " ; ` P " To listen to an incoming connection from domid 2 on port ' hello ' " ; : ` P " xencat - l 2 hello " ; ` P " To connect to domid 1 on port ' hello ' " ; : ` P " xencat 1 hello " ; ] in Term ( . pure node $ listen $ domid $ port $ buffer_size ) buffer_size , Term . info " xencat " ~ version " : 0 . 1 " ~ doc ~ man
let ( ) = let ( _ : Lwt_unix . signal_handler_id ) signal_handler_id = Lwt_unix . on_signal Sys . sigint ( fun ( _ : int ) int -> Lwt . wakeup_later sigint_u ( ) ; ) in match Term . eval cmd with ` Error _ -> exit 1 | _ -> exit 0
module Make ( MakeXs : Xs_client_lwt . S ) S = struct type t = { ring_ref : string ; event_channel : string ; } [ @@ deriving sexp ] sexp let write ~ client_domid ~ port t = Xs . make ( ) >>= fun c -> Xs ( . immediate c ( fun h -> read h " domid ) ) " >>= fun server_domid -> Xs ( . immediate c ( fun h -> getdomainpath h ( int_of_string server_domid ) server_domid ) server_domid ) server_domid >>= fun domainpath -> let xs_path = Printf . sprintf " % s / data / vchan /% d /% s " domainpath client_domid ( Port . to_string port ) port in let acl = Xs_protocol . ACL ( { . owner = int_of_string server_domid ; other = NONE ; acl = [ client_domid , READ ] } ) in let info = [ xs_path ^ " / ring - ref " , t . ring_ref ; xs_path ^ " / event - channel " , t . event_channel ; ] in Xs ( . transaction c ( fun h -> Lwt_list . iter_s ( fun ( k , v ) v -> write h k v >>= fun ( ) -> setperms h k acl ) info ) ) let read ~ server_domid ~ port = Xs . make ( ) >>= fun c -> Xs ( . immediate c ( fun h -> read h " domid ) ) " >>= fun client_domid -> Xs ( . immediate c ( fun h -> getdomainpath h server_domid ) server_domid ) server_domid >>= fun domainpath -> let xs_path = Printf . sprintf " % s / data / vchan /% s /% s " domainpath client_domid ( Port . to_string port ) port in Xs ( . wait c ( fun xsh -> Lwt . catch ( fun ( ) -> read xsh ( xs_path ^ " / ring - ref ) " >>= fun rref -> read xsh ( xs_path ^ " / event - channel ) " >>= fun evtchn -> return ( rref , evtchn ) evtchn ) ( fun _ -> fail Xs_protocol . Eagain ) Eagain ) Eagain ) Eagain >>= fun ( ring_ref , event_channel ) event_channel -> return { ring_ref ; event_channel } let delete ~ client_domid ~ port = Xs . make ( ) >>= fun c -> Xs ( . immediate c ( fun h -> read h " domid ) ) " >>= fun server_domid -> Xs ( . immediate c ( fun h -> getdomainpath h ( int_of_string server_domid ) server_domid ) server_domid ) server_domid >>= fun domainpath -> let xs_path = Printf . sprintf " % s / data / vchan /% d /% s " domainpath client_domid ( Port . to_string port ) port in Xs ( . transaction c ( fun h -> rm h xs_path >>= fun ( ) -> let dir = Filename . dirname xs_path in directory h dir >>= function | [ ] -> rm h dir | _ -> return ( ) ) ) end
type ( ' a , ' b ) result = | Ok of ' a | Error of ' b
module type IO = sig include Cohttp . S . IO val close : ( ic * oc ) -> unit t val open_connection : Uri . t -> ( ( ic * oc ) , exn ) result t val sleep : float -> unit t val gettimeofday : unit -> float end
module Make ( IO : IO ) = struct open IO type ic = IO . ic type oc = IO . oc module Request = Cohttp . Request . Make ( IO ) module Response = Cohttp . Response . Make ( IO ) type t = { uri : Uri . t ; mutable io : ( ic * oc ) option ; } let make uri = { uri = uri ; io = None ; } let disconnect ( t : t ) = match t . io with | Some io -> t . io <- None ; close io | None -> return ( ) let connect ( t : t ) : ( ( ic * oc ) , exn ) result IO . t = match t . io with | Some io -> return ( Ok io ) | None -> open_connection t . uri >>= function | Error e -> return ( Error e ) | Ok io -> t . io <- Some io ; return ( Ok io ) let counter = ref 0 let one_attempt t ( ic , oc ) request = let body = request in let headers = Cohttp . Header . of_list [ " user - agent " , user_agent ; " content - length " , string_of_int ( String . length body ) ; " connection " , " keep - alive " ; ] in let request = Cohttp . Request . make ~ meth ` : POST ~ version ` : HTTP_1_1 ~ headers t . uri in Request . write ( fun writer -> Request . write_body writer body ) request oc >>= fun ( ) -> Response . read ic >>= function | ` Eof -> Printf . fprintf stderr " failed to read response \ n " ; %! return ( Error No_response ) | ` Invalid error -> Printf . fprintf stderr " malformed response : % s \ n " %! error ; return ( Error No_response ) | ` Ok response -> let body = Buffer . create 16 in let reader = Response . make_body_reader response ic in let rec loop ( ) = Response . read_body_chunk reader >>= function | Cohttp . Transfer . Chunk x -> Buffer . add_string body x ; loop ( ) | Cohttp . Transfer . Final_chunk x -> Buffer . add_string body x ; return ( Buffer . contents body ) | Cohttp . Transfer . Done -> return ( Buffer . contents body ) in loop ( ) >>= fun body -> match Cohttp . Response . status response with | ` OK -> return ( Ok body ) | s -> return ( Error ( Http_error ( Cohttp . Code . code_of_status s , body ) ) ) let retry timeout delay_between_attempts is_finished f = let start = gettimeofday ( ) in let rec loop n = f ( ) >>= fun result -> let time_so_far = gettimeofday ( ) . - start in if time_so_far > timeout || is_finished result then return result else sleep ( delay_between_attempts time_so_far ( n + 1 ) ) >>= fun ( ) -> loop ( n + 1 ) in loop 0 let every ideal_interval time_so_far next_n = let ideal_time = float_of_int next_n . * ideal_interval in max 0 . ( ideal_time . - time_so_far ) let rpc ( ? timeout = 30 . ) t req = let is_finished = function | Ok _ -> true | Error ( Http_error ( _ , _ ) ) -> true | Error ( No_content_length ) -> true | Error ( No_response ) -> false | Error _ -> true in retry timeout ( every 1 . ) is_finished ( fun ( ) -> connect t >>= function | Error e -> disconnect t >>= fun ( ) -> return ( Error e ) | Ok io -> one_attempt t io req ) end
module IO = struct type ' a t = ' a Deferred . t let ( ) >>= = Deferred . ( ) >>= let return = Deferred . return type ic = ( unit -> unit Deferred . t ) * Reader . t type oc = ( unit -> unit Deferred . t ) * Writer . t type conn = unit let read_line ( _ , ic ) = Reader . read_line ic >>| function | ` Ok s -> Some s | ` Eof -> None let read ( _ , ic ) len = let buf = Bytes . create len in Reader . read ic ~ len buf >>| function | ` Ok len ' -> let content = Bytes . sub buf ~ pos : 0 ~ len : len ' in Bytes . to_string content | ` Eof -> " " let write ( _ , oc ) buf = Writer . write oc buf ; return ( ) let flush ( _ , oc ) = Async . Writer . flushed oc let close ( ( close1 , _ ) , ( close2 , _ ) ) = close1 ( ) >>= fun ( ) -> close2 ( ) let open_connection uri = match Uri . scheme uri with | Some " http " -> let port = match Uri . port uri with | None -> 80 | Some port -> port in begin match Uri . host uri with | Some host -> let endp = Host_and_port . create ~ host ~ port in Tcp . connect ( Tcp . Where_to_connect . of_host_and_port endp ) >>| fun ( _ , ic , oc ) -> Ok ( ( ( fun ( ) -> Reader . close ic ) , ic ) , ( ( fun ( ) -> Writer . close oc ) , oc ) ) | None -> return ( Error ( Failed_to_resolve_hostname " " ) ) end | Some x -> return ( Error ( Unsupported_scheme x ) ) | None -> return ( Error ( Unsupported_scheme " " ) ) let sleep s = after ( sec s ) let gettimeofday = Unix . gettimeofday end
let exn_to_string = function | Api_errors . Server_error ( code , params ) -> Printf . sprintf " % s % s " code ( String . concat ~ sep " : " params ) | e -> Printf . sprintf " Caught unexpected exception : % s " ( Exn . to_string e )
let do_it uri string = let uri = Uri . of_string uri in let connection = M . make uri in let ( ) >>= = Deferred . ( ) >>= in Monitor . protect ( fun ( ) -> M . rpc connection string >>= function | Ok x -> return x | Error e -> eprintf " Caught : % s \ n " %! ( exn_to_string e ) ; Exn . reraise e " connection error " ) ~ finally ( : fun ( ) -> M . disconnect connection )
let make ( ? timeout = 30 . ) uri call = let req = Xmlrpc . string_of_call call in do_it uri req >>| Xmlrpc . response_of_string
let make_json ( ? timeout = 30 . ) uri call = let req = Jsonrpc . string_of_call call in do_it uri req >>| Jsonrpc . response_of_string
module Client = Client . ClientF ( struct include Deferred let bind a f = bind a ~ f end )
module Lwt_unix_IO = struct type ' a t = ' a Lwt . t let ( ) >>= = Lwt . bind let return = Lwt . return let ( ) >> m n = m >>= fun _ -> n type ic = ( unit -> unit Lwt . t ) * Lwt_io . input_channel type oc = ( unit -> unit Lwt . t ) * Lwt_io . output_channel type conn = Lwt_unix . file_descr let read_line ( _ , ic ) = Lwt_io . read_line_opt ic let read ( _ , ic ) count = Lwt . catch ( fun ( ) -> Lwt_io . read ~ count ic ) ( function | End_of_file -> return " " | e -> Lwt . fail e ) let write ( _ , oc ) = Lwt_io . write oc let flush ( _ , oc ) = Lwt_io . flush oc let close ( ( close1 , _ ) , ( close2 , _ ) ) = close1 ( ) >> close2 ( ) let sslctx = Ssl . init ( ) ; Ssl . create_context Ssl . TLSv1_2 Ssl . Client_context let open_connection uri = ( match Uri . scheme uri with | Some " file " -> return ( Unix . PF_UNIX , Unix . ADDR_UNIX ( Uri . path uri ) , false ) | Some " http " | Some " https " -> Util . sockaddr_of_uri uri >|= fun ( sockaddr , ssl ) -> ( ( Unix . domain_of_sockaddr sockaddr ) , sockaddr , ssl ) | Some x -> fail ( Unsupported_scheme x ) | None -> fail ( Unsupported_scheme " " ) ) >>= fun ( domain , sockaddr , ssl ) -> if ssl then begin let fd = Lwt_unix . socket domain Unix . SOCK_STREAM 0 in Lwt . catch ( fun ( ) -> Lwt . catch ( fun ( ) -> Lwt_unix . connect fd sockaddr ) ( fun e -> Lwt_unix . close fd >>= fun ( ) -> Lwt . fail e ) >>= fun ( ) -> Lwt_ssl . ssl_connect fd sslctx >>= fun sock -> let ic = Lwt_ssl . in_channel_of_descr sock in let oc = Lwt_ssl . out_channel_of_descr sock in return ( Ok ( ( return , ic ) , ( ( fun ( ) -> Lwt_ssl . close sock ) , oc ) ) ) ) ( fun e -> return ( Error e ) ) end else begin let fd = Lwt_unix . socket domain Unix . SOCK_STREAM 0 in Lwt . catch ( fun ( ) -> Lwt . catch ( fun ( ) -> Lwt_unix . connect fd sockaddr ) ( fun e -> Lwt_unix . close fd >>= fun ( ) -> Lwt . fail e ) >>= fun ( ) -> let ic = Lwt_io . of_fd ~ close : return ~ mode : Lwt_io . input fd in let oc = Lwt_io . of_fd ~ close ( : fun ( ) -> Lwt_unix . close fd ) ~ mode : Lwt_io . output fd in return ( Ok ( ( ( fun ( ) -> Lwt_io . close ic ) , ic ) , ( ( fun ( ) -> Lwt_io . close oc ) , oc ) ) ) ) ( fun e -> return ( Error e ) ) end let sleep = Lwt_unix . sleep let gettimeofday = Unix . gettimeofday end
let exn_to_string = function | Api_errors . Server_error ( code , params ) -> Printf . sprintf " % s % s " code ( String . concat " " params ) | e -> Printexc . to_string e
let do_it uri string = let uri = Uri . of_string uri in let connection = M . make uri in Lwt . finalize ( fun ( ) -> M . rpc connection string >>= fun result -> match result with | Ok x -> return x | Error e -> Printf . fprintf stderr " Caught : % s \ n " %! ( exn_to_string e ) ; fail e ) ( fun ( ) -> M . disconnect connection )
let make ( ? timeout = 30 . ) uri call = let string = Xmlrpc . string_of_call call in do_it uri string >>= fun result -> Lwt . return ( Xmlrpc . response_of_string result )
let make_json ( ? timeout = 30 . ) uri call = let string = Jsonrpc . string_of_call call in do_it uri string >>= fun result -> Lwt . return ( Jsonrpc . response_of_string result )
type cf = [ ` Average | ` Min | ` Max ]
let string_of_cf = function | ` Average -> " AVERAGE " | ` Min -> " MIN " | ` Max -> " MAX "
let cf_of_string = function | " AVERAGE " -> ` Ok ` Average | " MIN " -> ` Ok ` Min | " MAX " -> ` Ok ` Max | x -> ` Error ( ` Msg ( Printf . sprintf " Unknown consolidation function : % s " x ) )
module Legend = struct type cls = [ ` VM | ` Host | ` Other of string ] type t = string * cf * cls * Uuidm . t let colon = Re . Str . regexp_string " " : let of_string x = match Re . Str . split_delim colon x with | cf :: cls :: uuid :: name :: [ ] -> begin match cf_of_string cf with | ` Error x -> ` Error x | ` Ok cf -> let cls = match cls with | " host " -> ` Host | " vm " -> ` VM | x -> ` Other x in begin match Uuidm . of_string uuid with | None -> ` Error ( ` Msg ( Printf . sprintf " Failed to parse uuid : % s " uuid ) ) | Some uuid -> ` Ok ( name , cf , cls , uuid ) end end | _ -> ` Error ( ` Msg ( Printf . sprintf " Failed to parse legend : % s " x ) ) let find_data_source dsl ( name , _ , _ , _ ) = try Some ( List . find ( fun ds -> ds . API . data_source_name_label = name ) dsl ) with Not_found -> None end
type interval = [ | ` Seconds | ` Minute | ` Hour | ` Day | ` Other of int ]
let seconds_of_interval = function | ` Seconds -> 5 | ` Minute -> 60 | ` Hour -> 60 * 60 | ` Day -> 24 * 60 * 60 | ` Other x -> x
let rec archive_length_of_interval = function | ` Seconds -> 10 * 60 | ` Minute -> 2 * 60 * 60 | ` Hour -> 7 * 24 * 60 * 60 | ` Day -> 365 * 7 * 24 * 60 * 60 | ` Other x -> if x <= ( seconds_of_interval ` Seconds ) then ( archive_length_of_interval ` Seconds ) else if x <= ( seconds_of_interval ` Minute ) then ( archive_length_of_interval ` Minute ) else if x <= ( seconds_of_interval ` Hour ) then ( archive_length_of_interval ` Hour ) else archive_length_of_interval ` Day
module Updates = struct let uri ~ host ~ authentication ~ start ( ? include_host = false ) ? interval ? cf ( ) = let ssl , scheme = match Uri . scheme host with | Some " https " -> true , " https " | Some " http " -> false , " http " | x -> failwith ( Printf . sprintf " Unknown scheme : % s " ( match x with None -> " None " | Some x -> x ) ) in let port = match Uri . port host with | Some x -> x | None -> if ssl then 443 else 80 in let query = [ " start " , [ string_of_int start ] ; " host " , [ string_of_bool include_host ] ] @ ( match interval with None -> [ ] | Some x -> [ " interval " , [ string_of_int ( seconds_of_interval x ) ] ] ) @ ( match cf with None -> [ ] | Some x -> [ " cf " , [ string_of_cf x ] ] ) in let userinfo = match authentication with | ` UserPassword ( user , pass ) -> Some ( user ^ " " : ^ pass ) | ` Session_id _ -> None in let query = match authentication with | ` UserPassword ( _ , _ ) -> query | ` Session_id s -> ( " session_id " , [ s ] ) :: query in Uri . make ~ scheme ? userinfo ? host ( : Uri . host host ) ~ port ~ path " :/ rrd_updates " ~ query ( ) let parse x = let input = Xmlm . make_input ( ` String ( 0 , x ) ) in Rrd_updates . of_xml input end
let ( |> ) a b = b a
let id x = x
module Fake_IO = struct type ' a t = T of ' a let return x = T x let ( ) >>= t f = match t with | T x -> f x let ( ) >> m n = m >>= fun _ -> n let rec iter f = function | [ ] -> return ( ) | x :: xs -> f x >>= fun ( ) -> ( iter f xs ) type ic = string Queue . t type oc = string Queue . t type conn = unit let read_line ic = if Queue . is_empty ic then begin return None end else begin let chunk = Queue . pop ic in return ( Some chunk ) end let read ic n = let chunk = Queue . pop ic in assert ( String . length chunk <= n ) ; return chunk let read_exactly ic buf off len = return ( if Queue . is_empty ic then false else begin let chunk = Queue . pop ic in String . blit chunk 0 buf off len ; true end ) let read_exactly ic len = let buf = Bytes . create len in read_exactly ic buf 0 len >>= function | true -> return ( Some buf ) | false -> return None let write oc string = Queue . push string oc ; return ( ) let flush _oc = return ( ) type connection = { address : Uri . t ; ic : ic ; oc : ic ; } let connections = ref [ ] let open_connection address = let ic = Queue . create ( ) and oc = Queue . create ( ) in let c = { address ; ic ; oc } in connections := c :: ! connections ; return ( Ok ( ic , oc ) ) let close ( ic , oc ) = let this_one c = c . ic == ic && c . oc == oc in ignore ( List . find this_one ! connections ) ; connections := List . filter ( fun c -> not ( this_one c ) ) ! connections ; return ( ) let timeofday = ref 0 . let gettimeofday ( ) = ! timeofday let num_sleeps = ref 0 let sleep x = incr num_sleeps ; timeofday := ! timeofday . + x ; return ( ) end
let test_login_fail _ = let module M = Xen_api . Make ( Fake_IO ) in let open Fake_IO in let rpc req = let xml = Xmlrpc . string_of_call req in M . rpc ( M . make ( Uri . of_string " http :// 127 . 0 . 0 . 1 " ) ) / xml >>= function | Ok _ -> failwith " should have failed with No_response " | Error e -> raise e in timeofday := 0 . ; num_sleeps := 0 ; begin try let _session_id = C . Session . login_with_password ~ rpc : rpc ~ uname " : root " ~ pwd " : password " ~ version " : 1 . 0 " ~ originator " : xen - api test " in ( ) with Xen_api . No_response -> ( ) end ; assert_equal ~ printer : string_of_float ~ msg " : timeofday " 31 . ! timeofday ; assert_equal ~ printer : string_of_int ~ msg " : num_sleeps " 31 ! num_sleeps ; ( )
let test_login_success _ = let session_id = " OpaqueRef : 9e9cf047 - 76d7 - 9f3a - 62ca - cb7bacf5a4e1 " in let result = Printf . sprintf " < methodResponse >< params >< param >< value >< struct >< member >< name > Status </ name >< value > Success </ value ></ member >< member >< name > Value </ name >< value >% s </ value ></ member ></ struct ></ value ></ param ></ params ></ methodResponse " > session_id in let module Fake_IO = struct include Fake_IO let open_connection address = let ic = Queue . create ( ) and oc = Queue . create ( ) in Queue . push " HTTP / 1 . 1 200 OK \ r \ n " ic ; Queue . push ( Printf . sprintf " Content - length : % d \ r \ n " ( String . length result ) ) ic ; Queue . push " \ r \ n " ic ; Queue . push result ic ; let c = { address ; ic ; oc } in connections := c :: ! connections ; return ( Ok ( ic , oc ) ) end in let open Fake_IO in let module M = Xen_api . Make ( Fake_IO ) in let rpc call = let s = Xmlrpc . string_of_call call in M . rpc ( M . make ( Uri . of_string " http :// 127 . 0 . 0 . 1 " ) ) / s >>= function | Ok x -> Xmlrpc . response_of_string x | Error e -> raise e in let session_id ' = C . Session . login_with_password ~ rpc ~ uname " : root " ~ pwd " : password " ~ version " : 1 . 0 " ~ originator " : xen - api test " in assert_equal ~ msg " : session_id " session_id ( API . Ref . string_of session_id ' )
let _ = let verbose = ref false in Arg . parse [ " - verbose " , Arg . Unit ( fun _ -> verbose := true ) , " Run in verbose mode " ; ] ( fun x -> Printf . fprintf stderr " Ignoring argument : % s " x ) " Test xen - api protocol code " ; let suite = " xen - api " >::: [ " login_fail " >:: test_login_fail ; " login_success " >:: test_login_success ; ] in run_test_tt ~ verbose :! verbose suite
type xexp = | Num of int | Var of string | Fn of string * xexp | App of xexp * xexp | If of xexp * xexp * xexp | Equal of xexp * xexp | Raise of xexp | Handle of xexp * int * xexp
type value = | N of int | B of bool | C of closure
type result = | Val of value | Exn of int
let emptyEnv = ( fun x -> raise ( RunError ( " unbound id : " ^ x ) ) )
let bind e x v = ( fun y -> if y = x then v else e y )
let getInt = function | N n -> n | _ -> raise ( TypeError " not an int " )
let getBool = function | B b -> b | _ -> raise ( TypeError " not a bool " )
let getClosure = function | C c -> c | _ -> raise ( TypeError " not a function " )
let rec eval env exp = match exp with | Num n -> Val ( N n ) | Var x -> Val ( env x ) | Fn ( x , e ) -> Val ( C ( x , e , env ) ) | App ( e1 , e2 ) -> ( match eval env e1 with | Val v1 -> let ( x , e_body , env ' ) = getClosure v1 in ( match eval env e2 with | Val v2 -> eval ( bind env ' x v2 ) e_body | Exn n -> Exn n ) | Exn n -> Exn n ) | If ( e1 , e2 , e3 ) -> ( match eval env e1 with | Val v -> if getBool v then eval env e2 else eval env e3 | Exn n -> Exn n ) | Equal ( e1 , e2 ) -> ( match eval env e1 with | Val v1 -> ( match eval env e2 with | Val v2 -> Val ( B ( getInt v1 = getInt v2 ) ) | Exn n -> Exn n ) | Exn n -> Exn n ) | Raise e -> ( match eval env e with | Val v -> Exn ( getInt v ) | Exn n -> Exn n ) | Handle ( e1 , n , e2 ) -> ( match eval env e1 with | Val v1 -> Val v1 | Exn n ' -> if n = n ' then eval env e2 else Exn n ' )
let run : xexp -> result = fun exp -> eval emptyEnv exp
let indent i = let rec iter = function | 0 -> ( ) | n -> ps " " ; iter ( n - 1 ) in nl ( ) ; iter i
let rec pp i exp = match exp with | Num n -> print_int n | Var s -> ps s | Fn ( x , e ) -> ps ( " fn " ^ x ^ " => " ) ; pp i e | App ( e , e ' ) -> ps " ( " ; pp i e ; ps " ) ( " ; pp i e ' ; ps " ) " | If ( e1 , e2 , e3 ) -> indent ( i + 1 ) ; ps " if " ; pp i e1 ; ps " then " ; indent ( i + 2 ) ; pp ( i + 2 ) e2 ; indent ( i + 1 ) ; ps " else " ; indent ( i + 2 ) ; pp ( i + 2 ) e3 ; nl ( ) | Equal ( e1 , e2 ) -> ps " ( " ; pp i e1 ; ps " = " ; pp i e2 ; ps " ) " | Raise e -> ps " raise ( " ; pp i e ; ps " ) " | Handle ( e1 , n , e2 ) -> ps " ( " ; pp i e1 ; ps " ) " ; ps ( " handle " ^ string_of_int n ^ " ( " ) ; pp i e2 ; ps " ) "
let print = pp 0
let rec is_sugarless = function | Num _ | Var _ -> true | Fn ( _ , e ) -> is_sugarless e | App ( e1 , e2 ) | Equal ( e1 , e2 ) -> is_sugarless e1 && is_sugarless e2 | If ( e1 , e2 , e3 ) -> is_sugarless e1 && is_sugarless e2 && is_sugarless e3 | Raise _ | Handle _ -> false
type t = { po_content : po_content ; translated : SetString . t }
let translations = ref { po_content = empty_po ; translated = SetString . empty }
let default_textdomain = ref None
let current_file = ref " "
let add_translation loc singular plural_opt domain = let t = ! translations in let filepos = let start = loc . Location . loc_start in let fname = match start . Lexing . pos_fname with " " -> ! current_file | fname -> fname in ( fname , start . Lexing . pos_lnum ) in let translated = SetString . add singular t . translated in let translated , translation = match plural_opt with | Some plural -> ( SetString . add plural translated , { po_comment_special = [ ] ; po_comment_filepos = [ filepos ] ; po_comment_translation = PoPlural ( [ singular ] , [ plural ] , [ [ " " ] ; [ " " ] ] ) ; } ) | None -> ( translated , { po_comment_special = [ ] ; po_comment_filepos = [ filepos ] ; po_comment_translation = PoSingular ( [ singular ] , [ " " ] ) ; } ) in let po_content = match ( domain , ! default_textdomain ) with | Some domain , _ -> add_po_translation_domain domain t . po_content translation | None , Some domain -> add_po_translation_domain domain t . po_content translation | None , None -> add_po_translation_no_domain t . po_content translation in translations := { po_content ; translated }
let output_translations ? output_file t = let fd = match output_file with Some f -> open_out f | None -> stdout in set_binary_mode_out fd true ; Marshal . to_channel fd t . po_content [ ]
let rec is_like lid = function | [ ] -> false | func :: functions -> ( match lid with | ( Lident f | Ldot ( _ , f ) ) when f = func -> true | _ -> is_like lid functions )
let visit_expr ( iterator : Ast_iterator . iterator ) expr = let loc = expr . pexp_loc in match expr . pexp_desc with | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " s_ " ; " f_ " ] -> add_translation loc singular None None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " sn_ " ; " fn_ " ] -> add_translation loc singular ( Some plural ) None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " gettext " ; " fgettext " ] -> add_translation loc singular None None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } # endif ) :: _ ) when is_like lid [ " dgettext " ; " fdgettext " ; " dcgettext " ; " fdcgettext " ] -> add_translation loc singular None ( Some domain ) | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " ngettext " ; " fngettext " ] -> add_translation loc singular ( Some plural ) None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } # endif ) :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } # endif ) :: _ ) when is_like lid [ " dngettext " ; " fdngettext " ; " dcngettext " ; " fdcngettext " ] -> add_translation loc singular ( Some plural ) ( Some domain ) | _ -> Ast_iterator . default_iterator . expr iterator expr
let ast_iterator = { Ast_iterator . default_iterator with expr = visit_expr }
let go fn = current_file := fn ; try let lexbuf = Lexing . from_channel ( open_in fn ) in let structure = Parse . implementation lexbuf in ast_iterator . Ast_iterator . structure ast_iterator structure with exn -> failwith ( fn ^ " : " ^ Printexc . to_string exn )
let ( ) = Arg . parse [ ] go " " ; output_translations ! translations
let hash x = seeded_hash_param 10 100 0 x
let hash_param n1 n2 x = seeded_hash_param n1 n2 0 x
let seeded_hash seed x = seeded_hash_param 10 100 seed x
type ' a t = { mutable size : int ; mutable data : ' a list array ; mutable seed : int ; initial_size : int ; }
let randomized_default = let params = try Sys . getenv " OCAMLRUNPARAM " with Not_found -> try Sys . getenv " CAMLRUNPARAM " with Not_found -> " " in String . contains params ' R '
let randomized = ref randomized_default
let randomize ( ) = randomized := true
let prng = lazy ( Random . State . make_self_init ( ) )
let rec power_2_above x n = if x >= n then x else if x * 2 > Sys . max_array_length then x else power_2_above ( x * 2 ) n
let create ( ? random = ! randomized ) initial_size = let s = power_2_above 16 initial_size in let seed = if random then Random . State . bits ( Lazy . force prng ) else 0 in { initial_size = s ; size = 0 ; seed = seed ; data = Array . make s [ ] }
let clear h = h . size <- 0 ; let len = Array . length h . data in for i = 0 to len - 1 do h . data . ( i ) <- [ ] done
let reset h = let len = Array . length h . data in if Obj . size ( Obj . repr h ) < 4 || len = h . initial_size then clear h else begin h . size <- 0 ; h . data <- Array . make h . initial_size [ ] end
let copy h = { h with data = Array . copy h . data }