|
| 1 | +open Opium.Std |
| 2 | +open Lwt.Syntax |
| 3 | + |
| 4 | +let run_app app ~instances ~port = |
| 5 | + let listen_address = |
| 6 | + let inet_addr = Unix.inet_addr_any in |
| 7 | + Unix.ADDR_INET (inet_addr, port) |
| 8 | + in |
| 9 | + let socket = |
| 10 | + Lwt_unix.socket (Unix.domain_of_sockaddr listen_address) Unix.SOCK_STREAM 0 |
| 11 | + in |
| 12 | + Lwt_unix.setsockopt socket Unix.SO_REUSEADDR true; |
| 13 | + |
| 14 | + Lwt_main.run ( |
| 15 | + let+ () = Lwt_unix.bind socket listen_address in |
| 16 | + Lwt_unix.listen socket (Lwt_unix.somaxconn () [@ocaml.warning "-3"]) |
| 17 | + ); |
| 18 | + |
| 19 | + let rec accept_loop socket handler instance = |
| 20 | + let* (socket', sockaddr') = Lwt_unix.accept socket in |
| 21 | + Lwt.async (fun () -> handler sockaddr' socket'); |
| 22 | + accept_loop socket handler instance |
| 23 | + in |
| 24 | + |
| 25 | + let rock = App.to_rock app in |
| 26 | + |
| 27 | + for i = 1 to instances do |
| 28 | + flush_all (); |
| 29 | + if Lwt_unix.fork () = 0 then ( |
| 30 | + (* child *) |
| 31 | + Server.start_refreshing_date (); |
| 32 | + Lwt.async (fun () -> |
| 33 | + let* () = Lwt_io.eprintf "Listening on %d (child %d)\n" port i in |
| 34 | + let handler = Server.create_connection_handler rock in |
| 35 | + accept_loop socket handler i |
| 36 | + ); |
| 37 | + let forever, _ = Lwt.wait () in |
| 38 | + Lwt_main.run forever; |
| 39 | + exit 0) |
| 40 | + done; |
| 41 | + |
| 42 | + while true do |
| 43 | + Unix.pause () |
| 44 | + done |
| 45 | + |
| 46 | + |
| 47 | +let main () = |
| 48 | + let port = |
| 49 | + match Sys.getenv_opt "PORT" with |
| 50 | + | Some x -> int_of_string x |
| 51 | + | None -> 8080 |
| 52 | + in |
| 53 | + let instances = |
| 54 | + match Sys.getenv_opt "APP_INSTANCES" with |
| 55 | + | Some x -> int_of_string x |
| 56 | + | None -> |
| 57 | + let ic = Unix.open_process_in "getconf _NPROCESSORS_ONLN" in |
| 58 | + let cores = int_of_string (input_line ic) in |
| 59 | + ignore (Unix.close_process_in ic); |
| 60 | + cores |
| 61 | + in |
| 62 | + |
| 63 | + Server.dump_lwt (); |
| 64 | + Printf.eprintf "Starting %d instances\n" instances; |
| 65 | + |
| 66 | + let app = Server.create_app ~port in |
| 67 | + run_app app ~instances ~port |
| 68 | + |
| 69 | +let () = main () |
0 commit comments