Skip to content

Commit

Permalink
refactor: add prometheus server package
Browse files Browse the repository at this point in the history
  • Loading branch information
manu0466 committed Aug 2, 2024
1 parent 0d084f7 commit d646865
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 9 deletions.
11 changes: 2 additions & 9 deletions cmd/start/cmd.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package start

import (
"fmt"
"net/http"
"os"
"os/signal"
"sync"
Expand All @@ -18,7 +16,6 @@ import (
"github.com/forbole/juno/v5/types"
cmdtypes "github.com/forbole/juno/v5/types/cmd"
"github.com/forbole/juno/v5/utils"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
Expand Down Expand Up @@ -61,12 +58,7 @@ func startParsing(ctx *parser.Context) error {
// Start the prometheus monitoring
monitoringCfg := ctx.Config.Monitoring
if monitoringCfg.Enabled {
http.Handle("/metrics", promhttp.Handler())
server := &http.Server{
Addr: fmt.Sprintf(":%d", monitoringCfg.Port),
ReadHeaderTimeout: 3 * time.Second,
}
go server.ListenAndServe()
ctx.Prometheus.Start()
}

// Start periodic operations
Expand Down Expand Up @@ -234,5 +226,6 @@ func trapSignal(ctx *parser.Context) {
defer ctx.Node.Stop()
defer ctx.Database.Close()
defer waitGroup.Done()
defer ctx.Prometheus.Stop()
}()
}
3 changes: 3 additions & 0 deletions parser/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/forbole/juno/v5/logging"
"github.com/forbole/juno/v5/modules"
"github.com/forbole/juno/v5/node"
"github.com/forbole/juno/v5/prometheus"
"github.com/forbole/juno/v5/types"
"github.com/forbole/juno/v5/types/config"
)
Expand All @@ -17,6 +18,7 @@ type Context struct {
Database database.Database
Logger logging.Logger
Modules []modules.Module
Prometheus *prometheus.Server
}

// NewContext builds a new Context instance
Expand All @@ -35,5 +37,6 @@ func NewContext(
Database: db,
Modules: modules,
Logger: logger,
Prometheus: prometheus.NewServer(config.Monitoring.Port),
}
}
44 changes: 44 additions & 0 deletions prometheus/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package prometheus

import (
"fmt"
"net/http"
"time"

"github.com/prometheus/client_golang/prometheus/promhttp"
)

type Server struct {
port int16
server *http.Server
}

// NewServer returns a new prometheus server instance
func NewServer(port int16) *Server {
return &Server{
port: port,
}
}

// Start starts the prometheus server
func (s *Server) Start() {
// Server already started
if s.server != nil {
return
}

http.Handle("/metrics", promhttp.Handler())
s.server = &http.Server{
Addr: fmt.Sprintf(":%d", s.port),
ReadHeaderTimeout: 3 * time.Second,
}
go s.server.ListenAndServe()
}

// Stop stops the prometheus server
func (s *Server) Stop() {
if s.server != nil {
s.server.Close()
s.server = nil
}
}

0 comments on commit d646865

Please sign in to comment.