app

package
v0.0.0-...-94b8695 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2023 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Overview

Package app provides functions to work with main server - metric collector

Index

Examples

Constants

View Source
const (
	DatabaseStorageType = "db"
	MemStorageType      = "memory"
)

Variables

View Source
var ContentTypesForCompress = "application/json; text/html"

type needed compress

Main logger

Functions

func GzipMiddleware

func GzipMiddleware(h http.Handler) http.Handler

func WithLogging

func WithLogging(h http.Handler) http.Handler

Types

type IMetric

type IMetric interface {
	GetName() string
	GetType() string
	GetValue() any
	GetTypeForQuery() string
}

IMetric provides functions to operate with metrics stored in DB

type Server

type Server struct {

	// Address of web server, where app woul be deployed
	// Format - Host[:Port]
	Address string
	// Interval in seconds for backup storage on disk
	StoreInterval int
	// Path to save storage with interval StoreInterval
	FileStoragePath string
	// True if server would restore metrics from backup file
	Restore bool
	// String connection to postgres DB
	// Format - "user=<user> password=<pass> host=<host> port=<port> dbname=<db> sslmode=<true/false>"
	DBConnection string
	// "db" or "memory"
	StorageType string
	// Key for decrypt and encrypt body of requests
	HashKey string
	// True if server would validate hash of all incoming requests
	CheckHash bool
	// True if server accepts encrypted messages from agent
	UseEncryption bool
	// Path to private key RSA
	PrivateKeyPath string
	// Trusted subnet to check clients ip addresses
	TrustedSubnet string
	// http server
	HTTPServer *http.Server
	// Path to file where mem stats will be saved
	MemProfile string
	// Exchange mode
	ExchangeMode string

	// implement GRPC server
	pb.UnimplementedMetricServerServer
	// contains filtered or unexported fields
}

func NewServer

func NewServer(settings *config.ServerFlags) (*Server, error)

NewServer creates app instance

func (*Server) AddMetric deprecated

func (srv *Server) AddMetric(ctx context.Context, metricType string, metricName string, metricValue string) error

AddMetric adds new metric if it doesn't exist, or update existing metric with name metricName

Deprecated: use AddMetricNew

func (*Server) AddMetricNew

func (srv *Server) AddMetricNew(ctx context.Context, m metrics.Metric) error

AddMetricNew adds new metric if it doesn't exist, or update existing metric with name metricName

func (*Server) AddMetricsBatch

func (srv *Server) AddMetricsBatch(ctx context.Context, m []metrics.Metric) error

AddMetricsBatch adds array of new metrics. Behavior is the same as in AddMetricNew

func (*Server) AllMetricsHandle

func (srv *Server) AllMetricsHandle(w http.ResponseWriter, r *http.Request)

AllMetricsHandle godoc @Tags getvalue @Summary Get all metrics @Description Get all metrics with current values @ID getvalue @Accept plain @Produce json @Success 200 {string} string "OK" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/{type}/{name} [get]

Example
client := &http.Client{}
address := "localhost:8080"
url := "http://" + address + "/"

bodyBuffer := new(bytes.Buffer)
request, err := http.NewRequest(http.MethodGet, url, bodyBuffer)
if err != nil {
	fmt.Printf("Error request: %v", err.Error())
	return
}

response, err := client.Do(request)
if err != nil {
	fmt.Printf("Error response: %v", err.Error())
	return
}

defer response.Body.Close()

dataResponse, err := io.ReadAll(response.Body)
if err != nil {
	fmt.Printf("Error reading response body: %v", err.Error())
	return
}

var allmetrics []metrics.Metric
reader := io.NopCloser(bytes.NewReader(dataResponse))
if err := json.NewDecoder(reader).Decode(&allmetrics); err != nil {
	fmt.Print("Error to parse response body")
	return
}

if response.StatusCode != http.StatusOK {
	fmt.Printf("Error response")
	return
}
fmt.Printf("all metrics: %v", allmetrics)
Output:

func (*Server) AsyncSaving

func (srv *Server) AsyncSaving(ctx context.Context)

AsyncSaving backups database to file

func (*Server) CheckHashMiddleware

func (srv *Server) CheckHashMiddleware(h http.Handler) http.Handler

func (*Server) DecryptMiddleware

func (srv *Server) DecryptMiddleware(h http.Handler) http.Handler

func (*Server) GetAllMetricsNew

func (srv *Server) GetAllMetricsNew(ctx context.Context) ([]*metrics.Metric, error)

GetAllMetricsNew returns all existed metrics with current values

func (*Server) GetMetricValue

func (srv *Server) GetMetricValue(ctx context.Context, metricType string, metricName string) (any, error)

GetMetricValue returns current value of metric

func (*Server) GetRequestedValues

func (srv *Server) GetRequestedValues(ctx context.Context, m []metrics.Metric) ([]metrics.Metric, error)

GetRequestedValues returns current values of requested metrics. return only already existed metrics

func (*Server) GetValueHandle

func (srv *Server) GetValueHandle(w http.ResponseWriter, r *http.Request)

GetValueHandle godoc @Tags getvalue @Summary Get value of existed metric @Description Get value of existed metric @ID getvalue @Accept plain @Produce plain @Param type path string true "Metric type" @Param name path string true "Metric name" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/{type}/{name} [get]

func (*Server) GetValueJSONHandle

func (srv *Server) GetValueJSONHandle(w http.ResponseWriter, r *http.Request)

GetValueJSONHandle godoc @Tags getvalue @Summary Get metric value @Description Get metric value @ID getvalueJSON @Accept json @Produce json @Param metric body metrics.Metric true "metric" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/ [get]

func (*Server) Ping

func (srv *Server) Ping(ctx context.Context) error

Ping tests connection to db

func (*Server) PingHandle

func (srv *Server) PingHandle(w http.ResponseWriter, r *http.Request)

PingHandle godoc @Tags checks @Summary Checking db connection @Description Checking db connection @ID checksPing @Accept plain @Produce plain @Success 200 {string} string "OK" @Failure 500 {string} string "Внутренняя ошибка" @Router /ping [get]

Example
client := &http.Client{}
address := "localhost:8080"
url := "http://" + address + "/ping"

bodyBuffer := new(bytes.Buffer)
request, err := http.NewRequest(http.MethodGet, url, bodyBuffer)
if err != nil {
	fmt.Printf("Error request: %v", err.Error())
	return
}

response, err := client.Do(request)
if err != nil {
	fmt.Printf("Error response: %v", err.Error())
	return
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
	fmt.Printf("Error response")
	return
}
Output:

func (*Server) PushMetrics

func (srv *Server) PushMetrics(ctx context.Context, in *pb.PushMetricsRequest) (*pb.PushMetricsResponse, error)

func (*Server) ReadFromFile

func (srv *Server) ReadFromFile() ([]metrics.Metric, error)

ReadFromFile reads all data from file

func (*Server) RestoreValues

func (srv *Server) RestoreValues(ctx context.Context)

RestoreValues restore metrics from file

func (*Server) SaveToFile

func (srv *Server) SaveToFile(ctx context.Context) error

SaveToFile saves metrics to file

func (*Server) StartServer

func (srv *Server) StartServer(ctx context.Context, srvFlags *config.ServerFlags)

func (*Server) StopAsyncSaving

func (srv *Server) StopAsyncSaving()

func (*Server) StopServer

func (srv *Server) StopServer(ctx context.Context)

func (*Server) UpdateBatchJSONHandle

func (srv *Server) UpdateBatchJSONHandle(w http.ResponseWriter, r *http.Request)

UpdateBatchJSONHandle godoc @Tags update @Summary Batch update array of metrics, data in JSON @Description Update existed metric or add new metric from JSON array of metrics @ID updateBatch @Accept json @Produce json @Param metrics body []metrics.Metric true "Array of metrics" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /updates/ [post]

Example
client := &http.Client{}
address := "localhost:8080"
url := "http://" + address + "/updates/"

mval := 34.5
mem := &metrics.Metric{
	ID:    "virtual_memory",
	MType: "gauge",
	Value: &mval,
}
cval := int64(12)
cpu := &metrics.Metric{
	ID:    "cpu",
	MType: "counter",
	Delta: &cval,
}
arr := make([]metrics.Metric, 0)
arr = append(arr, *mem)
arr = append(arr, *cpu)

bodyBuffer := new(bytes.Buffer)
gzb := gzip.NewWriter(bodyBuffer)
json.NewEncoder(gzb).Encode(arr)
err := gzb.Close()
if err != nil {
	fmt.Printf("Error encode request body: %v", err.Error())
	return
}

request, err := http.NewRequest(http.MethodPost, url, bodyBuffer)
if err != nil {
	fmt.Printf("Error request: %v", err.Error())
	return
}

response, err := client.Do(request)
if err != nil {
	fmt.Printf("Error response: %v", err.Error())
	return
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
	fmt.Printf("Error response")
	return
}
Output:

func (*Server) UpdateHandle

func (srv *Server) UpdateHandle(w http.ResponseWriter, r *http.Request)

UpdateHandle godoc @Tags update @Summary Update existed metric or add new metric @Description Update existed metric or add new metric @ID update @Accept plain @Produce plain @Param type path string true "Metric type" @Param name path string true "Metric name" @Param value path number true "Metric value" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /update/{type}/{name}/{value} [post]

func (*Server) UpdateJSONHandle

func (srv *Server) UpdateJSONHandle(w http.ResponseWriter, r *http.Request)

UpdateJSONHandle godoc @Tags update @Summary Update metric, data in JSON @Description Update existed metric or add new metric from JSON data @ID updateJSON @Accept json @Produce json @Param metric body []metrics.Metric true "Array of metrics" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /update/ [post]

func (*Server) ValidateIP

func (srv *Server) ValidateIP(h http.Handler) http.Handler

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL