Skip to content

Commit f8a722a

Browse files
committed
Add option to allow specifying address to bind to
1 parent fb4f8b1 commit f8a722a

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

app/prometheus_unix.ml

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,46 @@ module Unix_runtime = struct
4242
]
4343
end
4444

45-
type config = int option
45+
type config = string option
4646

4747
module Server = Prometheus_app.Cohttp(Cohttp_lwt_unix.Server)
4848

49-
let serve = function
50-
| None -> []
51-
| Some port ->
52-
let mode = `TCP (`Port port) in
49+
let bind addr port =
50+
let open! Unix in
51+
let [@ocaml.warning "-partial-match"] addrinfo :: _ =
52+
getaddrinfo addr port [AI_SOCKTYPE SOCK_STREAM] in
53+
let socket = socket ~cloexec:true addrinfo.ai_family addrinfo.ai_socktype addrinfo.ai_protocol in
54+
let () = setsockopt socket SO_REUSEADDR true in
5355
let callback = Server.callback in
56+
let () = bind socket addrinfo.ai_addr in
57+
let () = listen socket 20 in
58+
let mode = `TCP (`Socket (Lwt_unix.of_unix_file_descr socket)) in
5459
let thread = Cohttp_lwt_unix.Server.create ~mode (Cohttp_lwt_unix.Server.make ~callback ()) in
5560
[thread]
5661

62+
let serve config =
63+
let addr = "0.0.0.0" in
64+
let port = "9090" in
65+
match config with
66+
| None -> []
67+
| Some config_s ->
68+
try
69+
match (String.split_on_char ':' config_s) with
70+
| [] -> bind addr port
71+
| port :: [] -> bind addr port
72+
| addr :: port :: [] -> bind addr port
73+
with
74+
| Match_failure _ -> Printf.printf "ERROR: Incorrect addr:port pair specified, prometheus listener not starting.\n"; flush_all (); []
75+
[@@ocaml.warning "-partial-match"]
76+
5777
let listen_prometheus =
5878
let open! Cmdliner in
5979
let doc =
60-
Arg.info ~docs:"MONITORING OPTIONS" ~docv:"PORT" ~doc:
61-
"Port on which to provide Prometheus metrics over HTTP."
80+
Arg.info ~docs:"MONITORING OPTIONS" ~docv:"ADDR_PORT" ~doc:
81+
"Address and port on which to provide Prometheus metrics over HTTP."
6282
["listen-prometheus"]
6383
in
64-
Arg.(value @@ opt (some int) None doc)
84+
Arg.(value @@ opt (some string) None doc)
6585

6686
let opts = listen_prometheus
6787

0 commit comments

Comments
 (0)