text
stringlengths
0
601k
let check_name_of_type t = ignore ( name_of_type t )
let remove_names tyl = let tyl = List . map repr tyl in names := List . filter ( fun ( ty , _ ) -> not ( List . memq ty tyl ) ) ! names
let visited_objects = ref ( [ ] : type_expr list )
let aliased = ref ( [ ] : type_expr list )
let delayed = ref ( [ ] : type_expr list )
let add_delayed t = if not ( List . memq t ! delayed ) then delayed := t :: ! delayed
let is_aliased ty = List . memq ( proxy ty ) ! aliased
let add_alias ty = let px = proxy ty in if not ( is_aliased px ) then begin aliased := px :: ! aliased ; add_named_var px end
let aliasable ty = match ty . desc with Tvar _ | Tunivar _ | Tpoly _ -> false | Tconstr ( p , _ , _ ) -> not ( is_nth ( snd ( best_type_path p ) ) ) | _ -> true
let namable_row row = row . row_name <> None && List . for_all ( fun ( _ , f ) -> match row_field_repr f with | Reither ( c , l , _ , _ ) -> row . row_closed && if c then l = [ ] else List . length l = 1 | _ -> true ) row . row_fields
let rec mark_loops_rec visited ty = let ty = repr ty in let px = proxy ty in if List . memq px visited && aliasable ty then add_alias px else let visited = px :: visited in match ty . desc with | Tvar _ -> add_named_var ty | Tarrow ( _ , ty1 , ty2 , _ ) -> mark_loops_rec visited ty1 ; mark_loops_rec visited ty2 | Ttuple tyl -> List . iter ( mark_loops_rec visited ) tyl | Tconstr ( p , tyl , _ ) -> let ( _p ' , s ) = best_type_path p in List . iter ( mark_loops_rec visited ) ( apply_subst s tyl ) | Tpackage ( _ , _ , tyl ) -> List . iter ( mark_loops_rec visited ) tyl | Tvariant row -> if List . memq px ! visited_objects then add_alias px else begin let row = row_repr row in if not ( static_row row ) then visited_objects := px :: ! visited_objects ; match row . row_name with | Some ( _p , tyl ) when namable_row row -> List . iter ( mark_loops_rec visited ) tyl | _ -> iter_row ( mark_loops_rec visited ) row end | Tobject ( fi , nm ) -> if List . memq px ! visited_objects then add_alias px else begin if opened_object ty then visited_objects := px :: ! visited_objects ; begin match ! nm with | None -> let fields , _ = flatten_fields fi in List . iter ( fun ( _ , kind , ty ) -> if field_kind_repr kind = Fpresent then mark_loops_rec visited ty ) fields | Some ( _ , l ) -> List . iter ( mark_loops_rec visited ) ( List . tl l ) end end | Tfield ( _ , kind , ty1 , ty2 ) when field_kind_repr kind = Fpresent -> mark_loops_rec visited ty1 ; mark_loops_rec visited ty2 | Tfield ( _ , _ , _ , ty2 ) -> mark_loops_rec visited ty2 | Tnil -> ( ) | Tsubst ty -> mark_loops_rec visited ty | Tlink _ -> fatal_error " Printtyp . mark_loops_rec ( 2 ) " | Tpoly ( ty , tyl ) -> List . iter ( fun t -> add_alias t ) tyl ; mark_loops_rec visited ty | Tunivar _ -> add_named_var ty
let mark_loops ty = normalize_type Env . empty ty ; mark_loops_rec [ ] ty ; ;
let reset_loop_marks ( ) = visited_objects := [ ] ; aliased := [ ] ; delayed := [ ]
let reset ( ) = unique_names := Ident . empty ; reset_names ( ) ; reset_loop_marks ( )
let reset_and_mark_loops ty = reset ( ) ; mark_loops ty
let reset_and_mark_loops_list tyl = reset ( ) ; List . iter mark_loops tyl
let print_labels = ref true
let rec tree_of_typexp sch ty = let ty = repr ty in let px = proxy ty in if List . mem_assq px ! names && not ( List . memq px ! delayed ) then let mark = is_non_gen sch ty in Otyp_var ( mark , name_of_type px ) else let pr_typ ( ) = match ty . desc with | Tvar _ -> Otyp_var ( is_non_gen sch ty , name_of_type ty ) | Tarrow ( l , ty1 , ty2 , _ ) -> let pr_arrow l ty1 ty2 = let lab = if ! print_labels || is_optional l then string_of_label l else " " in let t1 = if is_optional l then match ( repr ty1 ) . desc with | Tconstr ( path , [ ty ] , _ ) when Path . same path Predef . path_option -> tree_of_typexp sch ty | _ -> Otyp_stuff " < hidden " > else tree_of_typexp sch ty1 in Otyp_arrow ( lab , t1 , tree_of_typexp sch ty2 ) in pr_arrow l ty1 ty2 | Ttuple tyl -> Otyp_tuple ( tree_of_typlist sch tyl ) | Tconstr ( p , tyl , _abbrev ) -> let p ' , s = best_type_path p in let tyl ' = apply_subst s tyl in if is_nth s then tree_of_typexp sch ( List . hd tyl ' ) else Otyp_constr ( tree_of_path p ' , tree_of_typlist sch tyl ' ) | Tvariant row -> let row = row_repr row in let fields = if row . row_closed then List . filter ( fun ( _ , f ) -> row_field_repr f <> Rabsent ) row . row_fields else row . row_fields in let present = List . filter ( fun ( _ , f ) -> match row_field_repr f with | Rpresent _ -> true | _ -> false ) fields in let all_present = List . length present = List . length fields in begin match row . row_name with | Some ( p , tyl ) when namable_row row -> let ( p ' , s ) = best_type_path p in let id = tree_of_path p ' in let args = tree_of_typlist sch ( apply_subst s tyl ) in if row . row_closed && all_present then if is_nth s then List . hd args else Otyp_constr ( id , args ) else let non_gen = is_non_gen sch px in let tags = if all_present then None else Some ( List . map fst present ) in let inh = match args with [ Otyp_constr ( i , a ) ] when is_nth s -> Ovar_name ( i , a ) | _ -> Ovar_name ( tree_of_path p , tree_of_typlist sch tyl ) in Otyp_variant ( non_gen , inh , row . row_closed , tags ) | _ -> let non_gen = not ( row . row_closed && all_present ) && is_non_gen sch px in let fields = List . map ( tree_of_row_field sch ) fields in let tags = if all_present then None else Some ( List . map fst present ) in Otyp_variant ( non_gen , Ovar_fields fields , row . row_closed , tags ) end | Tobject ( fi , nm ) -> tree_of_typobject sch fi ! nm | Tnil | Tfield _ -> tree_of_typobject sch ty None | Tsubst ty -> tree_of_typexp sch ty | Tlink _ -> fatal_error " Printtyp . tree_of_typexp " | Tpoly ( ty , [ ] ) -> tree_of_typexp sch ty | Tpoly ( ty , tyl ) -> let tyl = List . map repr tyl in if tyl = [ ] then tree_of_typexp sch ty else begin let old_delayed = ! delayed in List . iter add_delayed tyl ; let tl = List . map name_of_type tyl in let tr = Otyp_poly ( tl , tree_of_typexp sch ty ) in remove_names tyl ; delayed := old_delayed ; tr end | Tunivar _ -> Otyp_var ( false , name_of_type ty ) | Tpackage ( p , n , tyl ) -> let n = List . map ( fun li -> String . concat " . " ( Longident . flatten li ) ) n in Otyp_module ( Path . name p , n , tree_of_typlist sch tyl ) in if List . memq px ! delayed then delayed := List . filter ( ( ) != px ) ! delayed ; if is_aliased px && aliasable ty then begin check_name_of_type px ; Otyp_alias ( pr_typ ( ) , name_of_type px ) end else pr_typ ( ) match row_field_repr f with | Rpresent None | Reither ( true , [ ] , _ , _ ) -> ( l , false , [ ] ) | Rpresent ( Some ty ) -> ( l , false , [ tree_of_typexp sch ty ] ) | Reither ( c , tyl , _ , _ ) -> if c then ( l , true , tree_of_typlist sch tyl ) else ( l , false , tree_of_typlist sch tyl ) | Rabsent -> ( l , false , [ ] ) List . map ( tree_of_typexp sch ) tyl begin match nm with | None -> let pr_fields fi = let ( fields , rest ) = flatten_fields fi in let present_fields = List . fold_right ( fun ( n , k , t ) l -> match field_kind_repr k with | Fpresent -> ( n , t ) :: l | _ -> l ) fields [ ] in let sorted_fields = List . sort ( fun ( n , _ ) ( n ' , _ ) -> String . compare n n ' ) present_fields in tree_of_typfields sch rest sorted_fields in let ( fields , rest ) = pr_fields fi in Otyp_object ( fields , rest ) | Some ( p , ty :: tyl ) -> let non_gen = is_non_gen sch ( repr ty ) in let args = tree_of_typlist sch tyl in let ( p ' , s ) = best_type_path p in assert ( s = Id ) ; Otyp_class ( non_gen , tree_of_path p ' , args ) | _ -> fatal_error " Printtyp . tree_of_typobject " end sch && is_Tvar ty && ty . level <> generic_level | [ ] -> let rest = match rest . desc with | Tvar _ | Tunivar _ -> Some ( is_non_gen sch rest ) | Tconstr _ -> Some false | Tnil -> None | _ -> fatal_error " typfields ( 1 ) " in ( [ ] , rest ) | ( s , t ) :: l -> let field = ( s , tree_of_typexp sch t ) in let ( fields , rest ) = tree_of_typfields sch rest l in ( field :: fields , rest )
let typexp sch ppf ty = ! Xoprint . out_type ppf ( tree_of_typexp sch ty )
let type_expr ppf ty = typexp false ppf ty
let type_scheme_max ( ? b_reset_names = true ) ppf ty = if b_reset_names then reset_names ( ) ; typexp true ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty ; tree_of_typexp true ty
let tree_of_constraints params = List . fold_right ( fun ty list -> let ty ' = unalias ty in if proxy ty != proxy ty ' then let tr = tree_of_typexp true ty in ( tr , tree_of_typexp true ty ' ) :: list else list ) params [ ]
let filter_params tyl = let params = List . fold_left ( fun tyl ty -> let ty = repr ty in if List . memq ty tyl then Btype . newgenty ( Tsubst ty ) :: tyl else ty :: tyl ) [ ] tyl in List . rev params
let mark_loops_constructor_arguments = function | Cstr_tuple l -> List . iter mark_loops l | Cstr_record l -> List . iter ( fun l -> mark_loops l . ld_type ) l
let rec tree_of_type_decl id decl = reset ( ) ; let params = filter_params decl . type_params in begin match decl . type_manifest with | Some ty -> let vars = free_variables ty in List . iter ( function { desc = Tvar ( Some " _ " ) } as ty -> if List . memq ty vars then ty . desc <- Tvar None | _ -> ( ) ) params | None -> ( ) end ; List . iter add_alias params ; List . iter mark_loops params ; List . iter check_name_of_type ( List . map proxy params ) ; let ty_manifest = match decl . type_manifest with | None -> None | Some ty -> let ty = match repr ty with { desc = Tvariant row } -> let row = row_repr row in begin match row . row_name with Some ( Pident id ' , _ ) when Ident . same id id ' -> newgenty ( Tvariant { row with row_name = None } ) | _ -> ty end | _ -> ty in mark_loops ty ; Some ty in begin match decl . type_kind with | Type_abstract -> ( ) | Type_variant cstrs -> List . iter ( fun c -> mark_loops_constructor_arguments c . cd_args ; may mark_loops c . cd_res ) cstrs | Type_record ( l , _rep ) -> List . iter ( fun l -> mark_loops l . ld_type ) l | Type_open -> ( ) end ; let type_param = function | Otyp_var ( _ , id ) -> id | _ -> " " ? in let type_defined decl = let abstr = match decl . type_kind with Type_abstract -> decl . type_manifest = None || decl . type_private = Private | Type_record _ -> decl . type_private = Private | Type_variant tll -> decl . type_private = Private || List . exists ( fun cd -> cd . cd_res <> None ) tll | Type_open -> decl . type_manifest = None in let vari = List . map2 ( fun ty v -> if abstr || not ( is_Tvar ( repr ty ) ) then Variance . get_upper v else ( true , true ) ) decl . type_params decl . type_variance in ( Ident . name id , List . map2 ( fun ty cocn -> type_param ( tree_of_typexp false ty ) , cocn ) params vari ) in let tree_of_manifest ty1 = match ty_manifest with | None -> ty1 | Some ty -> Otyp_manifest ( tree_of_typexp false ty , ty1 ) in let ( name , args ) = type_defined decl in let constraints = tree_of_constraints params in let ty , priv = match decl . type_kind with | Type_abstract -> begin match ty_manifest with | None -> ( Otyp_abstract , Public ) | Some ty -> tree_of_typexp false ty , decl . type_private end | Type_variant cstrs -> tree_of_manifest ( Otyp_sum ( List . map tree_of_constructor cstrs ) ) , decl . type_private | Type_record ( lbls , _rep ) -> tree_of_manifest ( Otyp_record ( List . map tree_of_label lbls ) ) , decl . type_private | Type_open -> tree_of_manifest Otyp_open , Public in let immediate = Builtin_attributes . immediate decl . type_attributes in { otype_name = name ; otype_params = args ; otype_type = ty ; otype_private = priv ; otype_immediate = immediate ; otype_unboxed = decl . type_unboxed . unboxed ; otype_cstrs = constraints } | Cstr_tuple l -> tree_of_typlist false l | Cstr_record l -> [ Otyp_record ( List . map tree_of_label l ) ] let name = Ident . name cd . cd_id in let arg ( ) = tree_of_constructor_arguments cd . cd_args in match cd . cd_res with | None -> ( name , arg ( ) , None ) | Some res -> let nm = ! names in names := [ ] ; let ret = tree_of_typexp false res in let args = arg ( ) in names := nm ; ( name , args , Some ret ) ( Ident . name l . ld_id , l . ld_mutable = Mutable , tree_of_typexp false l . ld_type )
let tree_of_type_declaration id decl rs = Osig_type ( tree_of_type_decl id decl , tree_of_rec rs )
let tree_of_extension_constructor id ext es = reset ( ) ; let ty_name = Path . name ext . ext_type_path in let ty_params = filter_params ext . ext_type_params in List . iter add_alias ty_params ; List . iter mark_loops ty_params ; List . iter check_name_of_type ( List . map proxy ty_params ) ; mark_loops_constructor_arguments ext . ext_args ; may mark_loops ext . ext_ret_type ; let type_param = function | Otyp_var ( _ , id ) -> id | _ -> " " ? in let ty_params = List . map ( fun ty -> type_param ( tree_of_typexp false ty ) ) ty_params in let name = Ident . name id in let args , ret = match ext . ext_ret_type with | None -> ( tree_of_constructor_arguments ext . ext_args , None ) | Some res -> let nm = ! names in names := [ ] ; let ret = tree_of_typexp false res in let args = tree_of_constructor_arguments ext . ext_args in names := nm ; ( args , Some ret ) in let ext = { oext_name = name ; oext_type_name = ty_name ; oext_type_params = ty_params ; oext_args = args ; oext_ret_type = ret ; oext_private = ext . ext_private } in let es = match es with Text_first -> Oext_first | Text_next -> Oext_next | Text_exception -> Oext_exception in Osig_typext ( ext , es )
let tree_of_value_description id decl = let id = Ident . name id in let ty = tree_of_type_scheme decl . val_type in let vd = { oval_name = id ; oval_type = ty ; oval_prims = [ ] ; oval_attributes = [ ] } in let vd = match decl . val_kind with | Val_prim p -> Primitive . print p vd | _ -> vd in Osig_value vd
let method_type ( _ , kind , ty ) = match field_kind_repr kind , repr ty with Fpresent , { desc = Tpoly ( ty , tyl ) } -> ( ty , tyl ) | _ , ty -> ( ty , [ ] )
let tree_of_metho sch concrete csil ( lab , kind , ty ) = if lab <> dummy_method then begin let kind = field_kind_repr kind in let priv = kind <> Fpresent in let virt = not ( Concr . mem lab concrete ) in let ( ty , tyl ) = method_type ( lab , kind , ty ) in let tty = tree_of_typexp sch ty in remove_names tyl ; Ocsg_method ( lab , priv , virt , tty ) :: csil end else csil
let rec prepare_class_type params = function | Cty_constr ( _p , tyl , cty ) -> let sty = Ctype . self_type cty in if List . memq ( proxy sty ) ! visited_objects || not ( List . for_all is_Tvar params ) || List . exists ( deep_occur sty ) tyl then prepare_class_type params cty else List . iter mark_loops tyl | Cty_signature sign -> let sty = repr sign . csig_self in let px = proxy sty in if List . memq px ! visited_objects then add_alias sty else visited_objects := px :: ! visited_objects ; let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . csig_self ) in List . iter ( fun met -> mark_loops ( fst ( method_type met ) ) ) fields ; Vars . iter ( fun _ ( _ , _ , ty ) -> mark_loops ty ) sign . csig_vars | Cty_arrow ( _ , ty , cty ) -> mark_loops ty ; prepare_class_type params cty
let rec tree_of_class_type sch params = function | Cty_constr ( p ' , tyl , cty ) -> let sty = Ctype . self_type cty in if List . memq ( proxy sty ) ! visited_objects || not ( List . for_all is_Tvar params ) then tree_of_class_type sch params cty else Octy_constr ( tree_of_path p ' , tree_of_typlist true tyl ) | Cty_signature sign -> let sty = repr sign . csig_self in let self_ty = if is_aliased sty then Some ( Otyp_var ( false , name_of_type ( proxy sty ) ) ) else None in let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . csig_self ) in let csil = [ ] in let csil = List . fold_left ( fun csil ( ty1 , ty2 ) -> Ocsg_constraint ( ty1 , ty2 ) :: csil ) csil ( tree_of_constraints params ) in let all_vars = Vars . fold ( fun l ( m , v , t ) all -> ( l , m , v , t ) :: all ) sign . csig_vars [ ] in let all_vars = List . rev all_vars in let csil = List . fold_left ( fun csil ( l , m , v , t ) -> Ocsg_value ( l , m = Mutable , v = Virtual , tree_of_typexp sch t ) :: csil ) csil all_vars in let csil = List . fold_left ( tree_of_metho sch sign . csig_concr ) csil fields in Octy_signature ( self_ty , List . rev csil ) | Cty_arrow ( l , ty , cty ) -> let lab = if ! print_labels || is_optional l then string_of_label l else " " in let ty = if is_optional l then match ( repr ty ) . desc with | Tconstr ( path , [ ty ] , _ ) when Path . same path Predef . path_option -> ty | _ -> newconstr ( Path . Pident ( Ident . create " < hidden " ) ) > [ ] else ty in let tr = tree_of_typexp sch ty in Octy_arrow ( lab , tr , tree_of_class_type sch params cty )
let tree_of_class_param param variance = ( match tree_of_typexp true param with Otyp_var ( _ , s ) -> s | _ -> " " ) , ? if is_Tvar ( repr param ) then ( true , true ) else variance
let class_variance = List . map Variance . ( fun v -> mem May_pos v , mem May_neg v )
let tree_of_class_declaration id cl rs = let params = filter_params cl . cty_params in reset ( ) ; List . iter add_alias params ; prepare_class_type params cl . cty_type ; let sty = Ctype . self_type cl . cty_type in List . iter mark_loops params ; List . iter check_name_of_type ( List . map proxy params ) ; if is_aliased sty then check_name_of_type ( proxy sty ) ; let vir_flag = cl . cty_new = None in Osig_class ( vir_flag , Ident . name id , List . map2 tree_of_class_param params ( class_variance cl . cty_variance ) , tree_of_class_type true params cl . cty_type , tree_of_rec rs )
let tree_of_cltype_declaration id cl rs = let params = List . map repr cl . clty_params in reset ( ) ; List . iter add_alias params ; prepare_class_type params cl . clty_type ; let sty = Ctype . self_type cl . clty_type in List . iter mark_loops params ; List . iter check_name_of_type ( List . map proxy params ) ; if is_aliased sty then check_name_of_type ( proxy sty ) ; let sign = Ctype . signature_of_class_type cl . clty_type in let virt = let ( fields , _ ) = Ctype . flatten_fields ( Ctype . object_fields sign . csig_self ) in List . exists ( fun ( lab , _ , _ ) -> not ( lab = dummy_method || Concr . mem lab sign . csig_concr ) ) fields || Vars . fold ( fun _ ( _ , vr , _ ) b -> vr = Virtual || b ) sign . csig_vars false in Osig_class_type ( virt , Ident . name id , List . map2 tree_of_class_param params ( class_variance cl . clty_variance ) , tree_of_class_type true params cl . clty_type , tree_of_rec rs )
let wrap_env fenv ftree arg = let env = ! printing_env in set_printing_env ( fenv env ) ; let tree = ftree arg in set_printing_env env ; tree
let filter_rem_sig item rem = match item , rem with | Sig_class _ , ctydecl :: tydecl1 :: tydecl2 :: rem -> ( [ ctydecl ; tydecl1 ; tydecl2 ] , rem ) | Sig_class_type _ , tydecl1 :: tydecl2 :: rem -> ( [ tydecl1 ; tydecl2 ] , rem ) | _ -> ( [ ] , rem )
let dummy = { type_params = [ ] ; type_arity = 0 ; type_kind = Type_abstract ; type_private = Public ; type_manifest = None ; type_variance = [ ] ; type_newtype_level = None ; type_loc = Location . none ; type_attributes = [ ] ; type_immediate = false ; type_unboxed = unboxed_false_default_false ; }
let hide_rec_items = function | Sig_type ( id , _decl , rs ) :: rem when rs = Trec_first && not ! Clflags . real_paths -> let rec get_ids = function Sig_type ( id , _ , Trec_next ) :: rem -> id :: get_ids rem | _ -> [ ] in let ids = id :: get_ids rem in set_printing_env ( List . fold_right ( fun id -> Env . add_type ~ check : false ( Ident . rename id ) dummy ) ids ! printing_env ) | _ -> ( )
let rec tree_of_modtype ( ? ellipsis = false ) = function | Mty_ident p -> Omty_ident ( tree_of_path p ) | Mty_signature sg -> Omty_signature ( if ellipsis then [ Osig_ellipsis ] else tree_of_signature sg ) | Mty_functor ( param , ty_arg , ty_res ) -> let res = match ty_arg with None -> tree_of_modtype ~ ellipsis ty_res | Some mty -> wrap_env ( Env . add_module ~ arg : true param mty ) ( tree_of_modtype ~ ellipsis ) ty_res in Omty_functor ( Ident . name param , may_map ( tree_of_modtype ~ ellipsis : false ) ty_arg , res ) | Mty_alias ( _ , p ) -> Omty_alias ( tree_of_path p ) wrap_env ( fun env -> env ) ( tree_of_signature_rec ! printing_env false ) sg [ ] -> [ ] | item :: rem as items -> let in_type_group = match in_type_group , item with true , Sig_type ( _ , _ , Trec_next ) -> true | _ , Sig_type ( _ , _ , ( Trec_not | Trec_first ) ) -> set_printing_env env ' ; true | _ -> set_printing_env env ' ; false in let ( sg , rem ) = filter_rem_sig item rem in hide_rec_items items ; let trees = trees_of_sigitem item in let env ' = Env . add_signature ( item :: sg ) env ' in trees @ tree_of_signature_rec env ' in_type_group rem | Sig_value ( id , decl ) -> [ tree_of_value_description id decl ] | Sig_type ( id , _ , _ ) when is_row_name ( Ident . name id ) -> [ ] | Sig_type ( id , decl , rs ) -> [ tree_of_type_declaration id decl rs ] | Sig_typext ( id , ext , es ) -> [ tree_of_extension_constructor id ext es ] | Sig_module ( id , md , rs ) -> let ellipsis = List . exists ( function ( { txt " . . . " } , = Parsetree . PStr [ ] ) -> true | _ -> false ) md . md_attributes in [ tree_of_module id md . md_type rs ~ ellipsis ] | Sig_modtype ( id , decl ) -> [ tree_of_modtype_declaration id decl ] | Sig_class ( id , decl , rs ) -> [ tree_of_class_declaration id decl rs ] | Sig_class_type ( id , decl , rs ) -> [ tree_of_cltype_declaration id decl rs ] let mty = match decl . mtd_type with | None -> Omty_abstract | Some mty -> tree_of_modtype mty in Osig_modtype ( Ident . name id , mty ) Osig_module ( Ident . name id , tree_of_modtype ? ellipsis mty , tree_of_rec rs ) end
module Exn = struct let protect f v ~ final = Spotlib . Exn . protect f v ~ finally : final end
module Array = struct let shuffle ( ? random = Random . int ) a = let len = Array . length a - 1 in for i = 0 to len - 1 do let d = len - i in let j = random d + i in let x = Array . unsafe_get a i in let y = Array . unsafe_get a j in Array . unsafe_set a i y ; Array . unsafe_set a j x ; done end
module Base = struct let ( !++ ) r = let v = ! r in incr r ; v end
module Gc = struct open Gc let used_words ( ) = let c = get ( ) in set { c with minor_heap_size = 1000 ; } ; compact ( ) ; let s = stat ( ) in let res = s . live_words in set c ; res let with_big_compacts f v = let used_before = used_words ( ) in Spotlib . Spot . Exn . protect_with f v ~ finally ( : fun _ -> let used_after = used_words ( ) in used_before , used_after ) end
let tnb data = try int_of_string ( List . hd ( String . split ' \ 000 ' data ) ) with _ -> 0
let do_test xb = let i = ref 0 in let disp op pkt = let tid , rid , ty , data = pkt in printf " % 3x % s % d ( % d ) % s " \% s " . \\ n " %! ! i op tid rid ( Xb . Op . to_string ty ) ( String . escaped data ) ; flush ( stdout ) ; in let y ( tid , ty , data ) = let spkt = ( tid , ! i , ty , data ) in disp " S : " spkt ; send_packet xb tid ! i ty data ; let rpkt = recv_packet xb in disp " R : " rpkt ; let ( _ , _ , _ , data ) = rpkt in data in let x spkt = ignore ( y spkt ) in x ( 0 , Xb . Op . Read , " \ 000 " ) ; x ( 0 , Xb . Op . Write , " \ 000 " ) ; x ( 0 , Xb . Op . Getdomainpath , " \ 000 " ) ; x ( 0 , Xb . Op . Directory , " \ 000 " ) ; x ( 0 , Xb . Op . Mkdir , " \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " \ 000 " ) ; x ( 0 , Xb . Op . Write , " / test \ 000xxx \ 000yyy \ 000 \ 000zzz " ) ; x ( 0 , Xb . Op . Read , " / test " ) ; x ( 0 , Xb . Op . Read , " / test \ 000 " ) ; x ( 0 , Xb . Op . Read , " / test \ 000some \ 000otherargs " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000spurious \ 000abc " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000spurious " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000someotherargs " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000someotherargs \ 000others " ) ; x ( 0 , Xb . Op . Write , " / test \ 000 " ) ; x ( 0 , Xb . Op . Write , " / test \ 000abc " ) ; x ( 0 , Xb . Op . Read , " / test " ) ; x ( 0 , Xb . Op . Read , " / test \ 000 " ) ; x ( 0 , Xb . Op . Read , " / test \ 000 \ 000 " ) ; x ( 0 , Xb . Op . Write , " / test " ) ; x ( 0 , Xb . Op . Read , " / test " ) ; x ( 0 , Xb . Op . Read , " / test \ 000 " ) ; x ( 0 , Xb . Op . Read , " / test \ 000 \ 000 " ) ; x ( 0 , Xb . Op . Write , " \ 000 " ) ; / x ( 0 , Xb . Op . Directory , " / test " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000 " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000 \ 000 " ) ; x ( 0 , Xb . Op . Rm , " / test " ) ; x ( 0 , Xb . Op . Directory , " / test " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000 " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000 \ 000 " ) ; x ( 0 , Xb . Op . Write , " / test / abc \ 000x1 " ) ; x ( 0 , Xb . Op . Write , " / test / def \ 000x2 " ) ; x ( 0 , Xb . Op . Write , " / test / xyz \ 000x3 " ) ; x ( 0 , Xb . Op . Write , " / test / xyz \ 000x4 " ) ; x ( 0 , Xb . Op . Directory , " / test " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000 " ) ; x ( 0 , Xb . Op . Directory , " / test \ 000spurious \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000spurious \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000 \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000n0 \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000n0 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000n0 \ 000r1 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000n0 \ 000r1 \ 000 " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; x ( 0 , Xb . Op . Setperms , " / test \ 000n0r2 \ 000spurious " ) ; x ( 0 , Xb . Op . Getperms , " / test \ 000 " ) ; let t1 = tnb ( y ( 0 , Xb . Op . Transaction_start , " \ 000 " ) ) in x ( t1 , Xb . Op . Transaction_end , " \ 000 " ) ; let t2 = tnb ( y ( 0 , Xb . Op . Transaction_start , " \ 000 " ) ) in x ( t2 , Xb . Op . Transaction_end , string_of_int t2 ^ " \ 000 " ) ; let t3 = tnb ( y ( 0 , Xb . Op . Transaction_start , " \ 000 \ 000 " ) ) in x ( t3 , Xb . Op . Transaction_end , " 0 \ 000 \ 000 " ) ; ( )
let ( ) = let xb = open_xb ( ) in finally ( fun ( ) -> do_test xb ) ( fun ( ) -> close_xb xb ) ;
module type XStringSig = sig type xstring = UChar . t XArray . t val get : xstring -> int -> UChar . t val set : xstring -> int -> UChar . t -> unit val length : xstring -> int type index val look : xstring -> index -> UChar . t val nth : xstring -> int -> index val first : xstring -> index val last : xstring -> index val out_of_range : xstring -> index -> bool val next : xstring -> index -> index val prev : xstring -> index -> index val move : xstring -> index -> int -> index val compare_index : xstring -> index -> index -> int val make : ? bufsize : int -> int -> UChar . t -> xstring val clear : xstring -> unit val reset : xstring -> unit val copy : xstring -> xstring val sub : xstring -> int -> int -> xstring val add_char : xstring -> UChar . t -> unit val add_text : xstring -> ' a UText . text -> unit val add_xstring : xstring -> xstring -> unit val shrink : xstring -> int -> unit val append : xstring -> xstring -> xstring val utext_of : xstring -> UText . t val ustring_of : xstring -> UText . ustring val iter : ( UChar . t -> unit ) unit -> xstring -> unit val compare : xstring -> xstring -> int end
module XStringAux : XStringSig = struct include XArray type xstring = UChar . t XArray . t let rec compare_aux i t1 t2 = if i >= length t1 then if i >= length t2 then 0 else ~- 1 else if i >= length t2 then 1 else match UChar . compare ( XArray . get t1 i ) i ( XArray . get t2 i ) i with 0 -> compare_aux ( i + 1 ) 1 t1 t2 | sgn -> sgn let compare t1 t2 = compare_aux 0 t1 t2 let add_xstring = add_xarray let add_char = add_element let add_text b t = UText . iter ( add_char b ) b t let ustring_of b = UText . init_ustring ( length b ) b ( get b ) b let utext_of b = UText . init ( length b ) b ( get b ) b end
let init len f = XArray . init len ( UChar . chr_of_uint 0 ) 0 f
module Buf = struct include XStringAux type buf = xstring let create bufsize = make ~ bufsize 0 ( UChar . chr_of_uint 0 ) 0 let contents x = x let add_string = add_xstring let add_buffer = add_xstring end
module String = struct include String let of_char c = String . make 1 c let rev_map f string = let n = length string in String . init n ( fun i -> f string . [ n - i - 1 ] ) let rev_iter f string = for i = length string - 1 downto 0 do f string . [ i ] done let fold_left f accu string = let accu = ref accu in for i = 0 to length string - 1 do accu := f ! accu string . [ i ] done ; ! accu let fold_right f string accu = let accu = ref accu in for i = length string - 1 downto 0 do accu := f string . [ i ] ! accu done ; ! accu let explode string = fold_right ( fun h t -> h :: t ) string [ ] let implode list = concat " " ( List . map of_char list ) let endswith suffix x = let x_l = String . length x and suffix_l = String . length suffix in suffix_l <= x_l && String . sub x ( x_l - suffix_l ) suffix_l = suffix let startswith prefix x = let x_l = String . length x and prefix_l = String . length prefix in prefix_l <= x_l && String . sub x 0 prefix_l = prefix let isspace = function ' ' | ' \ n ' | ' \ r ' | ' \ t ' -> true | _ -> false let strip predicate string = let rec remove = function | [ ] -> [ ] | c :: cs -> if predicate c then remove cs else c :: cs in implode ( List . rev ( remove ( List . rev ( remove ( explode string ) ) ) ) ) let escaped ? rules string = match rules with | None -> String . escaped string | Some rules -> let aux h t = ( if List . mem_assoc h rules then List . assoc h rules else of_char h ) :: t in concat " " ( fold_right aux string [ ] ) let split_f p str = let not_p x = not ( p x ) in let rec split_one p acc = function | [ ] -> ( List . rev acc , [ ] ) | c :: cs -> if p c then split_one p ( c :: acc ) cs else ( List . rev acc , c :: cs ) in let rec alternate acc drop chars = if chars = [ ] then acc else let a , b = split_one ( if drop then p else not_p ) [ ] chars in alternate ( if drop then acc else a :: acc ) ( not drop ) b in List . rev ( List . map implode ( alternate [ ] true ( explode str ) ) ) let index_opt s c = let rec loop i = if String . length s = i then None else if s . [ i ] = c then Some i else loop ( i + 1 ) in loop 0 let rec split ( ? limit = - 1 ) c s = let i = match index_opt s c with Some x -> x | None -> - 1 in let nlimit = if limit = - 1 || limit = 0 then limit else limit - 1 in if i = - 1 || nlimit = 0 then [ s ] else let a = String . sub s 0 i and b = String . sub s ( i + 1 ) ( String . length s - i - 1 ) in a :: split ~ limit : nlimit c b let rtrim s = let n = String . length s in if n > 0 && s . [ n - 1 ] = ' \ n ' then String . sub s 0 ( n - 1 ) else s let has_substr str sub = if String . length sub > String . length str then false else let result = ref false in for start = 0 to String . length str - String . length sub do if String . sub str start ( String . length sub ) = sub then result := true done ; ! result let find_all needle haystack = let m = String . length needle and n = String . length haystack in if m > n then [ ] else let i = ref 0 and found = ref [ ] in while ! i < n - m + 1 do if String . sub haystack ! i m = needle then ( found := ! i :: ! found ; i := ! i + m ) else incr i done ; List . rev ! found let replace f t s = let indexes = find_all f s in let n = List . length indexes in if n > 0 then ( let len_f = String . length f and len_t = String . length t in let new_len = String . length s + ( n * len_t ) - ( n * len_f ) in let new_b = Bytes . make new_len ' \ 000 ' in let orig_offset = ref 0 and dest_offset = ref 0 in List . iter ( fun h -> let len = h - ! orig_offset in Bytes . blit_string s ! orig_offset new_b ! dest_offset len ; Bytes . blit_string t 0 new_b ( ! dest_offset + len ) len_t ; orig_offset := ! orig_offset + len + len_f ; dest_offset := ! dest_offset + len + len_t ) indexes ; Bytes . blit_string s ! orig_offset new_b ! dest_offset ( String . length s - ! orig_offset ) ; Bytes . unsafe_to_string new_b ) else s let filter_chars s valid = let badchars = ref false in let buf = Buffer . create 0 in for i = 0 to String . length s - 1 do if ! badchars then ( if valid s . [ i ] then Buffer . add_char buf s . [ i ] ) else if not ( valid s . [ i ] ) then ( Buffer . add_substring buf s 0 i ; badchars := true ) done ; if ! badchars then Buffer . contents buf else s let map_unlikely s f = let changed = ref false in let m = ref 0 in let buf = Buffer . create 0 in for i = 0 to String . length s - 1 do match f s . [ i ] with | None -> ( ) | Some n -> changed := true ; Buffer . add_substring buf s ! m ( i - ! m ) ; Buffer . add_string buf n ; m := i + 1 done ; if ! changed then ( Buffer . add_substring buf s ! m ( String . length s - ! m ) ; Buffer . contents buf ) else s let sub_to_end s start = let length = String . length s in String . sub s start ( length - start ) let sub_before c s = String . sub s 0 ( String . index s c ) let sub_after c s = sub_to_end s ( String . index s c + 1 ) end
let test_boolean tested_f ( name , case , expected ) = let check ( ) = Alcotest . ( check bool ) name expected ( tested_f case ) in ( name , ` Quick , check )
let test_string tested_f ( name , case , expected ) = let check ( ) = Alcotest . ( check string ) name expected ( tested_f case ) in ( name , ` Quick , check )
let test_list tested_f ( name , case , expected ) = let check ( ) = Alcotest . ( check @@ list string ) name expected ( tested_f case ) in ( name , ` Quick , check )
let test_rev_map = let spec_rev = [ ( " " , " " ) ; ( " foo bar " , " rab oof " ) ] in let spec_func = [ ( " id " , Fun . id ) ; ( " uppercase_ascii " , Char . uppercase_ascii ) ] in let test ( f_name , f ) ( case , expected ) = let expected = String . map f expected in let name = Printf . sprintf { " |% s " produces " % s " ( % s ) } | case expected f_name in test_string ( XString . rev_map f ) ( name , case , expected ) in let tests = List . concat ( List . map ( fun func -> List . map ( test func ) spec_rev ) spec_func ) in ( " rev_map " , tests )
let test_split = let test ? limit ( splitter , splitted , expected ) = let split , name = match limit with | None -> let name = Printf . sprintf { ' |% c ' splits " % s " } | splitter splitted in let split = XString . split ~ limit ( :- 1 ) in ( split , name ) | Some limit -> let name = Printf . sprintf { ' |% c ' splits " % s " with limit % i } | splitter splitted limit in let split = XString . split ~ limit in ( split , name ) in test_list ( split splitter ) ( name , splitted , expected ) in let specs_no_limit = [ ( ' . ' , " . . . " , [ " " ; " " ; " " ; " " ] ) ; ( ' . ' , " foo . bar . baz " , [ " foo " ; " bar " ; " baz " ] ) ] in let tests_no_limit = List . map test specs_no_limit in let specs_limit = [ ( 0 , [ ( ' . ' , " . . . " , [ " . . . " ] ) ; ( ' . ' , " foo . bar . baz " , [ " foo . bar . baz " ] ) ] ) ; ( 1 , [ ( ' . ' , " . . . " , [ " . . . " ] ) ; ( ' . ' , " foo . bar . baz " , [ " foo . bar . baz " ] ) ] ) ; ( 2 , [ ( ' . ' , " . . . " , [ " " ; " . . " ] ) ; ( ' . ' , " foo . bar . baz " , [ " foo " ; " bar . baz " ] ) ] ) ; ( 3 , [ ( ' . ' , " . . . " , [ " " ; " " ; " . " ] ) ; ( ' . ' , " foo . bar . baz " , [ " foo " ; " bar " ; " baz " ] ) ] ) ; ( 4 , [ ( ' . ' , " . . . " , [ " " ; " " ; " " ; " " ] ) ] ) ] in let tests_limit = List . map ( fun ( limit , spec ) -> List . map ( test ~ limit ) spec ) specs_limit |> List . concat in ( " split " , List . concat [ tests_no_limit ; tests_limit ] )
let test_split_f = let specs = [ ( XString . isspace , " foo bar " , [ " foo " ; " bar " ] ) ; ( XString . isspace , " foo bar " , [ " foo " ; " bar " ] ) ; ( XString . isspace , " foo \ n \ t \ r bar " , [ " foo " ; " bar " ] ) ; ( XString . isspace , " foo bar " , [ " foo " ; " bar " ] ) ; ( XString . isspace , " " , [ ] ) ; ( XString . isspace , " " , [ ] ) ] in let test ( splitter , splitted , expected ) = let name = Printf . sprintf { " |% s " } | ( String . escaped splitted ) in test_list ( XString . split_f splitter ) ( name , splitted , expected ) in let tests = List . map test specs in ( " split_f " , tests )
let test_has_substr = let spec = [ ( " " , " " , true ) ; ( " " , " foo bar " , true ) ; ( " f " , " foof " , true ) ; ( " foofo " , " foof " , false ) ; ( " foof " , " foof " , true ) ; ( " f " , " foof " , true ) ; ( " fo " , " foof " , true ) ; ( " of " , " foof " , true ) ; ( " ff " , " foof " , false ) ] in let test ( contained , container , expected ) = let name = Printf . sprintf { " |% s " in " % s " } | contained container in test_boolean ( XString . has_substr container ) ( name , contained , expected ) in ( " has_substr " , List . map test spec )
let test_startswith = let spec = [ ( " " , " " , true ) ; ( " " , " foo bar " , true ) ; ( " foofo " , " foof " , false ) ; ( " foof " , " foof " , true ) ; ( " f " , " foof " , true ) ; ( " fo " , " foof " , true ) ; ( " of " , " foof " , false ) ; ( " ff " , " foof " , false ) ] in let test ( contained , container , expected ) = let name = Printf . sprintf { " |% s " starts with " % s " } | container contained in test_boolean ( XString . startswith contained ) ( name , container , expected ) in ( " startswith " , List . map test spec )
let test_endswith = let spec = [ ( " " , " " , true ) ; ( " " , " foo bar " , true ) ; ( " ofoof " , " foof " , false ) ; ( " foof " , " foof " , true ) ; ( " f " , " foof " , true ) ; ( " fo " , " foof " , false ) ; ( " of " , " foof " , true ) ; ( " ff " , " foof " , false ) ] in let test ( contained , container , expected ) = let name = Printf . sprintf { " |% s " ends with " % s " } | container contained in test_boolean ( XString . endswith contained ) ( name , container , expected ) in ( " endswith " , List . map test spec )
let test_rtrim = let spec = [ ( " " , " " ) ; ( " \ n " , " " ) ; ( " \ n \ n " , " \ n " ) ; ( " \ n " , " \ n " ) ; ( " foo \ n " , " foo " ) ; ( " fo \ no " , " fo \ no " ) ] in let test ( case , expected ) = let name = Printf . sprintf { " |% s " gets trimmed to " % s " } | ( String . escaped case ) ( String . escaped expected ) in test_string XString . rtrim ( name , case , expected ) in ( " rtrim " , List . map test spec )
let ( ) = Alcotest . run " Xstringext " [ test_rev_map ; test_split ; test_split_f ; test_has_substr ; test_startswith ; test_endswith ; test_rtrim ]
let ( |> ) a b = b a
let getdomainpath domid client = immediate client ( fun xs -> getdomainpath xs domid ) >>= fun dom_path -> return ( prefix ^ dom_path )
let readdir d client = Lwt . catch ( fun ( ) -> immediate client ( fun xs -> directory xs d ) ) ( function | Xs_protocol . Enoent _ -> return [ ] | e -> Lwt . fail e )
let read_opt path xs = Lwt . catch ( fun ( ) -> read xs path >>= fun x -> Lwt . return ( Some x ) ) ( function | Xs_protocol . Enoent _ -> return None | e -> Lwt . fail e )
let exists path xs = read_opt path xs >|= ( fun x -> x <> None )
module Device = struct type kind = Vif | Vbd | Tap | Pci | Vfs | Vfb | Vkbd let kind_of_string = function | " vif " -> Some Vif | " vbd " -> Some Vbd | " tap " -> Some Tap | " pci " -> Some Pci | " vfs " -> Some Vfs | " vfb " -> Some Vfb | " vkbd " -> Some Vkbd | x -> None let string_of_kind = function | Vif -> " vif " | Vbd -> " vbd " | Tap -> " tap " | Pci -> " pci " | Vfs -> " vfs " | Vfb -> " vfb " | Vkbd -> " vkbd " type devid = int type endpoint = { domid : int ; kind : kind ; devid : int } type device = { frontend : endpoint ; backend : endpoint } let parse_int i = try Some ( int_of_string i ) with _ -> None let rec split ? limit ( : limit ( =- 1 ) ) c s = let i = try String . index s c with Not_found -> - 1 in let nlimit = if limit = - 1 || limit = 0 then limit else limit - 1 in if i = - 1 || nlimit = 0 then [ s ] else let a = String . sub s 0 i and b = String . sub s ( i + 1 ) ( String . length s - i - 1 ) in a :: ( split ~ limit : nlimit c b ) let parse_backend_link x = match split ' ' / x with | [ " " ; " local " ; " domain " ; domid ; " backend " ; kind ; _ ; devid ] -> begin match parse_int domid , kind_of_string kind , parse_int devid with | Some domid , Some kind , Some devid -> Some { domid = domid ; kind = kind ; devid = devid } | _ , _ , _ -> None end | _ -> None let to_list xs = List . fold_left ( fun acc x -> match x with | Some x -> x :: acc | None -> acc ) [ ] xs let list_kinds dir client = readdir dir client >|= List . map kind_of_string >|= to_list let list_frontends domid client = getdomainpath domid client >>= fun dom_path -> let frontend_dir = dom_path ^ " / device " in list_kinds frontend_dir client >>= fun kinds -> Lwt_list . map_s ( fun k -> let dir = Printf . sprintf " % s /% s " frontend_dir ( string_of_kind k ) in readdir dir client >|= List . map parse_int >|= to_list >>= fun devids -> Lwt_list . map_s ( fun devid -> let frontend = { domid = domid ; kind = k ; devid = devid } in Lwt . catch ( fun ( ) -> immediate client ( fun xs -> read xs ( Printf . sprintf " % s /% d / backend " dir devid ) >>= fun x -> match parse_backend_link x with | Some b -> return ( Some { backend = b ; frontend = frontend } ) | None -> return None ) ) ( fun _ -> return None ) ) devids >|= to_list ) kinds >>= fun ll -> return ( List . concat ll ) let backend_path_of_device ( x : device ) client = getdomainpath x . backend . domid client >>= fun dom_path -> return ( Printf . sprintf " % s / backend /% s /% u /% d " dom_path ( string_of_kind x . backend . kind ) x . frontend . domid x . backend . devid ) let backend_error_path_of_device ( x : device ) client = getdomainpath x . backend . domid client >>= fun dom_path -> return ( Printf . sprintf " % s / error / backend /% s /% d " dom_path ( string_of_kind x . backend . kind ) x . frontend . domid ) let frontend_path_of_device ( x : device ) client = getdomainpath x . backend . domid client >>= fun dom_path -> return ( Printf . sprintf " % s / device /% s /% d " dom_path ( string_of_kind x . frontend . kind ) x . frontend . devid ) let frontend_error_path_of_device ( x : device ) client = getdomainpath x . frontend . domid client >>= fun dom_path -> return ( Printf . sprintf " % s / error / device /% s /% d / error " dom_path ( string_of_kind x . frontend . kind ) x . frontend . devid ) let hard_shutdown_request ( x : device ) client = backend_path_of_device x client >>= fun backend_path -> frontend_path_of_device x client >>= fun frontend_path -> let online_path = backend_path ^ " / online " in immediate client ( fun xs -> write xs online_path " 0 " >>= fun ( ) -> rm xs frontend_path ) let private_path = prefix ^ " / xapi " let get_private_path domid = Printf . sprintf " % s /% d " private_path domid let get_private_data_path_of_device ( x : device ) = Printf . sprintf " % s / private /% s /% d " ( get_private_path x . frontend . domid ) ( string_of_kind x . backend . kind ) x . backend . devid let get_hotplug_path ( x : device ) = Printf . sprintf " % s / hotplug /% s /% d " ( get_private_path x . frontend . domid ) ( string_of_kind x . backend . kind ) x . backend . devid let get_private_data_path_of_device ( x : device ) = Printf . sprintf " % s / private /% s /% d " ( get_private_path x . frontend . domid ) ( string_of_kind x . backend . kind ) x . backend . devid let rm_device_state ( x : device ) client = immediate client ( fun xs -> frontend_path_of_device x client >>= fun fe -> backend_path_of_device x client >>= fun be -> backend_error_path_of_device x client >>= fun ber -> frontend_error_path_of_device x client >>= fun fer -> Lwt_list . iter_s ( rm xs ) [ fe ; be ; ber ; Filename . dirname fer ] ) let hard_shutdown device client = hard_shutdown_request device client >>= fun ( ) -> rm_device_state device client let add device client = let backend_list = [ ] and frontend_list = [ ] and private_list = [ ] in frontend_path_of_device device client >>= fun frontend_path -> backend_path_of_device device client >>= fun backend_path -> let hotplug_path = get_hotplug_path device in let private_data_path = get_private_data_path_of_device device in transaction client ( fun xs -> exists ( Printf . sprintf " / local / domain /% d / vm " device . backend . domid ) xs >>= fun _ -> exists frontend_path xs >>= fun _ -> Lwt . catch ( fun ( ) -> rm xs frontend_path ) ( fun _ -> return ( ) ) >>= fun ( ) -> Lwt . catch ( fun ( ) -> rm xs backend_path ) ( fun _ -> return ( ) ) >>= fun ( ) -> mkdir xs frontend_path >>= fun ( ) -> setperms xs frontend_path ( Xs_protocol . ACL . ( { owner = device . frontend . domid ; other = NONE ; acl = [ device . backend . domid , READ ] } ) ) >>= fun ( ) -> mkdir xs backend_path >>= fun ( ) -> setperms xs backend_path ( Xs_protocol . ACL . ( { owner = device . backend . domid ; other = NONE ; acl = [ device . frontend . domid , READ ] } ) ) >>= fun ( ) -> mkdir xs hotplug_path >>= fun ( ) -> setperms xs hotplug_path ( Xs_protocol . ACL . ( { owner = device . backend . domid ; other = NONE ; acl = [ ] } ) ) >>= fun ( ) -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( frontend_path ^ " " / ^ x ) y ) ( ( " backend " , backend_path ) :: frontend_list ) >>= fun ( ) -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( backend_path ^ " " / ^ x ) y ) ( ( " frontend " , frontend_path ) :: backend_list ) >>= fun ( ) -> mkdir xs private_data_path >>= fun ( ) -> setperms xs private_data_path ( Xs_protocol . ACL . ( { owner = device . backend . domid ; other = NONE ; acl = [ ] } ) ) >>= fun ( ) -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( private_data_path ^ " " / ^ x ) y ) ( ( " backend - kind " , string_of_kind device . backend . kind ) :: ( " backend - id " , string_of_int device . backend . domid ) :: private_list ) ) end
module Domain = struct let make domid client = getdomainpath domid client >>= fun dom_path -> let uuid = Printf . sprintf " uuid -% d " domid in let name = " name " in let vm_path = prefix ^ " / vm " / ^ uuid in let vss_path = prefix ^ " / vss " / ^ uuid in let xsdata = [ " xsdata " , " xsdata " ] in let platformdata = [ " platformdata " , " platformdata " ] in let bios_strings = [ " bios_strings " , " bios_strings " ] in let roperm = Xs_protocol . ACL . ( { owner = 0 ; other = NONE ; acl = [ domid , READ ] } ) in let rwperm = Xs_protocol . ACL . ( { owner = domid ; other = NONE ; acl = [ ] } ) in transaction client ( fun xs -> Lwt . catch ( fun ( ) -> rm xs dom_path ) ( fun _ -> return ( ) ) >>= fun ( ) -> mkdir xs dom_path >>= fun ( ) -> setperms xs dom_path roperm >>= fun ( ) -> immediate client ( exists vm_path ) >>= fun vm_exists -> ( if not vm_exists then begin mkdir xs vm_path >>= fun ( ) -> setperms xs vm_path roperm >>= fun ( ) -> write xs ( vm_path ^ " / uuid " ) uuid >>= fun ( ) -> write xs ( vm_path ^ " / name " ) name end else return ( ) ) >>= fun ( ) -> write xs ( Printf . sprintf " % s / domains /% d " vm_path domid ) dom_path >>= fun ( ) -> mkdir xs vss_path >>= fun ( ) -> setperms xs vss_path rwperm >>= fun ( ) -> write xs ( dom_path ^ " / vm " ) vm_path >>= fun ( ) -> write xs ( dom_path ^ " / vss " ) vss_path >>= fun ( ) -> write xs ( dom_path ^ " / name " ) name >>= fun ( ) -> Lwt_list . iter_s ( fun dir -> let ent = Printf . sprintf " % s /% s " dom_path dir in mkdir xs ent >>= fun ( ) -> setperms xs ent roperm ) [ " cpu " ; " memory " ] >>= fun ( ) -> Lwt_list . iter_s ( fun dir -> let ent = Printf . sprintf " % s /% s " dom_path dir in mkdir xs ent >>= fun ( ) -> setperms xs ent rwperm ) [ " device " ; " error " ; " drivers " ; " control " ; " attr " ; " data " ; " messages " ; " vm - data " ] ) >>= fun ( ) -> immediate client ( fun xs -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( dom_path ^ " " / ^ x ) y ) xsdata >>= fun ( ) -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( dom_path ^ " / platform " / ^ x ) y ) platformdata >>= fun ( ) -> Lwt_list . iter_s ( fun ( x , y ) -> write xs ( dom_path ^ " / bios - strings " / ^ x ) y ) bios_strings >>= fun ( ) -> write xs ( dom_path ^ " / action - request " ) " poweroff " >>= fun ( ) -> write xs ( dom_path ^ " / control / platform - feature - multiprocessor - suspend " ) " 1 " >>= fun ( ) -> write xs ( dom_path ^ " / unique - domain - id " ) uuid ) let control_shutdown domid client = getdomainpath domid client >|= ( fun x -> x ^ " / control / shutdown " ) let string_of_shutdown_reason _ = " halt " let get_uuid domid = Printf . sprintf " uuid -% d " domid let shutdown domid req client = let reason = string_of_shutdown_reason req in control_shutdown domid client >>= fun path -> getdomainpath domid client >>= fun dom_path -> transaction client ( fun xs -> immediate client ( exists dom_path ) >>= fun domain_exists -> if domain_exists then begin write xs path reason >>= fun ( ) -> return true end else return false ) let destroy domid client = getdomainpath domid client >>= fun dom_path -> Device . list_frontends domid client >>= fun all_devices -> Lwt_list . iter_s ( fun device -> Device . hard_shutdown device client ) all_devices >>= fun ( ) -> immediate client ( read_opt ( dom_path ^ " / vm " ) ) >>= fun vm_path -> immediate client ( read_opt ( dom_path ^ " / vss " ) ) >>= fun vss_path -> begin match vm_path with | Some vm_path -> immediate client ( fun xs -> rm xs ( vm_path ^ " / domains " / ^ ( string_of_int domid ) ) >>= fun ( ) -> readdir ( vm_path ^ " / domains " ) client >>= fun domains -> if List . filter ( fun x -> x <> " " ) domains = [ ] then begin rm xs vm_path >>= fun ( ) -> begin match vss_path with | Some vss_path -> rm xs vss_path | None -> return ( ) end end else return ( ) ) | None -> return ( ) end >>= fun ( ) -> immediate client ( fun xs -> rm xs dom_path ) >>= fun ( ) -> getdomainpath 0 client >|= ( fun x -> x ^ " / backend " ) >>= fun backend_path -> readdir backend_path client >>= fun all_backend_types -> Lwt_list . iter_s ( fun ty -> immediate client ( fun xs -> rm xs ( Printf . sprintf " % s /% s /% d " backend_path ty domid ) ) ) all_backend_types end
let vm_shutdown domid client = Domain . shutdown domid ( ) client >>= fun _ -> Domain . destroy domid client
let vm_start domid client = let vbd devid = { Device . frontend = { Device . domid = domid ; kind = Device . Vbd ; devid = 0 } ; backend = { Device . domid = 0 ; kind = Device . Vbd ; devid = 0 } } in Domain . make domid client >>= fun ( ) -> Lwt_list . iter_s ( fun d -> Device . add d client ) [ vbd 0 ; vbd 1 ; vbd 2 ]
let vm_cycle domid client = vm_start domid client >>= fun ( ) -> vm_shutdown domid client
let rec between start finish = if start > finish then [ ] else start :: ( between ( start + 1 ) finish )
let sequential n client : unit Lwt . t = Lwt_list . iter_s ( fun domid -> vm_cycle domid client ) ( between 0 n )
let parallel n client = Lwt_list . iter_p ( fun domid -> vm_cycle domid client ) ( between 0 n )
let query m n client = Lwt_list . iter_s ( fun domid -> vm_start domid client ) ( between 0 n ) >>= fun ( ) -> let rec loop i = if i = m then Lwt . return_unit else begin Lwt_list . iter_p ( fun domid -> immediate client ( fun xs -> read xs ( Printf . sprintf " % s / local / domain /% d / name " prefix domid ) >>= fun _ -> Lwt . return_unit ) ) ( between 0 n ) >>= fun ( ) -> loop ( i + 1 ) end in loop 0 >>= fun ( ) -> Lwt_list . iter_s ( fun domid -> vm_shutdown domid client ) ( between 0 n )
let time f = let start = Unix . gettimeofday ( ) in f ( ) >>= fun ( ) -> return ( Unix . gettimeofday ( ) . - start )
let usage ( ) = let bin x = Sys . argv . ( 0 ) ^ x in let lines = [ bin " : a xenstore benchmark tool " ; " " ; " Usage " ; : bin " [ - path / var / run / xenstored / socket ] [ - n number of vms ] " ; ] in List . iter ( fun x -> Printf . fprintf stderr " % s \ n " x ) lines
let main ( ) = let verbose = ref false in let args = Sys . argv |> Array . to_list |> List . tl in if List . mem " - h " args then begin usage ( ) ; return ( ) ; end else begin verbose := List . mem " - v " args ; let args = List . filter ( fun x -> x <> " - v " ) args in let extract args key = let result = ref None in let args = List . fold_left ( fun ( acc , foundit ) x -> if foundit then ( result := Some x ; ( acc , false ) ) else if x = key then ( acc , true ) else ( x :: acc , false ) ) ( [ ] , false ) args |> fst |> List . rev in ! result , args in let path , args = extract args " - path " in begin match path with | Some path -> Xs_transport . xenstored_socket := path | None -> ( ) end ; let n , args = extract args " - n " in let n = match n with | None -> 300 | Some n -> int_of_string n in make ( ) >>= fun client -> time ( fun ( ) -> sequential n client ) >>= fun t -> Lwt_io . write Lwt_io . stdout ( Printf . sprintf " % d sequential starts and shutdowns : . % 02f \ n " n t ) >>= fun ( ) -> time ( fun ( ) -> parallel n client ) >>= fun t -> Lwt_io . write Lwt_io . stdout ( Printf . sprintf " % d parallel starts and shutdowns : . % 02f \ n " n t ) >>= fun ( ) -> time ( fun ( ) -> query 1000 n client ) >>= fun t -> Lwt_io . write Lwt_io . stdout ( Printf . sprintf " % d read queries per % d VMs : . % 02f \ n " 1000 n t ) end
let _ = Lwt_main . run ( main ( ) )
let ( |> ) a b = b a
type expr = | Val of string | Not of expr | And of expr * expr | Or of expr * expr | Eq of expr * expr
let rec pretty_print ( ) = let open Format in function | Val x -> sprintf " " \% s " " \ x | Not x -> sprintf " Not ( [ @% a ] ) " @ pretty_print x | And ( x , y ) -> sprintf " And ( [ @% a , @ % a ] ) " @ pretty_print x pretty_print y | Or ( x , y ) -> sprintf " Or ( [ @% a , @ % a ] ) " @ pretty_print x pretty_print y | Eq ( x , y ) -> sprintf " Eq ( [ @% a , @ % a ] ) " @ pretty_print x pretty_print y
let rec to_conjunction = function | And ( x , y ) -> ( to_conjunction x ) @ ( to_conjunction y ) | Eq ( Val k , Val v ) -> [ k , v ] | _ -> raise Invalid_expression
let parse_expr s = let open Genlex in let keywords = [ " ( " ; " ) " ; " not " ; " " ; = " and " ; " or " ] in let flatten s = let to_list s = let result = ref [ ] in Stream . iter ( fun x -> result := x :: ! result ) s ; List . rev ! result in let ident is = if is = [ ] then [ ] else [ Ident ( String . concat " " ( List . rev is ) ) ] in let is , tokens = List . fold_left ( fun ( is , tokens ) x -> match is , x with | is , Ident i -> ( i :: is ) , tokens | is , x -> [ ] , ( x :: ( ident is ) @ tokens ) ) ( [ ] , [ ] ) ( to_list s ) in ident is @ tokens |> List . rev |> Stream . of_list in let rec parse_atom ( __strm : _ Stream . t ) = match Stream . peek __strm with | Some ( Int n ) -> ( Stream . junk __strm ; Val ( string_of_int n ) ) | Some ( Ident n ) -> ( Stream . junk __strm ; Val n ) | Some ( Float n ) -> ( Stream . junk __strm ; Val ( string_of_float n ) ) | Some ( String n ) -> ( Stream . junk __strm ; Val n ) | Some ( Kwd " not " ) -> ( Stream . junk __strm ; let e = ( try parse_expr __strm with | Stream . Failure -> raise ( Stream . Error " " ) ) in Not e ) | Some ( Kwd " ( " ) -> ( Stream . junk __strm ; let e = ( try parse_expr __strm with | Stream . Failure -> raise ( Stream . Error " " ) ) in ( match Stream . peek __strm with | Some ( Kwd " ) " ) -> ( Stream . junk __strm ; e ) | _ -> raise ( Stream . Error " " ) ) ) | _ -> raise Stream . Failure and parse_expr ( __strm : _ Stream . t ) = let e1 = parse_atom __strm in let stream = __strm in ( fun ( __strm : _ Stream . t ) -> match Stream . peek __strm with | Some ( Kwd " and " ) -> ( Stream . junk __strm ; let e2 = ( try parse_expr __strm with | Stream . Failure -> raise ( Stream . Error " " ) ) in And ( e1 , e2 ) ) | Some ( Kwd " or " ) -> ( Stream . junk __strm ; let e2 = ( try parse_expr __strm with | Stream . Failure -> raise ( Stream . Error " " ) ) in Or ( e1 , e2 ) ) | Some ( Kwd " " ) = -> ( Stream . junk __strm ; let e2 = ( try parse_expr __strm with | Stream . Failure -> raise ( Stream . Error " " ) ) in Eq ( e1 , e2 ) ) | _ -> e1 ) stream in s |> Stream . of_string |> make_lexer keywords |> flatten |> parse_expr
let rec eval_expression expr xs = match expr with | Val path -> Lwt . catch ( fun ( ) -> read xs path >>= fun _k -> return true ) ( function Enoent _ -> return false | e -> Lwt . fail e ) | Not a -> eval_expression a xs >>= fun a ' -> return ( not ( a ' ) ) | And ( a , b ) -> eval_expression a xs >>= fun a ' -> eval_expression b xs >>= fun b ' -> return ( a ' && b ' ) | Or ( a , b ) -> eval_expression a xs >>= fun a ' -> eval_expression b xs >>= fun b ' -> return ( a ' || b ' ) | Eq ( Val path , Val v ) -> Lwt . catch ( fun ( ) -> read xs path >>= fun v ' -> return ( v = v ' ) ) ( function | Enoent _ -> return false | e -> Lwt . fail e ) | _ -> fail Invalid_expression
let usage ( ) = let bin x = Sys . argv . ( 0 ) ^ x in let lines = [ bin " : a xenstore protocol client " ; " " ; " Usage " ; : bin " [ - path / var / run / xenstored / socket ] [ - restrict domid ] < subcommand > [ args ] " ; " " ; " Where < subcommand > can be one of " ; : " " ; bin " read < key " ; > " -- read the value stored at < key , > or fail if it doesn ' t exist " ; bin " write < key = val > [ and keyN = valN ] " ; * " -- write the key value pair ( s ) " ; bin " directory < key " ; > " -- list the direct children of < key " ; > bin " wait < expr " ; > " -- block until the < expr > is true " ; bin " debug < cmd > [ arg ] " ; " -- execute the given debug command " ; " " ; " Example expressions " ; : " " ; bin " wait / foo " ; " -- block until the key " \/ foo " \ exists " ; bin " wait not ( / foo ) " ; " -- block until the key " \/ foo " \ is deleted " ; bin " wait / foo or / bar " ; " -- block until either key " \/ foo " \ or " \/ bar " \ are created " ; bin " wait / foo and ( / bar = hello ) " ; " -- block until either key " \/ foo " \ is created or key " \/ bar " \ has value " \ hello " " ; \ ] in List . iter ( fun x -> Printf . fprintf stderr " % s \ n " x ) lines
let main ( ) = let verbose = ref false in let args = Sys . argv |> Array . to_list |> List . tl in if List . mem " - h " args then begin usage ( ) ; return ( ) ; end else begin verbose := List . mem " - v " args ; let args = List . filter ( fun x -> x <> " - v " ) args in let extract args key = let result = ref None in let args = List . fold_left ( fun ( acc , foundit ) x -> if foundit then ( result := Some x ; ( acc , false ) ) else if x = key then ( acc , true ) else ( x :: acc , false ) ) ( [ ] , false ) args |> fst |> List . rev in ! result , args in let path , args = extract args " - path " in begin match path with | Some path -> Xs_transport . xenstored_socket := path | None -> ( ) end ; let restrict_domid , args = extract args " - restrict " in let do_restrict xs = match restrict_domid with | Some domid -> restrict xs ( int_of_string domid ) | None -> return ( ) in match args with | [ " read " ; key ] -> make ( ) >>= fun client -> immediate client ( fun xs -> do_restrict xs >>= fun ( ) -> read xs key >>= fun v -> Lwt_io . write Lwt_io . stdout v ) | [ " directory " ; key ] -> make ( ) >>= fun client -> immediate client ( fun xs -> do_restrict xs >>= fun ( ) -> directory xs key >>= fun ls -> Lwt_list . iter_s ( fun x -> Lwt_io . write Lwt_io . stdout ( x ^ " \ n " ) ) ls ) | " write " :: expr -> begin Lwt . catch ( fun ( ) -> let expr = String . concat " " expr |> parse_expr in if ! verbose then Printf . printf " Parsed : % s \ n " %! ( pretty_print ( ) expr ) ; expr |> to_conjunction |> return ) ( function | Invalid_expression as e -> Lwt_io . write Lwt_io . stderr " Invalid expression ; expected < key = val > [ and key = val ] *\ n " >>= fun ( ) -> Lwt . fail e | e -> Lwt . fail e ) >>= fun items -> make ( ) >>= fun client -> immediate client ( fun xs -> do_restrict xs >>= fun ( ) -> Lwt_list . iter_s ( fun ( k , v ) -> write xs k v ) items ) end | " debug " :: cmd_args -> make ( ) >>= fun client -> immediate client ( fun xs -> do_restrict xs >>= fun ( ) -> debug xs cmd_args >>= fun results -> Lwt_list . iter_s ( fun x -> Lwt_io . write Lwt_io . stdout ( x ^ " \ n " ) ) results ) | " wait " :: expr -> Lwt . catch ( fun ( ) -> let expr = String . concat " " expr |> parse_expr in if ! verbose then Printf . printf " Parsed : % s \ n " %! ( pretty_print ( ) expr ) ; make ( ) >>= fun client -> let result = wait client ( fun xs -> do_restrict xs >>= fun ( ) -> eval_expression expr xs >>= fun result -> if not result then fail Eagain else return ( ) ) in Lwt_timeout . create 5 ( fun ( ) -> cancel result ) |> Lwt_timeout . start ; result ) ( function | Invalid_expression as e -> Lwt_io . write Lwt_io . stderr " Invalid expression \ n " >>= fun ( ) -> Lwt . fail e | e -> Lwt . fail e ) | _ -> usage ( ) ; return ( ) end
let _ = Lwt_main . run ( main ( ) )
module type IO = sig type ' a t = ' a Lwt . t val return : ' a -> ' a t val ( >>= ) : ' a t -> ( ' a -> ' b t ) -> ' b t type backend = [ ` xen | ` unix ] val backend : backend type channel val create : unit -> channel t val destroy : channel -> unit t val read : channel -> string -> int -> int -> int t val write : channel -> string -> int -> int -> unit t end
module type S = sig type client val make : unit -> client Lwt . t val suspend : client -> unit Lwt . t val resume : client -> unit Lwt . t type handle val immediate : client -> ( handle -> ' a Lwt . t ) -> ' a Lwt . t val transaction : client -> ( handle -> ' a Lwt . t ) -> ' a Lwt . t val wait : client -> ( handle -> ' a Lwt . t ) -> ' a Lwt . t val directory : handle -> string -> string list Lwt . t val read : handle -> string -> string Lwt . t val write : handle -> string -> string -> unit Lwt . t val rm : handle -> string -> unit Lwt . t val mkdir : handle -> string -> unit Lwt . t val setperms : handle -> string -> Xs_protocol . ACL . t -> unit Lwt . t val debug : handle -> string list -> string list Lwt . t val restrict : handle -> int -> unit Lwt . t val getdomainpath : handle -> int -> string Lwt . t val watch : handle -> string -> Xs_protocol . Token . t -> unit Lwt . t val unwatch : handle -> string -> Xs_protocol . Token . t -> unit Lwt . t val introduce : handle -> int -> nativeint -> int -> unit Lwt . t val set_target : handle -> int -> int -> unit Lwt . t end
let ( |> ) a b = b a
let ( ++ ) f g x = f ( g x )
module Watcher = struct type t = { mutable paths : StringSet . t ; mutable cancelling : bool ; c : unit Lwt_condition . t ; m : Lwt_mutex . t ; } let make ( ) = { paths = StringSet . empty ; cancelling = false ; c = Lwt_condition . create ( ) ; m = Lwt_mutex . create ( ) ; } let put ( x : t ) path = Lwt_mutex . with_lock x . m ( fun ( ) -> ) let get ( x : t ) = Lwt_mutex . with_lock x . m ( fun ( ) -> while_lwt x . paths = StringSet . empty && not x . cancelling do Lwt_condition . wait ~ mutex : x . m x . c done >> let results = x . paths in x . paths <- StringSet . empty ; ) let cancel ( x : t ) = let ( _ : unit Lwt . t ) = Lwt_mutex . with_lock x . m ( ) end
module Client = functor ( IO : IO with type ' a t = ' a Lwt . t ) -> struct module PS = PacketStream ( IO ) type client = { mutable transport : IO . channel ; ps : PS . stream ; rid_to_wakeup : ( int32 , Xs_protocol . t Lwt . u ) Hashtbl . t ; mutable dispatcher_thread : unit Lwt . t ; mutable dispatcher_shutting_down : bool ; watchevents : ( Token . t , Watcher . t ) Hashtbl . t ; mutable suspended : bool ; suspended_m : Lwt_mutex . t ; suspended_c : unit Lwt_condition . t ; } let client_cache = ref None let client_cache_m = Lwt_mutex . create ( ) let recv_one t = match_lwt ( PS . recv t . ps ) with | Ok x -> return x | Exception e -> raise_lwt e let send_one t = PS . send t . ps let handle_exn t e = Printf . fprintf stderr " Caught : % s \ n " %! ( Printexc . to_string e ) ; lwt ( ) = begin match e with | Xs_protocol . Response_parser_failed x -> return ( ) | _ -> return ( ) end in t . dispatcher_shutting_down <- true ; lwt ( ) = Lwt_mutex . with_lock t . suspended_m ( fun ( ) -> Printf . fprintf stderr " Propagating exception to % d threads \ n " %! ( Hashtbl . length t . rid_to_wakeup ) ; Hashtbl . iter ( fun _ u -> Lwt . wakeup_later_exn u e ) t . rid_to_wakeup ; return ( ) ) in raise_lwt e let rec dispatcher t = lwt pkt = try_lwt recv_one t with e -> handle_exn t e in match get_ty pkt with | Op . Watchevent -> lwt ( ) = begin match Unmarshal . list pkt with | Some [ path ; token ] -> let token = Token . of_string token in if Hashtbl . mem t . watchevents token then Watcher . put ( Hashtbl . find t . watchevents token ) path >> dispatcher t else dispatcher t | _ -> handle_exn t Malformed_watch_event end in dispatcher t | _ -> let rid = get_rid pkt in lwt thread = Lwt_mutex . with_lock t . suspended_m ( fun ( ) -> if Hashtbl . mem t . rid_to_wakeup rid then return ( Some ( Hashtbl . find t . rid_to_wakeup rid ) ) else return None ) in match thread with | None -> handle_exn t ( Unexpected_rid rid ) | Some thread -> begin Lwt . wakeup_later thread pkt ; dispatcher t end let make_unsafe ( ) = lwt transport = IO . create ( ) in let t = { transport = transport ; ps = PS . make transport ; rid_to_wakeup = Hashtbl . create 10 ; dispatcher_thread = return ( ) ; dispatcher_shutting_down = false ; watchevents = Hashtbl . create 10 ; suspended = false ; suspended_m = Lwt_mutex . create ( ) ; suspended_c = Lwt_condition . create ( ) ; } in t . dispatcher_thread <- dispatcher t ; return t let make ( ) = match IO . backend with | ` unix -> make_unsafe ( ) | ` xen -> Lwt_mutex . with_lock client_cache_m ( fun ( ) -> match ! client_cache with | Some c -> return c | None -> lwt c = make_unsafe ( ) in client_cache := Some c ; return c ) let suspend t = lwt ( ) = Lwt_mutex . with_lock t . suspended_m ( fun ( ) -> t . suspended <- true ; while_lwt ( Hashtbl . length t . rid_to_wakeup > 0 ) do Lwt_condition . wait ~ mutex : t . suspended_m t . suspended_c done ) in Hashtbl . iter ( fun _ watcher -> Watcher . cancel watcher ) t . watchevents ; Lwt . cancel t . dispatcher_thread ; return ( ) let resume_unsafe t = lwt ( ) = Lwt_mutex . with_lock t . suspended_m ( fun ( ) -> t . suspended <- false ; t . dispatcher_shutting_down <- false ; Lwt_condition . broadcast t . suspended_c ( ) ; return ( ) ) in t . dispatcher_thread <- dispatcher t ; return ( ) let resume t = match IO . backend with | ` unix -> resume_unsafe t | ` xen -> ( match ! client_cache with | None -> Lwt . return ( ) | Some c -> IO . create ( ) >>= fun transport -> c . transport <- transport ; resume_unsafe t ) type handle = client Xs_handle . t let make_rid = let rpc hint h payload unmarshal = let open Xs_handle in let rid = make_rid ( ) in let request = Request . print payload ( get_tid h ) rid in let t , u = wait ( ) in let c = get_client h in if c . dispatcher_shutting_down then raise_lwt Dispatcher_failed else begin lwt ( ) = Lwt_mutex . with_lock c . suspended_m ( fun ( ) -> lwt ( ) = while_lwt c . suspended do Lwt_condition . wait ~ mutex : c . suspended_m c . suspended_c done in Hashtbl . add c . rid_to_wakeup rid u ; lwt ( ) = send_one c request in return ( ) ) in lwt res = t in lwt ( ) = Lwt_mutex . with_lock c . suspended_m ( fun ( ) -> Hashtbl . remove c . rid_to_wakeup rid ; Lwt_condition . broadcast c . suspended_c ( ) ; return ( ) ) in try_lwt return ( response hint request res unmarshal ) end let directory h path = rpc " directory " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Directory ) ) Unmarshal . list let read h path = rpc " read " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Read ) ) Unmarshal . string let write h path data = rpc " write " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Write data ) ) Unmarshal . ok let rm h path = rpc " rm " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Rm ) ) Unmarshal . ok let mkdir h path = rpc " mkdir " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Mkdir ) ) Unmarshal . ok let setperms h path acl = rpc " setperms " ( Xs_handle . accessed_path h path ) Request . ( PathOp ( path , Setperms acl ) ) Unmarshal . ok let debug h cmd_args = rpc " debug " h ( Request . Debug cmd_args ) Unmarshal . list let restrict h domid = rpc " restrict " h ( Request . Restrict domid ) Unmarshal . ok let getdomainpath h domid = rpc " getdomainpath " h ( Request . Getdomainpath domid ) Unmarshal . string let watch h path token = rpc " watch " ( Xs_handle . watch h path ) ( Request . Watch ( path , Token . to_string token ) ) Unmarshal . ok let unwatch h path token = rpc " unwatch " ( Xs_handle . watch h path ) ( Request . Unwatch ( path , Token . to_string token ) ) Unmarshal . ok let introduce h domid store_mfn store_port = rpc " introduce " h ( Request . Introduce ( domid , store_mfn , store_port ) ) Unmarshal . ok let set_target h stubdom_domid domid = rpc " set_target " h ( Request . Set_target ( stubdom_domid , domid ) ) Unmarshal . ok let immediate client f = f ( Xs_handle . no_transaction client ) let counter = ref 0l let wait client f = let open StringSet in counter := Int32 . succ ! counter ; let token = Token . of_string ( Printf . sprintf " % ld : xs_client . wait " ! counter ) in let watcher = Watcher . make ( ) in Hashtbl . add client . watchevents token watcher ; let result , wakener = Lwt . task ( ) in on_cancel result ( fun ( ) -> ) ; let h = Xs_handle . watching client in let adjust_paths ( ) = let current_paths = Xs_handle . get_watched_paths h in let old_paths = diff current_paths ( Xs_handle . get_accessed_paths h ) in lwt ( ) = Lwt_list . iter_s ( fun p -> unwatch h p token ) ( elements old_paths ) in let new_paths = diff ( Xs_handle . get_accessed_paths h ) current_paths in lwt ( ) = Lwt_list . iter_s ( fun p -> watch h p token ) ( elements new_paths ) in if old_paths = empty && ( new_paths = empty ) then begin lwt results = Watcher . get watcher in if results = empty then fail ( Failure " goodnight " ) else return ( ) end else return ( ) in let rec loop ( ) = lwt finished = try_lwt lwt result = f h in wakeup wakener result ; return true with Eagain -> return false in if finished then return ( ) else adjust_paths ( ) >> loop ( ) in let ( _ : unit Lwt . t ) = try_lwt loop ( ) finally let current_paths = Xs_handle . get_watched_paths h in lwt ( ) = Lwt_list . iter_s ( fun p -> unwatch h p token ) ( elements current_paths ) in Hashtbl . remove client . watchevents token ; return ( ) in result let rec transaction client f = lwt tid = rpc " transaction_start " ( Xs_handle . no_transaction client ) Request . Transaction_start Unmarshal . int32 in let h = Xs_handle . transaction client tid in lwt result = f h in try_lwt lwt res ' = rpc " transaction_end " h ( Request . Transaction_end true ) Unmarshal . string in if res ' = " OK " then return result else raise_lwt ( Error ( Printf . sprintf " Unexpected transaction result : % s " res ' ) ) with Eagain -> transaction client f end
let finally f g = try let result = f ( ) in g ( ) ; result with e -> g ( ) ; raise e
let with_mutex m f = Mutex . lock m ; finally f ( fun ( ) -> Mutex . unlock m )