Skip to content

Commit

Permalink
iter5 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ex0rcist committed Jul 10, 2024
1 parent 83fadf5 commit 8d3e88c
Show file tree
Hide file tree
Showing 15 changed files with 123 additions and 95 deletions.
25 changes: 6 additions & 19 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
@@ -1,41 +1,28 @@
package main

import (
"time"

"github.com/ex0rcist/metflix/internal/agent"
"github.com/ex0rcist/metflix/internal/logging"
"github.com/rs/zerolog/log"
)

func main() {
logging.Setup()

log.Info().Msg("starting agent...")
logging.LogInfo("starting agent...")

agnt, err := agent.New()
if err != nil {
log.Error().Err(err).Msg("")
return
logging.LogFatal(err)
}

err = agnt.ParseFlags()
if err != nil {
log.Error().Err(err).Msg("")
return
logging.LogFatal(err)
}

log.Info().Msg(agnt.Config.String())
logging.LogInfo(agnt.Config.String())

err = agnt.Run()
if err != nil {
log.Error().Err(err).Msg("")
return
}
agnt.Run()

log.Info().Msg("agent ready")

for { // fixme: tmp hack for goroutine
time.Sleep(time.Second * 1)
}
logging.LogInfo("agent ready")
}
18 changes: 6 additions & 12 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,28 @@ package main
import (
"github.com/ex0rcist/metflix/internal/logging"
"github.com/ex0rcist/metflix/internal/server"

"github.com/rs/zerolog/log"
)

func main() {
logging.Setup()

log.Info().Msg("starting server...")
logging.LogInfo("starting server...")

srv, err := server.New()
if err != nil {
log.Error().Err(err).Msg("")
return
logging.LogFatal(err)
}

err = srv.ParseFlags()
if err != nil {

log.Error().Err(err).Msg("")
return
logging.LogFatal(err)
}

log.Info().Msgf(srv.Config.String())
log.Info().Msg("server ready") // TODO: must be after run?
logging.LogInfo(srv.Config.String())
logging.LogInfo("server ready") // TODO: must be after run?

err = srv.Run()
if err != nil {
log.Error().Err(err).Msg("")
return
logging.LogFatal(err)
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.22.4
require (
github.com/caarlos0/env/v11 v11.1.0
github.com/go-chi/chi/v5 v5.1.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.33.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.9.0
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
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 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down
23 changes: 16 additions & 7 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ package agent

import (
"fmt"
"sync"
"time"

"github.com/caarlos0/env/v11"
"github.com/ex0rcist/metflix/internal/entities"
"github.com/rs/zerolog/log"
"github.com/ex0rcist/metflix/internal/logging"
"github.com/spf13/pflag"
)

type Agent struct {
Config *Config
Stats *Stats
API *API

wg sync.WaitGroup
}

type Config struct {
Expand Down Expand Up @@ -58,40 +61,46 @@ func (a *Agent) ParseFlags() error {
})

if err := env.Parse(a.Config); err != nil {
fmt.Printf("%+v\n", err)
return err
}

return nil
}

func (a *Agent) Run() error {
func (a *Agent) Run() {
a.wg.Add(2)

go a.startPolling()
go a.startReporting()

return nil // return error from goroutine?
a.wg.Wait()
}

func (a *Agent) startPolling() {
defer a.wg.Done()

for {
err := a.Stats.Poll()
if err != nil {
return // todo: handle errors
logging.LogError(err)
}

time.Sleep(intToDuration(a.Config.PollInterval))
}
}

func (a *Agent) startReporting() {
defer a.wg.Done()

for {
time.Sleep(intToDuration(a.Config.ReportInterval))

a.reportStats() // todo: handle errors
a.reportStats()
}
}

func (a *Agent) reportStats() {
log.Info().Msg("reporting stats ... ")
logging.LogInfo("reporting stats ... ")

// agent continues polling while report is in progress, take snapshot?
snapshot := *a.Stats
Expand Down
4 changes: 0 additions & 4 deletions internal/agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,3 @@ func TestRun(t *testing.T) {
_, err := New()
require.NoError(t, err)
}

func TestReportStats(t *testing.T) {
// HELP: как тестировать приватные?
}
18 changes: 8 additions & 10 deletions internal/agent/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ import (
"time"

"github.com/ex0rcist/metflix/internal/entities"
"github.com/ex0rcist/metflix/internal/logging"
"github.com/ex0rcist/metflix/internal/metrics"
"github.com/rs/zerolog/log"
)

type API struct {
address *entities.Address
httpClient *http.Client
err error
}

func NewAPI(address *entities.Address, httpTransport http.RoundTripper) *API {
Expand All @@ -30,7 +29,6 @@ func NewAPI(address *entities.Address, httpTransport http.RoundTripper) *API {
return &API{
address: address,
httpClient: client,
err: nil,
}
}

Expand All @@ -40,28 +38,28 @@ func (c *API) Report(name string, metric metrics.Metric) *API {

req, err := http.NewRequest(http.MethodPost, url, http.NoBody)
if err != nil {
panic(err)
logging.LogError(err, "httpRequest error")
}

req.Header.Set("Content-Type", "text/plain")

log.Info().Msg(fmt.Sprintf("sending POST to %v", url))
logging.LogInfo(fmt.Sprintf("sending POST to %v", url))

resp, err := c.httpClient.Do(req)

if err != nil {
panic(err)
//c.err = err
logging.LogError(err, "httpClient error")
return c
}

defer resp.Body.Close()

respBody, err := io.ReadAll(resp.Body) // нужно прочитать ответ для keepalive?
if err != nil {
c.err = err
logging.LogError(entities.ErrMetricReport, "error reading response body")
}

if resp.StatusCode != http.StatusOK {
fmt.Println(respBody) // todo: log
logging.LogError(entities.ErrMetricReport, string(respBody))
}

return c
Expand Down
4 changes: 2 additions & 2 deletions internal/agent/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"math/rand"
"time"

"github.com/ex0rcist/metflix/internal/logging"
"github.com/ex0rcist/metflix/internal/metrics"
"github.com/rs/zerolog/log"
)

type Stats struct {
Expand All @@ -22,7 +22,7 @@ func NewStats() *Stats {
}

func (m *Stats) Poll() error {
log.Info().Msg("polling stats ... ")
logging.LogInfo("polling stats ... ")

m.PollCount++
m.RandomValue = metrics.Gauge(m.generator.Float64())
Expand Down
5 changes: 2 additions & 3 deletions internal/entities/address.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package entities

import (
"errors"
"fmt"
"strconv"
"strings"
Expand All @@ -18,13 +17,13 @@ func (a Address) String() string {
func (a *Address) Set(src string) error {
chunks := strings.Split(src, ":")
if len(chunks) != 2 {
return fmt.Errorf("set address failed: %w", errors.New("bad address"))
return fmt.Errorf("set address failed: %w", ErrBadAddressFormat)
}

port := chunks[1]

if _, err := strconv.Atoi(port); err != nil {
return fmt.Errorf("set address failed: %w", errors.New("bad port"))
return fmt.Errorf("set address failed: %w", err)
}

*a = Address(src)
Expand Down
14 changes: 14 additions & 0 deletions internal/entities/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package entities

import "errors"

var (
ErrBadAddressFormat = errors.New("bad net address format")

ErrMetricNotFound = errors.New("metric not found")
ErrMetricUnknown = errors.New("unknown metric type")
ErrMetricReport = errors.New("metric report error")
ErrMetricMissingName = errors.New("metric name is missing")
ErrMetricInvalidName = errors.New("metric name contains invalid characters")
ErrMetricLongName = errors.New("metric name is too long")
)
40 changes: 32 additions & 8 deletions internal/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,47 @@ package logging

import (
"os"
"strings"
"time"

"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
)

func Setup() {
// HELP: not working :(
// zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack

output := zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: time.RFC3339, // time.RFC822
}
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}

// HELP: didn't manage to put error stack :(
l := zerolog.New(output).With().Timestamp()

log.Logger = l.Logger()
}

func NewError(err error) error { // wrap err to pkg/errors
return errors.New(err.Error()) // TODO: can we remove this func from stack?
}

func LogError(err error, messages ...string) {
msg := optMessagesToString(messages)
log.Error().Stack().Err(err).Msg(msg)
}

func LogFatal(err error, messages ...string) {
msg := optMessagesToString(messages)
log.Fatal().Stack().Err(err).Msg(msg)
}

func LogInfo(messages ...string) {
msg := optMessagesToString(messages)
log.Info().Msg(msg)
}

func optMessagesToString(messages []string) string {
if len(messages) == 0 {
return ""
}

return strings.Join(messages, "; ")
}
Loading

0 comments on commit 8d3e88c

Please sign in to comment.