1+ import socket
2+
13from prometheus_client import start_http_server
24import trio
5+
36from libp2p .host .ping import PingEvent
47from libp2p .metrics .ping import PingMetrics
5- from libp2p .utils .address_validation import find_free_port
8+
9+
10+ def find_available_port (start_port : int = 8000 , host : str = "127.0.0.1" ) -> int :
11+ port = start_port
12+
13+ while True :
14+ with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as sock :
15+ try :
16+ sock .bind ((host , port ))
17+ return port
18+ except OSError :
19+ port += 1
620
721
822class Metrics :
@@ -15,15 +29,26 @@ async def start_prometheus_server(
1529 self ,
1630 metric_recv_channel : trio .MemoryReceiveChannel ,
1731 ) -> None :
18-
19- free_port = find_free_port ()
20- start_http_server (free_port )
21-
22- print (f"Prometheus server started: http://localhost:{ free_port } " )
32+ metrics = find_available_port (8000 )
33+ prometheus_dashboard = find_available_port (9000 )
34+ grafana_dashboard = find_available_port (7000 )
35+
36+ start_http_server (metrics )
37+
38+ print (f"\n Prometheus metrics visible at: http://localhost:{ metrics } " )
39+ print (
40+ f"Prometheus dashboard visible at: http://localhost:{ prometheus_dashboard } "
41+ )
42+ print (f"Grafana dashboard visible at: http://localhost:{ grafana_dashboard } \n " )
43+
44+ print (
45+ "\n Start prometheus and grafana dashboard, for another terminal: \n "
46+ f"PROMETHEUS_PORT={ prometheus_dashboard } GRAFANA_PORT={ grafana_dashboard } docker compose up\n "
47+ )
2348
2449 while True :
2550 event = await metric_recv_channel .receive ()
26-
51+
2752 match event :
2853 case PingEvent ():
29- self .ping .record (event )
54+ self .ping .record (event )
0 commit comments