Skip to content

Commit

Permalink
Expose metrics on configurable port
Browse files Browse the repository at this point in the history
  • Loading branch information
qba73 committed Mar 22, 2024
1 parent 29dfbfb commit f8af094
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
9 changes: 7 additions & 2 deletions hpot.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ func (p *Pot) Records() []net.Addr {
// to handle requests on incoming connections on given ports.
func (p *Pot) ListenAndServe() error {
mux := http.NewServeMux()
mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d", p.NumConnections())
mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d\n", p.NumConnections())
})

s := &http.Server{
Expand All @@ -57,6 +57,9 @@ func (p *Pot) ListenAndServe() error {
}

go func() {
if p.Verbose {
fmt.Println("Starting metrics server on:", s.Addr)
}
if err := s.ListenAndServe(); err != nil {
panic(err)
}
Expand Down Expand Up @@ -116,6 +119,7 @@ In verbose mode (-v), reports all incoming connections.`

func Main() int {
verbose := flag.Bool("v", false, "verbose output")
adminPort := flag.Int("admin", 8085, "admin port for reading metrics")
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Println(usage)
Expand All @@ -130,6 +134,7 @@ func Main() int {

pot := NewHoneyPotServer()
pot.Verbose = *verbose
pot.AdminPort = *adminPort
pot.Ports = ports

if err := pot.ListenAndServe(); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions hpot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func TestPotReturnsConnectionCount(t *testing.T) {
}()

got := getStats(t, pot.AdminPort)
want := "0"
want := "0\n"

if want != got {
t.Error(cmp.Diff(want, got))
Expand All @@ -73,7 +73,7 @@ func TestPotReturnsConnectionCount(t *testing.T) {
mustConnect(t, port)

got = getStats(t, pot.AdminPort)
want = "2"
want = "2\n"

if want != got {
t.Error(cmp.Diff(want, got))
Expand All @@ -83,7 +83,7 @@ func TestPotReturnsConnectionCount(t *testing.T) {
func getStats(t *testing.T, port int) string {
t.Helper()

url := fmt.Sprintf("http://127.0.0.1:%d/stats", port)
url := fmt.Sprintf("http://127.0.0.1:%d/metrics", port)
res, err := http.Get(url)
for err != nil {
time.Sleep(10 * time.Millisecond)
Expand Down

0 comments on commit f8af094

Please sign in to comment.