Skip to content

Commit

Permalink
refactor: switch metrics to Service pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
ThinkChaos committed Apr 3, 2024
1 parent d7a2952 commit e1c717b
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 29 deletions.
5 changes: 5 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/0xERR0R/blocky/config"
"github.com/0xERR0R/blocky/evt"
"github.com/0xERR0R/blocky/log"
"github.com/0xERR0R/blocky/metrics"
"github.com/0xERR0R/blocky/server"
"github.com/0xERR0R/blocky/util"

Expand Down Expand Up @@ -47,6 +48,10 @@ func startServer(_ *cobra.Command, _ []string) error {
ctx, cancelFn := context.WithCancel(context.Background())
defer cancelFn()

if cfg.Prometheus.Enable {
metrics.StartCollection()
}

srv, err := server.NewServer(ctx, cfg)
if err != nil {
return fmt.Errorf("can't start server: %w", err)
Expand Down
14 changes: 9 additions & 5 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ type Config struct {
// The `yaml` struct tags are just for manual testing,
// and require replacing `yaml:"-"` in Config to work.
type Services struct {
DoH DoHService `yaml:"dns-over-https"`
DoH DoHService `yaml:"dns-over-https"`
Metrics MetricsService `yaml:"metrics"`
}

type Ports struct {
Expand Down Expand Up @@ -618,11 +619,14 @@ func (cfg *Config) validate(logger *logrus.Entry) {
// This should be replaced with a migration once everything from Ports is supported in Services.
// Done this way for now to avoid creating temporary generic services and updating all Ports related code at once.
func (cfg *Config) CopyPortsToServices() {
httpAddrs := httpAddrs{
HTTPAddrs: HTTPAddrs{HTTP: cfg.Ports.HTTP},
HTTPSAddrs: HTTPSAddrs{HTTPS: cfg.Ports.HTTPS},
}

cfg.Services = Services{
DoH: DoHService{Addrs: DoHAddrs{
HTTPAddrs: HTTPAddrs{HTTP: cfg.Ports.HTTP},
HTTPSAddrs: HTTPSAddrs{HTTPS: cfg.Ports.HTTPS},
}},
DoH: DoHService{Addrs: httpAddrs},
Metrics: MetricsService{Addrs: httpAddrs},
}
}

Expand Down
12 changes: 9 additions & 3 deletions config/doh_service.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package config

type DoHService struct {
Addrs DoHAddrs `yaml:"addrs"`
type (
DoHService httpService
MetricsService httpService
)

// httpService can be used by any service that uses HTTP(S).
type httpService struct {
Addrs httpAddrs `yaml:"addrs"`
}

type DoHAddrs struct {
type httpAddrs struct {
HTTPAddrs `yaml:",inline"`
HTTPSAddrs `yaml:",inline"`
}
Expand Down
17 changes: 5 additions & 12 deletions metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
package metrics

import (
"github.com/0xERR0R/blocky/config"

"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

//nolint:gochecknoglobals
Expand All @@ -17,12 +13,9 @@ func RegisterMetric(c prometheus.Collector) {
_ = reg.Register(c)
}

// Start starts prometheus endpoint
func Start(router *chi.Mux, cfg config.Metrics) {
if cfg.Enable {
_ = reg.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
_ = reg.Register(collectors.NewGoCollector())
router.Handle(cfg.Path, promhttp.InstrumentMetricHandler(reg,
promhttp.HandlerFor(reg, promhttp.HandlerOpts{})))
}
func StartCollection() {
_ = reg.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
_ = reg.Register(collectors.NewGoCollector())

registerEventListeners()
}
4 changes: 2 additions & 2 deletions metrics/metrics_event_publisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
"github.com/prometheus/client_golang/prometheus"
)

// RegisterEventListeners registers all metric handlers by the event bus
func RegisterEventListeners() {
// registerEventListeners registers all metric handlers on the event bus
func registerEventListeners() {
registerBlockingEventListeners()
registerCachingEventListeners()
registerApplicationEventListeners()
Expand Down
48 changes: 48 additions & 0 deletions metrics/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package metrics

import (
"github.com/0xERR0R/blocky/config"
"github.com/0xERR0R/blocky/service"
"github.com/0xERR0R/blocky/util"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Service implements service.HTTPService.
type Service struct {
service.HTTPInfo
}

func NewService(cfg config.MetricsService, metricsCfg config.Metrics) *Service {
endpoints := util.ConcatSlices(
service.EndpointsFromAddrs(service.HTTPProtocol, cfg.Addrs.HTTP),
service.EndpointsFromAddrs(service.HTTPSProtocol, cfg.Addrs.HTTPS),
)

if !metricsCfg.Enable || len(endpoints) == 0 {
// Avoid setting up collectors and listeners
return new(Service)
}

s := &Service{
HTTPInfo: service.HTTPInfo{
Info: service.Info{
Name: "Metrics",
Endpoints: endpoints,
},

Mux: chi.NewMux(),
},
}

s.Mux.Handle(
metricsCfg.Path,
promhttp.InstrumentMetricHandler(reg, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})),
)

return s
}

func (s *Service) Merge(other service.Service) (service.Merger, error) {
return service.MergeHTTP(s, other)
}
7 changes: 3 additions & 4 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,6 @@ func newTLSConfig(cfg *config.Config) (*tls.Config, error) {
}

// NewServer creates new server instance with passed config
//
//nolint:funlen
func NewServer(ctx context.Context, cfg *config.Config) (server *Server, err error) {
cfg.CopyPortsToServices()

Expand All @@ -142,8 +140,6 @@ func NewServer(ctx context.Context, cfg *config.Config) (server *Server, err err
return nil, err
}

metrics.RegisterEventListeners()

bootstrap, err := resolver.NewBootstrap(ctx, cfg)
if err != nil {
return nil, err
Expand Down Expand Up @@ -194,6 +190,7 @@ func (s *Server) createServices() ([]service.Service, error) {
res := []service.Service{
newHTTPMiscService(s.cfg, openAPIImpl),
newDoHService(s.cfg.Services.DoH, s.handleReq),
metrics.NewService(s.cfg.Services.Metrics, s.cfg.Prometheus),
}

// Remove services the user has not enabled
Expand Down Expand Up @@ -244,6 +241,8 @@ func createListeners(ctx context.Context, cfg *config.Config, tlsCfg *tls.Config
newListeners(ctx, service.HTTPSProtocol, cfg.Ports.HTTPS, listenTLS, res),
newListeners(ctx, service.HTTPProtocol, cfg.Services.DoH.Addrs.HTTP, service.ListenTCP, res),
newListeners(ctx, service.HTTPSProtocol, cfg.Services.DoH.Addrs.HTTPS, listenTLS, res),
newListeners(ctx, service.HTTPProtocol, cfg.Services.Metrics.Addrs.HTTP, service.ListenTCP, res),
newListeners(ctx, service.HTTPSProtocol, cfg.Services.Metrics.Addrs.HTTPS, listenTLS, res),
)
if err != nil {
return nil, err
Expand Down
3 changes: 0 additions & 3 deletions server/server_endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net"
"net/http"

"github.com/0xERR0R/blocky/metrics"
"github.com/0xERR0R/blocky/resolver"

"github.com/0xERR0R/blocky/api"
Expand Down Expand Up @@ -74,8 +73,6 @@ func createHTTPRouter(cfg *config.Config, openAPIImpl api.StrictServerInterface)

configureRootHandler(cfg, router)

metrics.Start(router, cfg.Prometheus)

return router
}

Expand Down

0 comments on commit e1c717b

Please sign in to comment.