Skip to content

Commit

Permalink
Add documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Zagir2000 committed Sep 26, 2023
1 parent 4247eb6 commit a464cf0
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 5 deletions.
1 change: 1 addition & 0 deletions internal/agent/hash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"hash"
)

// Создаем хеш для его передачи на сервер.
func CrateHash(secretKey string, data []byte, hashNew func() hash.Hash) string {
secretKeyToByte := []byte(secretKey)
h := hmac.New(hashNew, secretKeyToByte)
Expand Down
25 changes: 20 additions & 5 deletions internal/agent/metricscollect/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,39 @@ import (
)

const (
counterMetric string = "counter"
gaugeMetric string = "gauge"
randomValueName string = "RandomValue"
counterMetric string = "counter" //counter metric
gaugeMetric string = "gauge" //gauge metric
randomValueName string = "RandomValue" // random value
pollCountName string = "PollCount"
contentType string = "application/json"
compressType string = "gzip"
)

// Константы для хедера.
const (
contentType string = "application/json"
compressType string = "gzip"
)

// Структура для сбора и отправки метрик.
type RuntimeMetrics struct {
RuntimeMemstats map[string]float64
PollCount int64
RandomValue float64
pollInterval time.Duration
}

// Структура для ошибки при отправке на сервер.
type SendMetricsError struct {
Code int `json:"code"`
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
}

// Инициализицаия структуры для сбора и отправки метрик.
func IntervalPin(pollIntervalFlag int) RuntimeMetrics {
return RuntimeMetrics{pollInterval: time.Duration(pollIntervalFlag), RuntimeMemstats: make(map[string]float64), PollCount: 0, RandomValue: 0}
}

// Добавление метрик в стрктуру RuntimeMetrics для будущей их отправки.
func (m *RuntimeMetrics) AddValueMetric() error {

mapstats := make(map[string]float64)
Expand Down Expand Up @@ -97,6 +105,7 @@ func (m *RuntimeMetrics) AddValueMetric() error {
return nil
}

// Добавление метрик с помощью пакета gopsutil и сбор дополнительных метрик.
func (m *RuntimeMetrics) AddVaueMetricGopsutil() error {
cpuStat, err := cpu.Times(true)
if err != nil {
Expand All @@ -117,6 +126,7 @@ func (m *RuntimeMetrics) AddVaueMetricGopsutil() error {
return nil
}

// Функция для отправления метрик на сервер пачками.
func (m *RuntimeMetrics) jsonMetricsToBatch() []byte {
metrics := make([]models.Metrics, 0, len(m.RuntimeMemstats)+2)
for k, v := range m.RuntimeMemstats {
Expand Down Expand Up @@ -147,6 +157,7 @@ func (m *RuntimeMetrics) jsonMetricsToBatch() []byte {
return out
}

// Функция для отправление на сервер по одной метрике за запрос.
func SendMetrics(res []byte, hash, hostpath string) error {
url := strings.Join([]string{"http:/", hostpath, "updates/"}, "/")

Expand Down Expand Up @@ -177,6 +188,7 @@ func SendMetrics(res []byte, hash, hostpath string) error {
return nil
}

// Функция которая добавляет и сжимает метрики для последующей отправки в канал.
func (m *RuntimeMetrics) NewСollect(ctx context.Context, cancel context.CancelFunc, jobs chan []byte) {
for {
select {
Expand All @@ -200,6 +212,7 @@ func (m *RuntimeMetrics) NewСollect(ctx context.Context, cancel context.CancelF
}
}

// Функция которая добавляет и сжимает метрики для последующей отправки в канал.
func (m *RuntimeMetrics) NewСollectMetricGopsutil(ctx context.Context, cancel context.CancelFunc, jobs chan []byte) {
for {
select {
Expand All @@ -221,6 +234,7 @@ func (m *RuntimeMetrics) NewСollectMetricGopsutil(ctx context.Context, cancel c
}
}

// Функция для сжатия данных.
func gzipCompress(data []byte) ([]byte, error) {
var buf bytes.Buffer

Expand All @@ -239,6 +253,7 @@ func gzipCompress(data []byte) ([]byte, error) {
return buf.Bytes(), err
}

// Функция для отправки метрик на сервер.
func SendMetricsGor(jobs <-chan []byte, runAddr, secretKey string) error {
for j := range jobs {

Expand Down
2 changes: 2 additions & 0 deletions internal/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package models

import "time"

// Структура для одной метрики
type Metrics struct {
ID string `json:"id"` // имя метрики
MType string `json:"type"` // параметр, принимающий значение gauge или counter
Delta *int64 `json:"delta,omitempty"` // значение метрики в случае передачи counter
Value *float64 `json:"value,omitempty"` // значение метрики в случае передачи gauge
}

// Время подключение к серверу
var TimeConnect []time.Duration = []time.Duration{1 * time.Second, 3 * time.Second, 5 * time.Second}
10 changes: 10 additions & 0 deletions internal/server/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,21 @@ import (
"go.uber.org/zap"
)

// Структура с бд, которую используют хэндеры.
type MetricHandlerDB struct {
Storage storage.Repository
pgDB *storage.PostgresDB
}

// Инициализация структуры MetricHandlerDB.
func MetricHandlerNew(s storage.Repository, pgDB *storage.PostgresDB) *MetricHandlerDB {
return &MetricHandlerDB{
Storage: s,
pgDB: pgDB,
}
}

// Метод для получения всех метрик.
func (m *MetricHandlerDB) GetAllMetrics(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {

Expand Down Expand Up @@ -60,6 +63,7 @@ func (m *MetricHandlerDB) GetAllMetrics(ctx context.Context, log *zap.Logger) ht

}

// Метод для получения одной метрики.
func (m *MetricHandlerDB) GetNowValueMetrics(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
Expand Down Expand Up @@ -97,6 +101,7 @@ func (m *MetricHandlerDB) GetNowValueMetrics(ctx context.Context, log *zap.Logge

}

// Метод для обновления метрик.
func (m *MetricHandlerDB) UpdateNewMetrics(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
Expand Down Expand Up @@ -147,6 +152,7 @@ func (m *MetricHandlerDB) UpdateNewMetrics(ctx context.Context, log *zap.Logger)
}
}

// Метод для добавления метрики, который использует json формат.
func (m *MetricHandlerDB) AddValueMetricsToJSON(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {

Expand Down Expand Up @@ -199,6 +205,8 @@ func (m *MetricHandlerDB) AddValueMetricsToJSON(ctx context.Context, log *zap.Lo
res.Write(response)
}
}

// Метод для обновления метрик, который использует json формат.
func (m *MetricHandlerDB) NewMetricsToJSON(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
Expand Down Expand Up @@ -263,6 +271,7 @@ func (m *MetricHandlerDB) NewMetricsToJSON(ctx context.Context, log *zap.Logger)
}
}

// Метод для проверки соединения бд.
func (m *MetricHandlerDB) PingDBConnect(ctx context.Context, log *zap.Logger) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
Expand All @@ -280,6 +289,7 @@ func (m *MetricHandlerDB) PingDBConnect(ctx context.Context, log *zap.Logger) ht
}
}

// Метод для обновления метрик, котрый использует пакеты.
func (m *MetricHandlerDB) UpdateNewMetricsBatch(ctx context.Context, log *zap.Logger, keySecret string) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {

Expand Down
40 changes: 40 additions & 0 deletions internal/server/handlers/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/Zagir2000/alert/internal/server/storage"
"github.com/d5/tengo/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)

func TestMetricHandler_MainPage(t *testing.T) {
Expand Down Expand Up @@ -75,3 +76,42 @@ func TestMetricHandler_MainPage(t *testing.T) {
})
}
}

func Example() {
//инициализируем логер
log, _ := logger.InitializeLogger("info")

ctx := context.Background()
//папка с миграциями
migrationsDir := "migrations"
//значение, указывающее, следует ли загружать ранее сохраненные значения из указанного файла при запуске сервера
restore := true
//time interval according to which the current server servers are kept on disk
//интервал времени, в течение которого текущие серверы сервера хранятся на диске
storeIntervall := 300
databaseDsn := "postgres://postgres:123456@localhost/metrics?sslmode=disable"
memStorageInterface, postgresDB, err := storage.NewStorage(ctx, migrationsDir, log, migrationsDir, restore, storeIntervall, databaseDsn)
if err != nil {
log.Fatal("Error in create storage", zap.Error(err))
}
if postgresDB != nil {
defer postgresDB.Close()
}
newHandStruct := MetricHandlerNew(memStorageInterface, postgresDB)
// Выполняем операцию получения метрик.
newHandStruct.GetAllMetrics(ctx, log)
// Выполняем операцию добавления метрики, который использует json формат.
newHandStruct.AddValueMetricsToJSON(ctx, log)
// Выполняем операцию получения метрик.
newHandStruct.GetNowValueMetrics(ctx, log)
// Выполняем операцию добавления метрик, который использует json формат.
newHandStruct.NewMetricsToJSON(ctx, log)
// Выполняем операцию проверки соединения базы данных.
newHandStruct.PingDBConnect(ctx, log)
// Выполняем операцию обновления метрики.
newHandStruct.UpdateNewMetrics(ctx, log)
//Ключ для подписи хэша
key := "secret"
// Выполняем операцию обновления метрик.
newHandStruct.UpdateNewMetricsBatch(ctx, log, key)
}
1 change: 1 addition & 0 deletions internal/server/handlers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"go.uber.org/zap"
)

// Роутер, который реализует все методы API.
func Router(ctx context.Context, log *zap.Logger, newHandStruct *MetricHandlerDB, keySecret string) chi.Router {
r := chi.NewRouter()
r.Use((logger.WithLogging(log)))
Expand Down
1 change: 1 addition & 0 deletions internal/server/hash/checkhash.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"hash"
)

// Проверка хэша при получении запроса
func CheckHash(data []byte, secretKey, checksum string, hashNew func() hash.Hash) error {
secretKeyToByte := []byte(secretKey)
h := hmac.New(hashNew, secretKeyToByte)
Expand Down
11 changes: 11 additions & 0 deletions internal/server/storage/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ type PostgresDB struct {
rw sync.RWMutex
}

// Проверка соденинения с базой данных.
func (pgdb *PostgresDB) PingDB(ctx context.Context) error {
err := pgdb.pool.Ping(ctx)
return err
}

// Инициализация базы данных и применение миграцией.
func InitDB(configDB string, log *zap.Logger, migratePath string) (*PostgresDB, error) {
err := runMigrations(configDB, migratePath)
if err != nil {
Expand All @@ -53,6 +55,7 @@ func InitDB(configDB string, log *zap.Logger, migratePath string) (*PostgresDB,
return nil, fmt.Errorf("failed to create a connection pool: %w", err)
}

// Функция применение миграций.
func runMigrations(dsn string, migratePath string) error {
m, err := migrate.New(fmt.Sprintf("file://%s", migratePath), dsn)
if err != nil {
Expand All @@ -66,10 +69,12 @@ func runMigrations(dsn string, migratePath string) error {
return nil
}

// Закрываем соедиение с бд.
func (pgdb *PostgresDB) Close() {
pgdb.pool.Close()
}

// Добавляем метрику gauge в бд.
func (pgdb *PostgresDB) AddGaugeValue(ctx context.Context, name string, value float64) error {
pgdb.rw.Lock()
defer pgdb.rw.Unlock()
Expand All @@ -87,6 +92,7 @@ func (pgdb *PostgresDB) AddGaugeValue(ctx context.Context, name string, value fl
return tx.Commit(ctx)
}

// Добавляем метрику counter в бд.
func (pgdb *PostgresDB) AddCounterValue(ctx context.Context, name string, value int64) error {
pgdb.rw.Lock()
defer pgdb.rw.Unlock()
Expand All @@ -104,6 +110,7 @@ func (pgdb *PostgresDB) AddCounterValue(ctx context.Context, name string, value
return tx.Commit(ctx)
}

// Получаем метрику gauge из бд.
func (pgdb *PostgresDB) GetGauge(ctx context.Context, name string) (float64, bool) {
var value float64
row := pgdb.pool.QueryRow(ctx,
Expand All @@ -118,6 +125,7 @@ func (pgdb *PostgresDB) GetGauge(ctx context.Context, name string) (float64, boo
return value, true
}

// Получаем метрику counter из бд.
func (pgdb *PostgresDB) GetCounter(ctx context.Context, name string) (int64, bool) {
var value int64
row := pgdb.pool.QueryRow(ctx,
Expand All @@ -131,6 +139,7 @@ func (pgdb *PostgresDB) GetCounter(ctx context.Context, name string) (int64, boo
return value, true
}

// Получаем все gauge метрики из бд.
func (pgdb *PostgresDB) GetAllGaugeValues(ctx context.Context) map[string]float64 {
gaugeMetrics := make(map[string]float64)
var nameValue string
Expand Down Expand Up @@ -158,6 +167,7 @@ func (pgdb *PostgresDB) GetAllGaugeValues(ctx context.Context) map[string]float6
return gaugeMetrics
}

// Получаем все counter метрики из бд.
func (pgdb *PostgresDB) GetAllCounterValues(ctx context.Context) map[string]int64 {
counterMetrics := make(map[string]int64)
var nameValue string
Expand Down Expand Up @@ -185,6 +195,7 @@ func (pgdb *PostgresDB) GetAllCounterValues(ctx context.Context) map[string]int6
return counterMetrics
}

// Добавляем все метрики в бд.
func (pgdb *PostgresDB) AddAllValue(ctx context.Context, metrics []models.Metrics) error {
pgdb.rw.Lock()
defer pgdb.rw.Unlock()
Expand Down
6 changes: 6 additions & 0 deletions internal/server/storage/filestorage.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Consumer struct {
decoder *json.Decoder
}

// Функция для создания файла
func NewProducer(fileName string) (*Producer, error) {
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
Expand All @@ -28,6 +29,7 @@ func NewProducer(fileName string) (*Producer, error) {
}, nil
}

// Функция для записи в json файл
func (p *Producer) WriteMetrics(metricGauge *memStorage) error {
err := p.encoder.Encode(&metricGauge)
if err != nil {
Expand All @@ -37,6 +39,7 @@ func (p *Producer) WriteMetrics(metricGauge *memStorage) error {
return nil
}

// Функция для создания файла
func NewConsumer(fileName string) (*Consumer, error) {
file, err := os.OpenFile(fileName, os.O_RDONLY|os.O_CREATE, 0666)
if err != nil {
Expand All @@ -45,6 +48,7 @@ func NewConsumer(fileName string) (*Consumer, error) {
return &Consumer{file: file, decoder: json.NewDecoder(file)}, nil
}

// Функция для чтения из файла
func (c *Consumer) ReadMetrics() (*memStorage, error) {
var metricsGaugeAndCounter memStorage
if err := c.decoder.Decode(&metricsGaugeAndCounter); err != nil {
Expand All @@ -61,6 +65,7 @@ func (p *Producer) Close() error {
return p.file.Close()
}

// Функция для сохранения метрик в json файл
func MetricsSaveJSON(fname string, m *memStorage) error {
producer, err := NewProducer(fname)
if err != nil {
Expand All @@ -78,6 +83,7 @@ func MetricsSaveJSON(fname string, m *memStorage) error {
return nil
}

// Функция для загрузки метрик из json файл
func MetricsLoadJSON(fname string, m *memStorage) error {
if _, err := os.Stat(fname); os.IsNotExist(err) {
return nil
Expand Down
Loading

0 comments on commit a464cf0

Please sign in to comment.