Skip to content

Commit

Permalink
Add checking if port reqired to start server is free
Browse files Browse the repository at this point in the history
  • Loading branch information
kasia-kujawa committed Dec 11, 2024
1 parent 5e1f55d commit a4d9be3
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions cmd/agent/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/signal"
Expand Down Expand Up @@ -270,6 +271,7 @@ func watchExitErrors(ctx context.Context, log *logrus.Entry, exitCh chan error,
func runPProf(cfg config.Config, log *logrus.Entry, exitCh chan error) (closeFunc func()) {
log.Infof("starting pprof server on port: %d", cfg.PprofPort)
addr := portToServerAddr(cfg.PprofPort)
checkPort(addr, "pprof", log)
pprofSrv := &http.Server{Addr: addr, Handler: http.DefaultServeMux}
closeFn := func() {
log.Infof("closing pprof server")
Expand Down Expand Up @@ -297,8 +299,9 @@ func runHealthzEndpoints(cfg config.Config, log *logrus.Entry, checks map[string
allChecks := lo.Assign(map[string]healthz.Checker{
"server": healthz.Ping,
}, checks)

healthzSrv := &http.Server{Addr: portToServerAddr(cfg.HealthzPort), Handler: &healthz.Handler{Checks: allChecks}}
addr := portToServerAddr(cfg.HealthzPort)
checkPort(addr, "healthz", log)
healthzSrv := &http.Server{Addr: addr, Handler: &healthz.Handler{Checks: allChecks}}
closeFunc := func() {
log.Infof("closing healthz server")
if err := healthzSrv.Close(); err != nil {
Expand All @@ -320,6 +323,16 @@ func runHealthzEndpoints(cfg config.Config, log *logrus.Entry, checks map[string
return closeFunc
}

func checkPort(address string, serverName string, log *logrus.Entry) {
listener, err := net.Listen("tcp", address)
if err != nil {
log.Errorf("port required to start %s server is not free, address: %s, error: %v", serverName, address, err)
return
}
defer listener.Close() // Close the listener
log.Infof("port required to start %s server is free, address: %s", serverName, address)
}

func portToServerAddr(port int) string {
return fmt.Sprintf(":%d", port)
}
Expand Down

0 comments on commit a4d9be3

Please sign in to comment.