Skip to content

Commit 1ad0a47

Browse files
committed
Add option to allow specifying address to bind to
1 parent 9bffcbe commit 1ad0a47

1 file changed

Lines changed: 31 additions & 5 deletions

File tree

app/prometheus_unix.ml

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,41 @@ module Unix_runtime = struct
4242
]
4343
end
4444

45-
type config = int option
45+
type config = {
46+
port : int option;
47+
addr : string option;
48+
}
4649

4750
module Server = Prometheus_app.Cohttp(Cohttp_lwt_unix.Server)
4851

49-
let serve = function
50-
| None -> []
51-
| Some port ->
52+
let serve config = match config.port, config.addr with
53+
| None, _ -> []
54+
| Some port, None ->
5255
let mode = `TCP (`Port port) in
5356
let callback = Server.callback in
5457
let thread = Cohttp_lwt_unix.Server.create ~mode (Cohttp_lwt_unix.Server.make ~callback ()) in
5558
[thread]
59+
| Some port, Some addr ->
60+
let open! Unix in
61+
let [@ocaml.warning "-partial-match"] addrinfo :: _ =
62+
getaddrinfo addr (Int.to_string port) [AI_SOCKTYPE SOCK_STREAM] in
63+
let socket = Lwt_unix.socket ~cloexec:true addrinfo.ai_family addrinfo.ai_socktype addrinfo.ai_protocol in
64+
let () = Lwt_unix.setsockopt socket SO_REUSEADDR true in
65+
let mode = `TCP (`Socket socket) in
66+
let callback = Server.callback in
67+
let () = Lwt.async (fun () -> Lwt_unix.bind socket addrinfo.ai_addr) in
68+
let () = Lwt_unix.listen socket 20 in
69+
let thread = Cohttp_lwt_unix.Server.create ~mode (Cohttp_lwt_unix.Server.make ~callback ()) in
70+
[thread]
71+
72+
let listen_prometheus_addr =
73+
let open! Cmdliner in
74+
let doc =
75+
Arg.info ~docs:"MONITORING OPTIONS" ~docv:"ADDR" ~doc:
76+
"Ip address on which to provide Prometheus metrics over HTTP."
77+
["listen-prometheus-addr"]
78+
in
79+
Arg.(value @@ opt (some string) None doc)
5680

5781
let listen_prometheus =
5882
let open! Cmdliner in
@@ -63,7 +87,9 @@ let listen_prometheus =
6387
in
6488
Arg.(value @@ opt (some int) None doc)
6589

66-
let opts = listen_prometheus
90+
let opts =
91+
let combine port addr = { port; addr } in
92+
Cmdliner.Term.(const combine $ listen_prometheus $ listen_prometheus_addr)
6793

6894
let () =
6995
let add (info, collector) =

0 commit comments

Comments
 (0)