Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iter8 #10

Closed
wants to merge 23 commits into from
27 changes: 19 additions & 8 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,56 @@ package main

import (
"context"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/DieOfCode/go-alert-service/internal/agent"
"github.com/DieOfCode/go-alert-service/internal/configuration"
m "github.com/DieOfCode/go-alert-service/internal/metrics"
"github.com/rs/zerolog"
)

func main() {
var metrics []m.Metric
logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
var metrics []m.Metrics
var counter int64
config := configuration.AgentConfiguration()
httpClient := &http.Client{
Timeout: time.Minute,
}

metricsAgent := agent.NewMetricsAgent(logger)
poolTicker := time.NewTicker(time.Duration(config.PollInterval) * time.Second)
reportTicker := time.NewTicker(time.Duration(config.ReportInterval) * time.Second)

ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGKILL, syscall.SIGTERM, syscall.SIGINT)
defer cancel()

logger.Info().
Int("pollInterval", config.PollInterval).
Int("reportInterval", config.ReportInterval).
Msg("Started collecting metrics")

loop:
for {
select {
case <-reportTicker.C:
metrics = append(metrics, m.Metric{MetricType: m.Counter, MetricName: m.PoolCount, Value: counter})
err := agent.SendMetric(ctx, *httpClient, metrics, config.ServerAddress)
metrics = append(metrics, m.Metrics{MType: m.Counter, ID: m.PoolCount, Delta: &counter})
err := metricsAgent.SendMetric(ctx, httpClient, metrics, config.ServerAddress)
if err != nil {
log.Fatal(err)
logger.Fatal().Err(err).Msg("SEND METRIC ERROR")
} else {
logger.Info().Interface("metrics", metrics).Msgf("METRICS SEND %d", len(metrics))
}
case <-poolTicker.C:
counter++
metrics = agent.CollectGaudeMetrics()
metrics = append(metrics, m.Metric{MetricType: m.Gauge, MetricName: m.RandomValue, Value: rand.Float64()})
metrics = metricsAgent.CollectGaudeMetrics()
random := rand.Float64()
metrics = append(metrics, m.Metrics{MType: m.Gauge, ID: m.RandomValue, Value: &random})
logger.Info().Interface("metrics", metrics).Msg("Metrics collected")

case <-ctx.Done():

Expand Down
19 changes: 13 additions & 6 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,39 @@
package main

import (
"fmt"
"net/http"
"os"

"github.com/DieOfCode/go-alert-service/internal/configuration"
"github.com/DieOfCode/go-alert-service/internal/handler"
log "github.com/DieOfCode/go-alert-service/internal/logger"
"github.com/DieOfCode/go-alert-service/internal/storage"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog"
)

func main() {

logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
config := configuration.ServerConfiguration()
memStorage := storage.NewMemStorage()
handler := handler.NewHandler(memStorage)
memStorage := storage.NewMemStorage(logger)
handler := handler.NewHandler(memStorage, logger)

router := chi.NewRouter()

router.Route("/", func(r chi.Router) {
r.Use(middleware.RequestLogger(&log.LogFormatter{Logger: &logger}))
r.Use(middleware.Recoverer)
r.MethodFunc(http.MethodPost, "/update/{type}/{name}/{value}", handler.HandleUpdateMetric)
r.MethodFunc(http.MethodGet, "/value/{type}/{name}", handler.HandleGetMetricByName)
r.MethodFunc(http.MethodGet, "/", handler.HandleGetAllMetrics)
r.MethodFunc(http.MethodPost, "/update/", handler.HandleUpdateJSONMetric)
r.MethodFunc(http.MethodPost, "/value/", handler.HandleGetJSONMetric)
})

err := http.ListenAndServe(config.ServerAddress, router)

logger.Info().Msgf("Server is listerning on %s", config.ServerAddress)
if err != nil {
fmt.Println("Ошибка запуска сервера:", err)
logger.Fatal().Err(err).Msg("Server start error")
}
}
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,12 @@ go 1.21.3
require (
github.com/caarlos0/env/v6 v6.10.1
github.com/go-chi/chi/v5 v5.0.10
github.com/rs/zerolog v1.31.0
)

require (
github.com/go-chi/chi v1.5.5
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
golang.org/x/sys v0.12.0 // indirect
)
21 changes: 21 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
github.com/caarlos0/env/v6 v6.10.1 h1:t1mPSxNpei6M5yAeu1qtRdPAK29Nbcf/n3G7x+b3/II=
github.com/caarlos0/env/v6 v6.10.1/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
59 changes: 45 additions & 14 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,33 @@ package agent
import (
"context"
"fmt"
"log"
"net/http"
"reflect"
"runtime"
"sync"

m "github.com/DieOfCode/go-alert-service/internal/metrics"
"github.com/rs/zerolog"
)

// TODO replace with real metric type
type Agent interface {
CollectGaudeMetrics() []m.Metrics
SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, address string) error
}

type MetricsAgent struct {
//TODO: replace to loger interface
logger zerolog.Logger
}

func CollectGaudeMetrics() []m.Metric {
var collectedMerics []m.Metric
func NewMetricsAgent(logger zerolog.Logger) *MetricsAgent {
return &MetricsAgent{
logger: logger,
}
}

func (metricAgent *MetricsAgent) CollectGaudeMetrics() []m.Metrics {
var collectedMerics []m.Metrics
var stat runtime.MemStats

runtime.ReadMemStats(&stat)
Expand All @@ -31,33 +45,50 @@ func CollectGaudeMetrics() []m.Metric {
continue
}

value := memStatValue.FieldByName(metricName)

collectedMerics = append(collectedMerics, m.Metric{MetricType: m.Gauge, MetricName: fieldValue.Name, Value: value})
canFloat := memStatValue.FieldByName(metricName).CanFloat()
if !canFloat {
continue
}
value := memStatValue.FieldByName(metricName).Float()
collectedMerics = append(collectedMerics, m.Metrics{MType: m.Gauge, ID: fieldValue.Name, Value: &value})

}

return collectedMerics
}

func SendMetric(ctx context.Context, client http.Client, metrics []m.Metric, address string) error {
func (metricAgent *MetricsAgent) SendMetric(ctx context.Context, client *http.Client, metrics []m.Metrics, address string) error {
wg := sync.WaitGroup{}
wg.Add(len(metrics))

for _, element := range metrics {

go func(element m.Metric) {
go func(element m.Metrics) {
defer wg.Done()
request := fmt.Sprintf("http://%s/update/%s/%s/%v", address, element.MetricType, element.MetricName, element.Value)
metricType := element.MType
metricID := element.ID
var request string
if metricType == m.Gauge {
if element.Value != nil {
value := *element.Value
request = fmt.Sprintf("http://%s/update/%s/%s/%v", address, metricType, metricID, value)
} else {
request = fmt.Sprintf("http://%s/update/%s/%s", address, metricType, metricID)
}

} else {
value := *element.Delta
request = fmt.Sprintf("http://%s/update/%s/%s/%v", address, element.MType, metricID, value)

}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, request, nil)
if err != nil {
log.Println(err)
metricAgent.logger.Err(err).Msgf("REQUEST CREATE ERROR")
return
}
req.Header.Set("Content-Type", "text/plain")
resp, err := client.Do(req)
if err != nil {
log.Println(err)
metricAgent.logger.Err(err).Msgf("UPDATE METRIC VALUE ERROR %s", element.ID)
return
}
resp.Body.Close()
Expand Down
5 changes: 5 additions & 0 deletions internal/error/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package error

type Error struct {
Error string `json:"error"`
}
Loading
Loading