Skip to content

Commit

Permalink
updated
Browse files Browse the repository at this point in the history
  • Loading branch information
timurIsaevIY committed Nov 26, 2024
1 parent 8928059 commit c171290
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 49 deletions.
5 changes: 2 additions & 3 deletions cmd/attractions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ func main() {

logger := setupLogger()

metricMw := metricsMw.Create()

db, err := sql.Open("postgres", cfg.ConnStr)
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
Expand All @@ -70,7 +72,6 @@ func main() {
}

go func() {

logger.Info("Starting HTTP server for metrics on :8091")
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error(fmt.Sprintf("HTTP server listen: %s\n", err))
Expand All @@ -88,8 +89,6 @@ func main() {
searchRepo := searchRepo.NewSearchRepository(db)
searchUsecase := searchUsecase.NewSearchUsecase(searchRepo)

metricMw := metricsMw.Create()

attractionsHandler := grpcAttractions.NewGrpcAttractionsHandler(placeUsecase)
citiesHandler := grpcCities.NewGrpcCitiesHandler(citiesUsecase)
reviewsHandler := grpcReviews.NewGrpcReviewsHandler(reviewUsecase)
Expand Down
18 changes: 18 additions & 0 deletions cmd/trips/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,24 @@ func main() {
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-stop

go func() {
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()

for {
select {
case <-ticker.C:
metricMw.TrackSystemMetrics("trips")
case <-stop:
return
}
}
}()

stop1 := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-stop1

log.Println("Shutting down gRPC server...")
grpcTripsServer.GracefulStop()
log.Println("gRPC server gracefully stopped")
Expand Down
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,25 @@ require (
github.com/fatih/color v1.18.0
github.com/golang/protobuf v1.5.4
github.com/prometheus/client_golang v1.20.5
github.com/shirou/gopsutil v3.21.11+incompatible
google.golang.org/grpc v1.68.0
google.golang.org/protobuf v1.35.2
)

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.8.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect
Expand Down
13 changes: 13 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumC
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
Expand All @@ -39,6 +41,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
Expand Down Expand Up @@ -66,12 +70,20 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargg
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg=
github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY=
github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
Expand All @@ -90,6 +102,7 @@ golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
9 changes: 5 additions & 4 deletions internal/pkg/metrics/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
)

type MetricsHTTP interface {
IncreaseHits(string, string)
IncreaseErr(string, string)
AddDurationToHistogram(string, time.Duration)
ServerMetricsInterceptor(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error)
IncreaseHits(method, path, service string)
IncreaseErr(method, path, service string)
AddDurationToHistogram(method, service string, duration time.Duration)
TrackSystemMetrics(serviceName string)
ServerMetricsInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)
}
138 changes: 98 additions & 40 deletions internal/pkg/metrics/middleware/prometheus.go
Original file line number Diff line number Diff line change
@@ -1,78 +1,136 @@
package middleware
package metrics

import (
"2024_2_ThereWillBeName/internal/pkg/metrics"
"context"
"google.golang.org/grpc"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"os"
"strings"
"sync"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"google.golang.org/grpc"
)

type SystemMetrics struct {
cpuUsage *prometheus.GaugeVec
memoryUsage *prometheus.GaugeVec
diskUsage *prometheus.GaugeVec
}

type GrpcMiddleware struct {
hits *prometheus.CounterVec
errors *prometheus.CounterVec
durations *prometheus.HistogramVec
hits *prometheus.CounterVec
errors *prometheus.CounterVec
durations *prometheus.HistogramVec
systemMetric *SystemMetrics
mu sync.Mutex
}

func Create() metrics.MetricsHTTP {
hits := prometheus.NewCounterVec(
prometheus.CounterOpts{
middleware := &GrpcMiddleware{
hits: promauto.NewCounterVec(prometheus.CounterOpts{
Name: "grpc_method_hits_total",
Help: "Total number of gRPC method calls.",
},
[]string{"method", "path"},
)
errors := prometheus.NewCounterVec(
prometheus.CounterOpts{
Help: "Total number of gRPC method calls across all services",
}, []string{"method", "path", "service"}),

errors: promauto.NewCounterVec(prometheus.CounterOpts{
Name: "grpc_method_errors_total",
Help: "Total number of gRPC method errors.",
},
[]string{"method", "path"},
)
durations := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Help: "Total number of gRPC method errors across all services",
}, []string{"method", "path", "service"}),

durations: promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "grpc_method_duration_seconds",
Help: "Histogram of gRPC method call durations.",
Help: "Histogram of gRPC method call durations across services",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "path"},
)
}, []string{"method", "service"}),

prometheus.MustRegister(hits, errors, durations)
systemMetric: &SystemMetrics{
cpuUsage: promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "service_cpu_usage_percent",
Help: "CPU usage percentage per service",
}, []string{"service", "hostname"}),

return &GrpcMiddleware{
hits: hits,
errors: errors,
durations: durations,
memoryUsage: promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "service_memory_usage_bytes",
Help: "Memory usage in bytes per service",
}, []string{"service", "hostname"}),

diskUsage: promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "service_disk_usage_percent",
Help: "Disk usage percentage per service",
}, []string{"service", "mount_point", "hostname"}),
},
}

return middleware
}

func (m *GrpcMiddleware) IncreaseHits(method, path string) {
m.hits.WithLabelValues(method, path).Inc()
func (m *GrpcMiddleware) IncreaseHits(method, path, service string) {
m.hits.WithLabelValues(method, path, service).Inc()
}

func (m *GrpcMiddleware) IncreaseErr(method, path string) {
m.errors.WithLabelValues(method, path).Inc()
func (m *GrpcMiddleware) IncreaseErr(method, path, service string) {
m.errors.WithLabelValues(method, path, service).Inc()
}

func (m *GrpcMiddleware) AddDurationToHistogram(method string, duration time.Duration) {
m.durations.WithLabelValues(method).Observe(duration.Seconds())
func (m *GrpcMiddleware) AddDurationToHistogram(method, service string, duration time.Duration) {
m.durations.WithLabelValues(method, service).Observe(duration.Seconds())
}

func (m *GrpcMiddleware) ServerMetricsInterceptor(ctx context.Context,
func (m *GrpcMiddleware) TrackSystemMetrics(serviceName string) {
m.mu.Lock()
defer m.mu.Unlock()

hostname, _ := os.Hostname()

// CPU Usage
cpuPercent, err := cpu.Percent(time.Second, false)
if err == nil && len(cpuPercent) > 0 {
m.systemMetric.cpuUsage.WithLabelValues(serviceName, hostname).Set(cpuPercent[0])
}

// Memory Usage
vmStat, err := mem.VirtualMemory()
if err == nil {
m.systemMetric.memoryUsage.WithLabelValues(serviceName, hostname).Set(float64(vmStat.Used))
}

// Disk Usage
diskStat, err := disk.Usage("/")
if err == nil {
m.systemMetric.diskUsage.WithLabelValues(serviceName, "/", hostname).Set(diskStat.UsedPercent)
}
}

func (m *GrpcMiddleware) ServerMetricsInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (interface{}, error) {

handler grpc.UnaryHandler,
) (interface{}, error) {
start := time.Now()
serviceName := extractServiceName(info.FullMethod)

h, err := handler(ctx, req)
duration := time.Since(start)

if err != nil {
m.IncreaseErr(info.FullMethod, "path")
m.IncreaseErr(info.FullMethod, "error", serviceName)
}
m.IncreaseHits(info.FullMethod, "path")
m.AddDurationToHistogram(info.FullMethod, duration)
m.IncreaseHits(info.FullMethod, "success", serviceName)
m.AddDurationToHistogram(info.FullMethod, serviceName, duration)

return h, err
}

func extractServiceName(fullMethod string) string {
parts := strings.Split(fullMethod, "/")
if len(parts) >= 2 {
return parts[1]
}
return "unknown"
}
4 changes: 2 additions & 2 deletions prometheus.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ scrape_configs:
- job_name: "trips"
metrics_path: api/v1/metrics
static_configs:
- targets: [ 'attractions:8092' ]
- targets: [ 'trips:8092' ]

- job_name: "users"
metrics_path: api/v1/metrics
static_configs:
- targets: [ 'attractions:8093' ]
- targets: [ 'users:8093' ]

0 comments on commit c171290

Please sign in to comment.