text
stringlengths
12
786k
let parse_error code err = let errors = [ ] @ Errors_internal . common in match Errors_internal . of_string err with | Some var -> if ( List . mem var errors ) && ( ( match Errors_internal . to_http_code var with | Some var -> var = code | None -> true ) ) then Some var else None | None -> None
let int_of_uchar u = UChar . uint_code u
let uchar_of_int n = UChar . chr_of_uint n
let sprint_uchar u = let n = UChar . uint_code u in let n2 = n land 0xffff in let n1 = n lsr 16 in if n1 = 0 then Printf . sprintf " \\ u % 04X " n2 else Printf . sprintf " \\ U % 04X % 04X " n1 n2
let escaped_uchar u = let n = int_of_uchar u in if n > 0x7f || n < 0 then sprint_uchar u else Char . escaped ( Char . chr n ) n
let backslash = Char . code ' \\ '
let escaped_utf8 s = let buf = Buffer . create 0 in let proc u = let n = int_of_uchar u in if n > 0x7f || n < 0 then Buffer . add_string buf ( sprint_uchar u ) u else Buffer . add_string buf ( String . escaped ( String . make 1 ( Char . chr n ) n ) n ) n in UTF8 . iter proc s ; Buffer . contents buf
let printer_utf8 f s = let b = UTF8 . Buf . create 0 in UTF8 . iter ( fun u -> if UChar . uint_code u = 92 then UTF8 . Buf . add_string b " " \\\\ else if UChar . uint_code u < 0x80 then UTF8 . Buf . add_char b u else let s = sprint_uchar u in UTF8 . Buf . add_string b s ) s s ; let s = UTF8 . Buf . contents b in Format . fprintf f " " \% s " " \ s
let printer_uchar f u = Format . fprintf f " ' % s ' " ( if UChar . uint_code u = backslash then " " \\\\ else if UChar . uint_code u < 0x80 then UTF8 . init 1 ( fun _ -> u ) u else sprint_uchar u ) u
let src = Logs . Src . create " websocket . upgrade_connection "
let lwt_reporter ( ) = let buf_fmt ~ like = let b = Buffer . create 512 in ( Fmt . with_buffer ~ like b , fun ( ) -> let m = Buffer . contents b in Buffer . reset b ; m ) in let app , app_flush = buf_fmt ~ like : Fmt . stdout in let dst , dst_flush = buf_fmt ~ like : Fmt . stderr in let reporter = Logs_fmt . reporter ~ app ~ dst ( ) in let report src level ~ over k msgf = let k ( ) = let write ( ) = match level with | Logs . App -> Lwt_io . write Lwt_io . stdout ( app_flush ( ) ) | _ -> Lwt_io . write Lwt_io . stderr ( dst_flush ( ) ) in let unblock ( ) = over ( ) ; Lwt . return_unit in Lwt . finalize write unblock |> Lwt . ignore_result ; k ( ) in reporter . Logs . report src level ~ over ( : fun ( ) -> ( ) ) k msgf in { Logs . report }
let handler ( _ , conn ) req body = let open Frame in Logs_lwt . app ~ src ( fun m -> m " [ CONN ] % a " Sexplib . Sexp . pp ( Cohttp . Connection . sexp_of_t conn ) ) >>= fun _ -> let uri = Cohttp . Request . uri req in match Uri . path uri with | " " / -> Logs_lwt . app ~ src ( fun m -> m " [ PATH ] " ) / >>= fun ( ) -> Cohttp_lwt_unix . Server . respond_string ~ status ` : OK ~ body : { | < html > < head > < meta charset " = utf - 8 " > < script src " =// code . jquery . com / jquery - 1 . 11 . 3 . min . js " ></ script > < script > ( $ window ) . on ( ' load ' , function ( ) { ws = new WebSocket ( ' ws :// localhost : 7777 / ws ' ) ; ws . onmessage = function ( x ) { console . log ( x . data ) ; var m = " <- Pong " + parseInt ( ( x . data . substring ( 8 ) ) - 1 ) ; ( ' $# msg ' ) . html ( " < p " > + x . data + " </ p >< p " > + m + " </ p " ) ; > ws . send ( m ) ; } ; } ) ; </ script > </ head > < body > < div id ' = msg ' ></ div > </ body > </ html > } | ( ) >|= fun resp -> ` Response resp | " / ws " -> Logs_lwt . app ~ src ( fun m -> m " [ PATH ] / ws " ) >>= fun ( ) -> Cohttp_lwt . Body . drain_body body >>= fun ( ) -> Websocket_cohttp_lwt . upgrade_connection req ( fun { opcode ; content ; _ } -> match opcode with | Opcode . Close -> Logs . app ~ src ( fun m -> m " [ RECV ] CLOSE " ) | _ -> Logs . app ~ src ( fun m -> m " [ RECV ] % s " content ) ) >>= fun ( resp , frames_out_fn ) -> let num_ref = ref 10 in let rec go ( ) = if ! num_ref = 0 then Logs_lwt . app ~ src ( fun m -> m " [ INFO ] Test done " ) else let msg = Printf . sprintf " -> Ping % d " ! num_ref in Logs_lwt . app ~ src ( fun m -> m " [ SEND ] % s " msg ) >>= fun ( ) -> Lwt . wrap1 frames_out_fn @@ Some ( Frame . create ~ content : msg ( ) ) >>= fun ( ) -> decr num_ref ; Lwt_unix . sleep 1 . >>= go in Lwt . async go ; Lwt . return resp | _ -> Logs_lwt . app ~ src ( fun m -> m " [ PATH ] Catch - all " ) >>= fun ( ) -> Cohttp_lwt_unix . Server . respond_string ~ status ` : Not_found ~ body ( : Sexplib . Sexp . to_string_hum ( Cohttp . Request . sexp_of_t req ) ) ( ) >|= fun resp -> ` Response resp
let start_server ? tls port = let conn_closed ( _ , c ) = Logs . app ~ src ( fun m -> m " [ SERV ] connection % a closed " Sexplib . Sexp . pp ( Cohttp . Connection . sexp_of_t c ) ) in Logs_lwt . app ~ src ( fun m -> m " [ SERV ] Listening for HTTP on port % d " port ) >>= fun ( ) -> let mode = match tls with | None -> Logs . app ~ src ( fun m -> m " TCP mode selected " ) ; ` TCP ( ` Port port ) | Some ( cert , key ) -> Logs . app ~ src ( fun m -> m " TLS mode selected " ) ; ` TLS ( ` Crt_file_path cert , ` Key_file_path key , ` No_password , ` Port port ) in Cohttp_lwt_unix . Server . create ~ mode ( Cohttp_lwt_unix . Server . make_response_action ~ callback : handler ~ conn_closed ( ) )
let ( ) = Logs . ( set_reporter ( lwt_reporter ( ) ) ) ; let port = ref 7777 in let cert = ref " " in let key = ref " " in let speclist = Arg . align [ ( " - cert " , Arg . Set_string cert , " cert file " ) ; ( " - key " , Arg . Set_string key , " key file " ) ; ( " - v " , Arg . Unit ( fun ( ) -> Logs . set_level ( Some Info ) ) , " Set loglevel to info " ) ; ( " - vv " , Arg . Unit ( fun ( ) -> Logs . set_level ( Some Debug ) ) , " Set loglevel to debug " ) ] in let anon_fun s = match int_of_string_opt s with | None -> invalid_arg " argument must be a port number " | Some p -> port := p in let usage_msg = " Usage : " ^ Sys . argv . ( 0 ) ^ " < options > port \ nOptions are " : in Arg . parse speclist anon_fun usage_msg ; let tls = match ( ! cert , ! key ) with | " " , _ | _ , " " -> None | cert , key -> Some ( cert , key ) in Lwt_main . run ( start_server ? tls ! port )
let old_data = { Format_v1 . a = Some 1 ; b = true ; c = Some 3 ; d = 4 . 0 ; }
let print_old_data ( ) = let ob = Bi_outbuf . create_channel_writer stdout in Format_v1 . write_t ob old_data ; Bi_outbuf . flush_channel_writer ob ; flush stdout
let convert x = Format_v2 . t_of_string ( Format_v1 . string_of_t ~ len : 100 x )
let print_new_data ( ) = let new_data = convert old_data in let ob = Bi_outbuf . create_channel_writer stdout in Format_v2 . write_t ob new_data ; Bi_outbuf . flush_channel_writer ob ; flush stdout
let upgrade ( ) = let ib = Bi_inbuf . from_channel stdin in let x = Format_v2 . read_t ib in let ob = Bi_outbuf . create_channel_writer stdout in Format_v2 . write_t ob x ; Bi_outbuf . flush_channel_writer ob ; flush stdout
let usage ( ) = eprintf " \ " %! Sys . argv . ( 0 ) ; exit 1
let main ( ) = match Sys . argv with [ | _ ; action ] | -> ( match action with " old " -> print_old_data ( ) | " new " -> print_new_data ( ) | " up " -> upgrade ( ) | _ -> usage ( ) ) | _ -> usage ( )
let ( ) = main ( )
let src = Logs . Src . create " uplink " ~ doc " : Network connection to NetVM "
module Log = ( val Logs . src_log src : Logs . LOG )
module Make ( R : Mirage_random . S ) ( Clock : Mirage_clock . MCLOCK ) = struct module Arp = Arp . Make ( Eth ) ( OS . Time ) module I = Static_ipv4 . Make ( R ) ( Clock ) ( Eth ) ( Arp ) module U = Udp . Make ( I ) ( R ) type t = { net : Netif . t ; eth : Eth . t ; arp : Arp . t ; interface : interface ; mutable fragments : Fragments . Cache . t ; ip : I . t ; udp : U . t ; } val queue = FrameQ . create ( Ipaddr . V4 . to_string other_ip ) method my_mac = Eth . mac eth method my_ip = my_ip method other_ip = other_ip method writev ethertype fillfn = FrameQ . send queue ( fun ( ) -> mac >>= fun dst -> Eth . write eth dst ethertype fillfn >|= or_raise " Write to uplink " Eth . pp_error ) end let send_dns_client_query t ~ src_port ~ dst ~ dst_port buf = U . write ~ src_port ~ dst ~ dst_port t . udp buf >|= function | Error s -> Log . err ( fun f -> f " error sending udp packet : % a " U . pp_error s ) ; Error ( ` Msg " failure " ) | Ok ( ) -> Ok ( ) let listen t get_ts dns_responses router = let handle_packet ip_header ip_packet = let open Udp_packet in Log . debug ( fun f -> f " received ipv4 packet from % a on uplink " Ipaddr . V4 . pp ip_header . Ipv4_packet . src ) ; match ip_packet with | ` UDP ( header , packet ) when Ports . mem header . dst_port ( ! router . Router . ports . My_nat . dns_udp ) -> Log . debug ( fun f -> f " found a DNS packet whose dst_port ( % d ) was in the list of dns_client ports " header . dst_port ) ; Lwt_mvar . put dns_responses ( header , packet ) | _ -> Firewall . ipv4_from_netvm router ( ` IPv4 ( ip_header , ip_packet ) ) in Netif . listen t . net ~ header_size : Ethernet . Packet . sizeof_ethernet ( fun frame -> Eth . input t . eth ~ arpv4 ( : Arp . input t . arp ) ~ ipv4 ( : fun ip -> let cache , r = Nat_packet . of_ipv4_packet t . fragments ~ now ( : get_ts ( ) ) ip in t . fragments <- cache ; match r with | Error e -> Log . warn ( fun f -> f " Ignored unknown IPv4 message from uplink : % a " Nat_packet . pp_error e ) ; Lwt . return ( ) | Ok None -> Lwt . return_unit | Ok ( Some ( ` IPv4 ( header , packet ) ) ) -> handle_packet header packet ) ~ ipv6 ( : fun _ip -> Lwt . return_unit ) frame ) >|= or_raise " Uplink listen loop " Netif . pp_error
let interface t = t . interface
let connect config = let my_ip = config . Dao . uplink_our_ip in let gateway = config . Dao . uplink_netvm_ip in Netif . connect " 0 " >>= fun net -> Eth . connect net >>= fun eth -> Arp . connect eth >>= fun arp -> Arp . add_ip arp my_ip >>= fun ( ) -> let cidr = Ipaddr . V4 . Prefix . make 0 my_ip in I . connect ~ cidr ~ gateway eth arp >>= fun ip -> U . connect ip >>= fun udp -> let netvm_mac = Arp . query arp gateway >|= or_raise " Getting MAC of our NetVM " Arp . pp_error in let interface = new netvm_iface eth netvm_mac ~ my_ip ~ other_ip : config . Dao . uplink_netvm_ip in let fragments = Fragments . Cache . empty ( 256 * 1024 ) in Lwt . return { net ; eth ; arp ; interface ; fragments ; ip ; udp } end
type ' a t = | Begin of ( [ ` Begin ] , ' a ODBUpload . t ) Task . t | Edit of ' a ODBUpload . t * LogBox . t | Commit of ' a ODBUpload . t * ( [ ` Commit ] , ODBPkgVer . t ) Task . t | Cancel of ( [ ` Cancel ] , unit ) Task . t
let upload_data = create_volatile_table ( )
let upload_data_set ~ sp id t = let hsh = match get_volatile_session_data ~ table : upload_data ~ sp ( ) with | Data hsh -> hsh | Data_session_expired | No_data -> let hsh = Hashtbl . create 2 in set_volatile_session_data ~ table : upload_data ~ sp hsh ; hsh in Hashtbl . replace hsh id t
let upload_data_unset ~ sp id = match get_volatile_session_data ~ table : upload_data ~ sp ( ) with | Data hsh -> Hashtbl . remove hsh id | Data_session_expired | No_data -> ( )
let upload_data_get ~ sp id = match get_volatile_session_data ~ table : upload_data ~ sp ( ) with | Data hsh -> Hashtbl . find hsh id | Data_session_expired | No_data -> raise Not_found
let upload_template ~ ctxt ~ sp ? extra_headers ctnt = template ~ ctxt ~ sp ~ title ( : OneTitle ( s_ " Upload " ) ) ~ div_id " : upload " ? extra_headers ctnt
let upload_completion_box ~ ctxt ~ sp id upload = let service = Eliom_predefmod . Action . register_new_post_coservice_for_session ' ~ sp ~ name " : upload_completion_action " ~ post_params ( : opt ( string " publink " ) ** string " package " ** ExtParams . version " version " ** int " order " ** int " id " ) ~ keep_get_na_params : false ( fun sp _ ( publink , ( pkg , ( version , ( ord , id ) ) ) ) -> Context . get_user ~ sp ( ) >>= fun ( ctxt , _ ) -> begin match upload_data_get ~ sp id with | Edit ( upload , log ) -> begin let upload = { upload with publink = publink ; completion = { upload . completion with ct_pkg = Sure pkg ; ct_ver = Sure version ; ct_ord = Sure ord } } in upload_data_set ~ sp id ( Edit ( upload , log ) ) ; return ( ) end | Begin _ | Commit _ | Cancel _ -> fail StateTransitionNotAllowed end ) in let has_oasis = upload . completion . ct_oasis <> None in let form = post_form ~ service ~ sp ( fun ( publink_nm , ( pkg_nm , ( ver_nm , ( ord_nm , id_nm ) ) ) ) -> [ p [ pcdata ( s_ " Tarball : " ) ; pcdata upload . tarball_nm ; br ( ) ; pcdata ( s_ " Public link : " ) ; string_input ~ input_type ` : Text ~ name : publink_nm ~ value ( : match upload . publink with | Some lnk -> lnk | None -> " " ) ( ) ; br ( ) ; pcdata ( s_ " Package : " ) ; begin let value = match upload . completion . ct_pkg with | Sure v | Unsure ( _ , v ) -> v | NotFound -> " " in if has_oasis then span [ pcdata value ; pcdata ( s_ " ( from _oasis ) " ) ; string_input ~ input_type ` : Hidden ~ name : pkg_nm ~ value ( ) ] else string_input ~ input_type ` : Text ~ name : pkg_nm ~ value ( ) end ; br ( ) ; pcdata ( s_ " Version : " ) ; begin let value = match upload . completion . ct_ver with | Sure v | Unsure ( _ , v ) -> v | NotFound -> OASISVersion . version_of_string " " in if has_oasis then span [ pcdata ( OASISVersion . string_of_version value ) ; pcdata ( s_ " ( from _oasis ) " ) ; user_type_input ~ input_type ` : Hidden ~ name : ver_nm ~ value OASISVersion . string_of_version ( ) ] else user_type_input ~ input_type ` : Text ~ name : ver_nm ~ value OASISVersion . string_of_version ( ) end ; br ( ) ; pcdata ( s_ " Order : " ) ; int_input ~ input_type ` : Text ~ name : ord_nm ~ value ( : match upload . completion . ct_ord with | Sure v | Unsure ( _ , v ) -> v | NotFound -> 0 ) ( ) ; br ( ) ; int_input ~ input_type ` : Hidden ~ name : id_nm ~ value : id ( ) ; raw_input ~ input_type ` : Reset ~ value ( : s_ " Reset " ) ( ) ; string_input ~ input_type ` : Submit ~ value ( : s_ " Save " ) ( ) ; ] ] ) ( ) in return ( box_check ( ODBPkgVer . check ( pkg_ver_of_upload upload ) ) form )
let upload_preview_box ~ ctxt ~ sp id upload = catch ( fun ( ) -> upload_phantom_storage ~ ctxt : ctxt . odb upload >>= fun ( pkg_ver , stor ) -> ODBStorage . PkgVer . oasis stor ( ` PkgVer pkg_ver ) >>= fun oasis_opt -> begin let ctxt = { ( Context . anonymize ctxt ) with stor = stor } in PkgVerViewCommon . preview_box ~ ctxt ~ sp pkg_ver ( fun ( ) -> return ( XHTML . M . a ~ a [ : a_href ( uri_of_string " http :// NOT_UPLOADED " ) ] [ pcdata upload . tarball_nm ; pcdata ( s_ " ( backup ) " ) ] , upload . tarball_nm ) ) oasis_opt >|= fun ctnt -> true , ctnt end ) ( fun e -> return ( false , [ html_error [ pcdata ( Printf . sprintf ( f_ " Unable to create the package : % s " ) ( Printexc . to_string e ) ) ] ] ) ) >|= fun ( is_ok , content ) -> is_ok , ( ( h3 [ pcdata ( s_ " Preview " ) ] ) :: content )
let upload_confirm_action = Eliom_predefmod . Action . register_new_post_coservice ' ~ name " : upload_confirm_action " ~ post_params ( : string " action " ** int " id " ) ~ keep_get_na_params : false ( fun sp id ( action , id ) -> Context . get_user ~ sp ( ) >>= fun ( ctxt , _ ) -> begin match upload_data_get ~ sp id with | Edit ( upload , _ ) -> begin try let state = match action with | " cancel " -> Cancel ( Task . create ~ ctxt ( fun ctxt -> upload_rollback ~ ctxt : ctxt . odb upload ) ) | " confirm " -> Commit ( upload , Task . create ~ ctxt ( fun ctxt -> upload_commit ~ ctxt : ctxt . odb upload ) ) | str -> failwith ( Printf . sprintf ( f_ " Unknow action ' % s ' " ) str ) in upload_data_set ~ sp id state ; return ( ) with e -> fail e end | Begin _ | Commit _ | Cancel _ -> fail StateTransitionNotAllowed end )
let upload_confirm_box ~ ctxt ~ sp id is_ok upload = return ( post_form ~ service : upload_confirm_action ~ sp ( fun ( action , id ' ) -> [ p [ int_input ~ input_type ` : Hidden ~ name : id ' ~ value : id ( ) ; string_button ~ name : action ~ value " : cancel " [ pcdata ( s_ " Cancel upload " ) ] ; string_button ~ a ( : if is_ok then [ ] else [ a_disabled ` Disabled ] ) ~ name : action ~ value " : confirm " [ pcdata ( s_ " Confirm upload " ) ] ; ] ] ) ( ) )
let upload_edit_box ~ ctxt ~ sp id upload log = upload_preview_box ~ ctxt ~ sp id upload >>= fun ( is_ok_preview , preview_box ) -> upload_completion_box ~ ctxt ~ sp id upload >>= fun ( is_ok_completion , completion_box ) -> upload_confirm_box ~ ctxt ~ sp id ( is_ok_preview && is_ok_completion ) upload >>= fun action_box -> LogBox . log_box ~ ctxt ~ sp log >>= fun log_box -> begin return ( [ log_box ] @ [ h3 [ pcdata " Results " ] ; completion_box ; ] @ preview_box @ [ action_box ; js_script ~ uri ( : make_uri ~ service ( : static_dir sp ) ~ sp [ " form - disabler . js " ] ) ( ) ; ] ) end
let upload_init_check tarball_fd publink_opt = try let publink_opt = match publink_opt with | Some s -> begin match ExtString . String . strip s with | " " -> None | s -> Some s end | None -> None in let tarball_nm = match get_original_filename tarball_fd with | " none " -> failwith ( s_ " No tarball uploaded , be sure to choose a \ file to upload . " ) | fn -> FilePath . basename fn in LwtExt . IO . with_file_content ( get_tmp_filename tarball_fd ) >>= fun tarball_content -> return ( tarball_content , tarball_nm , publink_opt ) with e -> fail e
let upload_init_action = Eliom_predefmod . Action . register_new_post_coservice ' ~ name " : upload_tarball " ~ post_params ( : string " publink " ** file " tarball " ** int " id " ) ( fun sp _ ( publink , ( tarball_fd , id ) ) -> Context . get_user ~ sp ( ) >>= fun ( ctxt , accnt ) -> upload_init_check tarball_fd ( Some publink ) >>= fun ( tarball_content , tarball_nm , publink ) -> begin let tsk = Task . create ~ ctxt ( fun ctxt -> upload_begin ~ ctxt : ctxt . odb ctxt . stor ( Web accnt . OCAAccount . accnt_real_name ) tarball_content tarball_nm publink ) in upload_data_set ~ sp id ( Begin tsk ) ; return ( ) end )
let upload_init_box ~ ctxt ~ sp id = let upload_form = post_form ~ service : upload_init_action ~ sp ( fun ( publink , ( tarball , id_nm ) ) -> [ p [ pcdata ( s_ " Tarball : " ) ; file_input ~ a [ : a_accept " application / x - bzip2 ; \ application / zip ; \ application / x - gzip " ] ~ name : tarball ( ) ; br ( ) ; pcdata ( s_ " Public link : " ) ; string_input ~ input_type ` : Text ~ name : publink ~ value " " : ( ) ; br ( ) ; int_input ~ input_type ` : Hidden ~ name : id_nm ~ value : id ( ) ; string_input ~ input_type ` : Submit ~ value ( : s_ " Upload " ) ( ) ] ] ) ( ) in return [ upload_form ]
let upload_with_id = Eliom_predefmod . Any . register_new_service ~ path [ " : upload " ] ~ get_params ( : int " id " ) ( fun sp id ( ) -> Context . get_user ~ sp ( ) >>= fun ( ctxt , _ ) -> try match upload_data_get ~ sp id with | Begin task_upload -> begin Task . wait ~ ctxt task_upload ctxt . upload_delay ( s_ " The tarball is not yet processed . " ) >>= fun ( task , delay , upload ) -> begin let log = Task . get_logger task in let ( ) = upload_data_set ~ sp id ( Edit ( upload , log ) ) in upload_edit_box ~ ctxt ~ sp id upload log >>= fun edit_box -> upload_template ~ ctxt ~ sp ( ( p [ pcdata ( Printf . sprintf ( f_ " The tarball ' % s ' has been processed \ in . % 3fs , please check and complete \ the result . " ) upload . tarball_nm delay ) ] ) :: edit_box ) >>= fun page -> Eliom_predefmod . Xhtml . send ~ sp page end end | Edit ( upload , log ) -> begin upload_edit_box ~ ctxt ~ sp id upload log >>= fun edit_box -> upload_template ~ ctxt ~ sp edit_box >>= fun page -> Eliom_predefmod . Xhtml . send ~ sp page end | Commit ( upload , task_commit ) -> begin catch ( fun ( ) -> Task . wait ~ ctxt task_commit ctxt . upload_commit_delay ( s_ " Commit of upload not yet finished . " ) >>= fun ( task , delay , pkg_ver ) -> begin upload_data_unset ~ sp id ; Eliom_predefmod . Redirection . send ~ sp ( preapply view_pkg_ver ( pkg_ver . ODBPkgVer . pkg , Version pkg_ver . ODBPkgVer . ver ) ) end ) ( fun e -> let ctxt = Task . set_logger task_commit ctxt in ODBMessage . error ~ ctxt : ctxt . odb ( f_ " Unable to commit upload : % s " ) ( Printexc . to_string e ) >>= fun ( ) -> begin let log = Task . get_logger task_commit in let ( ) = upload_data_set ~ sp id ( Edit ( upload , log ) ) in upload_edit_box ~ ctxt ~ sp id upload log >>= fun edit_box -> upload_template ~ ctxt ~ sp edit_box >>= fun page -> Eliom_predefmod . Xhtml . send ~ sp page end ) end | Cancel task_cancel -> begin Task . wait ~ ctxt task_cancel ctxt . upload_cancel_delay ( s_ " Cancelation of upload not yet finished . " ) >>= fun ( task , delay , ( ) ) -> begin upload_data_unset ~ sp id ; Eliom_predefmod . Redirection . send ~ sp upload end end with Not_found -> begin upload_init_box ~ ctxt ~ sp id >>= fun init_box -> upload_template ~ ctxt ~ sp init_box >>= fun page -> Eliom_predefmod . Xhtml . send ~ sp page end )
let upload_id = ref 1
let upload_handler sp ( ) ( ) = incr upload_id ; return ( preapply upload_with_id ! upload_id )
type t = { stop_async_upload : bool ; upload_resource_by_id : int64 -> unit ; thread_pool : ThreadPool . t ; }
let stop_async_upload = { GapiLens . get = ( fun x -> x . stop_async_upload ) ; GapiLens . set = ( fun v x -> { x with stop_async_upload = v } ) ; }
let upload_resource_by_id = { GapiLens . get = ( fun x -> x . upload_resource_by_id ) ; GapiLens . set = ( fun v x -> { x with upload_resource_by_id = v } ) ; }
let thread_pool = { GapiLens . get = ( fun x -> x . thread_pool ) ; GapiLens . set = ( fun v x -> { x with thread_pool = v } ) ; }
module ConcurrentUploadQueue = ConcurrentGlobal . Make ( struct type u = t let label = " upload - queue " end )
let upload_resource cache = let d = ConcurrentUploadQueue . get ( ) in let upload = d . upload_resource_by_id in let upload_entry = Cache . UploadQueue . select_next_resource cache in let do_work e = let entry_id = e . CacheData . UploadEntry . id in let resource_id = e . CacheData . UploadEntry . resource_id in Utils . log_with_header " Uploading queued entry ( id =% Ld ) resource_id =% Ld . \ n " %! entry_id resource_id ; Cache . UploadQueue . update_entry_state cache CacheData . UploadEntry . State . Uploading entry_id ; ( try upload resource_id with e -> Utils . log_with_header " Upload failed for queued entry ( id =% Ld ) . \ n " %! entry_id ; Cache . UploadQueue . update_entry_state cache CacheData . UploadEntry . State . ToUpload entry_id ; raise e ) ; Utils . log_with_header " Removing queued entry ( id =% Ld ) . \ n " %! entry_id ; Cache . UploadQueue . delete_upload_entry cache e in match upload_entry with | Some e -> ThreadPool . add_work do_work e d . thread_pool | None -> ( )
let poll_upload_queue cache = let check ( ) = let d = ConcurrentUploadQueue . get ( ) in if d . stop_async_upload then ( let entries = Cache . UploadQueue . count_entries cache in Utils . log_with_header " Waiting for pending uploads ( % d ) \ n " %! entries ; if entries = 0 then raise Exit ) in try while true do check ( ) ; Thread . delay 1 . 0 ; upload_resource cache done with Exit -> let d = ConcurrentUploadQueue . get ( ) in Utils . log_with_header " Waiting for pending upload threads ( % d ) . . . " %! ( ThreadPool . pending_threads d . thread_pool ) ; ThreadPool . shutdown d . thread_pool ; Utils . log_message " done \ n " %!
let start_async_upload_thread cache upload_threads upload_resource = let data = { stop_async_upload = false ; upload_resource_by_id = upload_resource ; thread_pool = ThreadPool . create ~ max_threads : upload_threads ( ) ; } in ConcurrentUploadQueue . set data ; let thread = Thread . create poll_upload_queue cache in Utils . log_with_header " Starting async upload thread ( TID =% d ) \ n " %! ( Thread . id thread ) ; Context . update_ctx ( Context . async_upload_thread ^= Some thread )
let stop_async_upload_thread ( ) = ConcurrentUploadQueue . update ( fun q -> q |> stop_async_upload ^= true )
let queue_resource cache config resource = let resource_id = resource . CacheData . Resource . id in let wait_for_slot ( ) = let check ( ) = let max_length = config . Config . async_upload_queue_max_length in let entries = Cache . UploadQueue . count_entries cache in if entries >= max_length then Utils . log_with_header " Waiting for pending uploads ( % d ) to get below the limit ( % d ) \ n " %! entries max_length else ( Utils . log_with_header " Pending uploads ( % d ) below the limit ( % d ) \ n " %! entries max_length ; raise Exit ) in try while true do check ( ) ; Thread . delay 1 . 0 done with Exit -> ( ) in let queue_r ( ) = let upload_entry = { CacheData . UploadEntry . id = 0L ; resource_id ; state = CacheData . UploadEntry . State . ( to_string ToUpload ) ; last_update = Unix . gettimeofday ( ) ; } in let inserted_upload_entry = Cache . UploadQueue . insert_upload_entry cache upload_entry in Utils . log_with_header " END : Resource id =% Ld queued for uploading ( entry id =% Ld ) \ n " %! resource_id inserted_upload_entry . CacheData . UploadEntry . id in Utils . log_with_header " BEGIN : Queue resource id =% Ld for uploading \ n " %! resource_id ; let upload_entry_with_resource_id = Cache . UploadQueue . select_with_resource_id cache resource_id in match upload_entry_with_resource_id with | None -> if config . Config . async_upload_queue_max_length > 0 then wait_for_slot ( ) ; queue_r ( ) | Some e -> Utils . log_with_header " END : Resource with id =% Ld already queued ( entry id =% Ld ) \ n " %! resource_id e . CacheData . UploadEntry . id
let o = Oauth . get_oauth auth_file
let ( ) = Format . eprintf " % a . " @ ( Ocaml . format_with Api . People . GetUploadStatus . ocaml_of_user ) ( Poly_result . from_Ok & Job . run & People . getUploadStatus o )
let rev_dirs = ref [ ]
let remove_non_local = ref false
let upload_movie = ref false
let ( ) = Arg . parse [ " - remove - non - local " , Arg . Set remove_non_local , " remove photos not in local directory from photoset ( the photo still exists in the flickr ) " ; " - upload - movie " , Arg . Set upload_movie , " upload movies too " ] ( fun x -> rev_dirs := x :: ! rev_dirs ) " uploads dirs . . "
let dirs = List . rev ! rev_dirs
let ( ) = let dirs = flip List . filter dirs & fun dir -> let b = File . Test . _d dir in if not b then !!% " WARNING : % s is not a directory . Skipped . . " @ dir ; b in flip List . iter dirs & fun dir -> let photoset = Filename . basename dir in assert ( photoset <> " " ) ; let photos = let acc = ref [ ] in Unix . Find . find ~ follow_symlink : true [ dir ] ~ f ( : fun p -> if p # kind = Ok Unix . S_REG then acc +::= p # path ) ; ! acc in let targets = flip List . filter photos & fun s -> match Tools2 . uploadable_by_name s with | Some ` Image -> true | Some ` Movie when ! upload_movie -> true | Some ` Movie -> !!% " WARNING : % s is a movie and therefore skipped . " @ s ; false | _ -> !!% " WARNING : % s is not uploadable I think . Therefore ignored . " @ s ; false in if targets <> [ ] then begin match Job . run & Job . retry ( fun conseq_fails e -> match e with | ` Http ( ( 502 | 504 as n ) , _ ) -> !!% " Server side error ( % d ) : % a . " @ n Api2 . format_error e ; !!% " Failed . Wait 1 min then retry . . . . " ; @ Unix . sleep 60 ; ` Ok conseq_fails | _ -> if conseq_fails >= 3 then begin !!% " Failed 3 times ! Check your setting . " ; !@ ` Error e end else begin !!% " Error : % a . " @ Api2 . format_error e ; !!% " Failed . Wait 1 min then retry . . . . " ; @ Unix . sleep 60 ; ` Ok ( conseq_fails + 1 ) end ) 0 & Tools2 . uploads ~ remove_non_local :! remove_non_local ~ photoset ~ existing : photos targets o with | ` Ok ( ) -> ( ) | ` Error ( desc , _ ) -> Api2 . error desc end
let uri = ref " http :// 127 . 0 . 0 . 1 " /
let username = ref " root "
let password = ref " password "
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 main filename = Lwt_unix . LargeFile . stat filename >>= fun stats -> let virtual_size = stats . Lwt_unix . LargeFile . st_size in let rpc = make ! uri in Session . login_with_password ~ rpc ~ uname :! username ~ pwd :! password ~ version " : 1 . 0 " ~ originator " : upload_disk " >>= fun session_id -> Lwt . finalize ( fun ( ) -> Pool . get_all ~ rpc ~ session_id >>= fun pools -> let pool = List . hd pools in Pool . get_default_SR ~ rpc ~ session_id ~ self : pool >>= fun sr -> ( VDI . create ~ rpc ~ session_id ~ name_label " : upload_disk " ~ name_description " " : ~ sR : sr ~ virtual_size ~ _type ` : user ~ sharable : false ~ read_only : false ~ other_config [ ] : ~ xenstore_data [ ] : ~ sm_config [ ] : ~ tags [ ] ) : >>= fun vdi -> ( Lwt . catch ( fun ( ) -> let authentication = Disk . UserPassword ( ! username , ! password ) in let uri = Disk . uri ~ pool ( : Uri . of_string ! uri ) ~ authentication ~ vdi in Disk . start_upload ~ chunked : false ~ uri >>= fun oc -> let blocksize = 1024 * 1024 * 2 in let block = Cstruct . create blocksize in Lwt_unix . openfile filename [ Unix . O_RDONLY ] 0o0 >>= fun fd -> Data_channel . of_fd ~ seekable : true fd >>= fun ic -> let rec copy remaining = if remaining = 0L then return ( ) else let block = Cstruct . sub block 0 Int64 . ( to_int ( min ( of_int blocksize ) remaining ) ) in ic . Data_channel . really_read block >>= fun ( ) -> oc . Data_channel . really_write block >>= fun ( ) -> copy Int64 . ( sub remaining ( of_int ( Cstruct . len block ) ) ) in copy virtual_size >>= fun ( ) -> oc . Data_channel . close ( ) >>= fun ( ) -> ic . Data_channel . close ( ) ) ( fun e -> Printf . fprintf stderr " Caught : % s , cleaning up \ n " %! ( Printexc . to_string e ) ; VDI . destroy ~ rpc ~ session_id ~ self : vdi >>= fun ( ) -> fail e ) ) >>= fun ( ) -> VDI . get_uuid ~ rpc ~ session_id ~ self : vdi >>= fun uuid -> Printf . printf " % s \ n " uuid ; return ( ) ) ( fun ( ) -> Session . logout ~ rpc ~ session_id )
let _ = let filename = ref " " in Arg . parse [ " - uri " , Arg . Set_string uri , ( Printf . sprintf " URI of server to connect to ( default % s ) " ! uri ) ; " - u " , Arg . Set_string username , ( Printf . sprintf " Username to log in with ( default % s ) " ! username ) ; " - pw " , Arg . Set_string password , ( Printf . sprintf " Password to log in with ( default % s ) " ! password ) ; ] ( fun x -> match ! filename with | " " -> filename := x | _ -> Printf . fprintf stderr " Ignoring argument : % s \ n " x ) " Simple example which uploads a disk image " ; Lwt_main . run ( main ! filename )
let ask_github fn = Github . ( Monad . run ( fn ( ) ) )
let upload_release token user repo tag content_type filename = let open Github_t in ask_github ( Github . Release . get_by_tag_name ~ token ~ user ~ repo ~ tag ) >|= Github . Response . value >>= fun r -> let id = r . release_id in print_endline ( sprintf " uploading to release id % Ld " id ) ; begin Lwt_io . file_length filename >|= Int64 . to_int >>= fun len -> let buf = Bytes . create len in Lwt_io . with_file ~ mode : Lwt_io . input filename ( fun ic -> Lwt_io . read_into_exactly ic buf 0 len ) >>= fun ( ) -> return buf end >>= fun body -> let body = Bytes . to_string body in ask_github ( Github . Release . upload_asset ~ token ~ user ~ repo ~ id ~ filename ~ content_type ~ body ) >>= fun _a -> return_unit
let run token user repo tag content_type filename = Lwt_main . run ( upload_release token user repo tag content_type filename )
let cmd = let cookie = Jar_cli . cookie ( ) in let user = let doc = " The user name on GitHub " in Arg . ( required & pos 0 ( some string ) None & info [ ] ~ docv " : USER " ~ doc ) in let repo = let doc = " The repository name on GitHub " in Arg . ( required & pos 1 ( some string ) None & info [ ] ~ docv " : REPO " ~ doc ) in let tag = let doc = " The release tag name on GitHub " in Arg . ( required & pos 2 ( some string ) None & info [ ] ~ docv " : TAG " ~ doc ) in let filename = let doc = " The filename to upload " in Arg . ( required & pos 3 ( some string ) None & info [ ] ~ docv " : FILENAME " ~ doc ) in let content_type = let doc = " The MIME content - type of the file . Defaults to application / octet - stream , but something more specific is recommended . " in Arg . ( value & pos 4 string " application / octet - stream " & info [ ] ~ docv " : CONTENT_TYPE " ~ doc ) in let doc = " upload a release asset to a GitHub repository " in let man = [ ` S " BUGS " ; ` P " Email bug reports to < mirageos - devel @ lists . xenproject . org . " ; ] > in let term = Term . ( ( const run $ cookie $ user $ repo $ tag $ content_type $ filename ) ) in let info = Cmd . info " git - upload - release " ~ version : Jar_version . t ~ doc ~ man in Cmd . v info term
let ( ) = exit @@ Cmd . eval cmd
let daemon ( ) = let % lwt bus = OBus_bus . system ( ) in return ( OBus_peer . make bus " org . freedesktop . UPower " )
let proxy daemon = OBus_proxy . make daemon [ " org " ; " freedesktop " ; " UPower " ]
let enumerate_devices daemon = let % lwt ( context , devices ) = OBus_method . call_with_context m_EnumerateDevices ( proxy daemon ) ( ) in return ( List . map ( fun path -> UPower_device . of_proxy ( OBus_proxy . make ( OBus_context . sender context ) path ) ) devices )
let device_added daemon = OBus_signal . map_with_context ( fun context device -> UPower_device . of_proxy ( OBus_proxy . make ( OBus_context . sender context ) ( OBus_path . of_string device ) ) ) ( OBus_signal . make s_DeviceAdded ( proxy daemon ) )
let device_removed daemon = OBus_signal . map_with_context ( fun context device -> UPower_device . of_proxy ( OBus_proxy . make ( OBus_context . sender context ) ( OBus_path . of_string device ) ) ) ( OBus_signal . make s_DeviceRemoved ( proxy daemon ) )
let device_changed daemon = OBus_signal . map_with_context ( fun context device -> UPower_device . of_proxy ( OBus_proxy . make ( OBus_context . sender context ) ( OBus_path . of_string device ) ) ) ( OBus_signal . make s_DeviceChanged ( proxy daemon ) )
let changed daemon = OBus_signal . make s_Changed ( proxy daemon )
let sleeping daemon = OBus_signal . make s_Sleeping ( proxy daemon )
let resuming daemon = OBus_signal . make s_Resuming ( proxy daemon )
let about_to_sleep daemon = OBus_method . call m_AboutToSleep ( proxy daemon ) ( )
let suspend daemon = OBus_method . call m_Suspend ( proxy daemon ) ( )
let suspend_allowed daemon = OBus_method . call m_SuspendAllowed ( proxy daemon ) ( )
let hibernate daemon = OBus_method . call m_Hibernate ( proxy daemon ) ( )
let hibernate_allowed daemon = OBus_method . call m_HibernateAllowed ( proxy daemon ) ( )
let daemon_version daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_DaemonVersion ( proxy daemon )
let can_suspend daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_CanSuspend ( proxy daemon )
let can_hibernate daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_CanHibernate ( proxy daemon )
let on_battery daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_OnBattery ( proxy daemon )
let on_low_battery daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_OnLowBattery ( proxy daemon )
let lid_is_closed daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_LidIsClosed ( proxy daemon )
let lid_is_present daemon = OBus_property . make ~ monitor : UPower_monitor . monitor p_LidIsPresent ( proxy daemon )
let properties daemon = OBus_property . group ~ monitor : UPower_monitor . monitor ( proxy daemon ) interface
type typ = [ ` Unknown | ` Line_power | ` Battery | ` Ups | ` Monitor | ` Mouse | ` Keyboard | ` Pda | ` Phone ]
type state = [ ` Unknown | ` Charging | ` Discharging | ` Empty | ` Fully_charged | ` Pending_charge | ` Pending_discharge ]
type technology = [ ` Unknown | ` Lithium_ion | ` Lithium_polymer | ` Lithium_iron_phosphate | ` Lead_acid | ` Nickel_cadmium | ` Nickel_metal_hydride ]
let refresh proxy = OBus_method . call m_Refresh proxy ( )
let changed proxy = OBus_signal . make s_Changed proxy