Skip to content
This repository has been archived by the owner on Mar 24, 2024. It is now read-only.

Iter 23-24 #10

Merged
merged 24 commits into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ce5d1b5
ref: Use common approach to shutdown agent and server
alkurbatov Apr 10, 2023
2baad00
fix: Change DecryptRequest status code on failure
alkurbatov Apr 10, 2023
1819a36
tests: Implement unit tests for DecryptRequest middleware
alkurbatov Apr 10, 2023
4461470
feat: Implement increment 23
alkurbatov Apr 11, 2023
e770cac
ref: Update golangci-lint and fix new errors
alkurbatov Apr 11, 2023
c0c6e2c
perf: Avoid buffer recreation during Encrypt/Decrypt
alkurbatov Apr 12, 2023
64c6341
feat: Implement support of gRPC API
alkurbatov Apr 15, 2023
10eec4c
feat: Implement Update and Get metric in gRPC API
alkurbatov Apr 15, 2023
999848e
feat: Support batch updates in gRPC API
alkurbatov Apr 15, 2023
4b077c3
tests: Add unit tests for config.LoadFromFile
alkurbatov Apr 15, 2023
af04933
feat: Support gRPC transport in Agent
alkurbatov Apr 16, 2023
e341c94
feat: Implement requests logging for gRPC API
alkurbatov Apr 16, 2023
0caa215
feat: Support requests filtering by subnet in gRPC API
alkurbatov Apr 16, 2023
e432d64
ref: Make it possible to sign/verify signature of arbitrary data
alkurbatov Apr 17, 2023
512f678
feat: Support signature verification in gRPC API
alkurbatov Apr 17, 2023
8aaee76
ref: Include gRPC autogenerated code into git
alkurbatov Apr 17, 2023
f4b9b0b
chore: Update version of autotest binary
alkurbatov Apr 17, 2023
e82752b
fix: Return BadRequest if we failed to decompress request
alkurbatov Apr 17, 2023
7cc41ac
test: Add tests for compression package
alkurbatov Apr 17, 2023
467fe3a
fix: Downgrade golangci-lint as it breaks in CI environment
alkurbatov Apr 17, 2023
446840b
fix: Avoid VCS stamping error when linting files in CI
alkurbatov Apr 17, 2023
7976a9f
tests: Add unit-tests for file backed storage
alkurbatov Apr 17, 2023
3a0d5b9
feat: Return list of updated metrics in response to batch update
alkurbatov Apr 18, 2023
e0c3616
feat (agent): Shutdown client gRPC connection gracefully
alkurbatov Apr 18, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ vendor/
.DS_Store

# Public/private keys for communications encryption
build/keys
build/keys
18 changes: 2 additions & 16 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ linters:
- interfacer
- ireturn
- maligned
- musttag
- nlreturn
- nosnakecase
- rowserrcheck
Expand All @@ -38,6 +39,7 @@ linters:
- varcheck
- varnamelen
- wastedassign
- wrapcheck

# FIXME (alkurbatov): Enable when we add parallelism to the tests.
- paralleltest
Expand All @@ -47,19 +49,3 @@ issues:
- path: '(.+)_test\.go'
linters:
- noctx

- path: '(.+)_mock\.go'
linters:
- wrapcheck

- path: 'internal/compression/.*.go'
linters:
- wrapcheck

- path: 'internal/exporter/exporter.go'
linters:
- wrapcheck

- path: 'internal/handlers/marshal.go'
linters:
- wrapcheck
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ repos:
exclude: ^docs/api

- repo: https://github.com/golangci/golangci-lint
rev: v1.51.2
rev: v1.51.1
hooks:
- id: golangci-lint
34 changes: 26 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ E2E_TEST = test/devopstest
API_DOCS = docs/api
KEY_PATH = build/keys

AGENT_VERSION ?= 0.22.0
SERVER_VERSION ?= 0.22.0
PROTO_SRC = api/proto
PROTO_FILES = health metrics
PROTO_DST = pkg/grpcapi

AGENT_VERSION ?= 0.24.0
SERVER_VERSION ?= 0.24.0

BUILD_DATE ?= $(shell date +%F\ %H:%M:%S)
BUILD_COMMIT ?= $(shell git rev-parse --short HEAD)
Expand All @@ -22,13 +26,27 @@ install-tools: $(E2E_TEST) ## Install additional linters and test tools
$(E2E_TEST):
@echo Installing $@
curl -sSfL \
https://github.com/Yandex-Practicum/go-autotests/releases/download/v0.7.14/devopstest-darwin-amd64 \
https://github.com/Yandex-Practicum/go-autotests/releases/download/v0.9.6/devopstest-darwin-amd64 \
-o $@
@chmod +x $(E2E_TEST)

build: $(COMPONENTS) ## Build whole project
build: proto $(COMPONENTS) ## Build whole project
.PHONY: build

proto: $(PROTO_FILES) ## Generate gRPC protobuf bindings
.PHONY: proto

$(PROTO_FILES): %: $(PROTO_DST)/%

$(PROTO_DST)/%:
protoc \
--proto_path=$(PROTO_SRC) \
--go_out=$(PROTO_DST) \
--go_opt=paths=source_relative \
--go-grpc_out=$(PROTO_DST) \
--go-grpc_opt=paths=source_relative \
$(PROTO_SRC)/$(notdir $@).proto

agent: ## Build agent
go build \
-ldflags "\
Expand All @@ -42,7 +60,7 @@ agent: ## Build agent

server: ## Build metrics server
rm -rf $(API_DOCS)
swag init -g ./internal/handlers/router.go --output $(API_DOCS)
swag init -g ./internal/httpbackend/router.go --output $(API_DOCS)

go build \
-ldflags "\
Expand All @@ -55,7 +73,7 @@ server: ## Build metrics server
.PHONY: server

staticlint: ## Build static lint utility
go build $(CCFLAGS) -o cmd/$@/$@ cmd/$@/*.go
go build -o cmd/$@/$@ cmd/$@/*.go
.PHONY: staticlint

clean: ## Remove build artifacts and downloaded test tools
Expand All @@ -64,12 +82,12 @@ clean: ## Remove build artifacts and downloaded test tools

lint: ## Run linters on the source code
golangci-lint run
./cmd/staticlint/staticlint ./cmd/... ./internal/... ./pkg/...
go list -buildvcs=false ./... | grep -F -v -e docs | xargs ./cmd/staticlint/staticlint
.PHONY: lint

unit-tests: ## Run unit tests
@go test -v -race ./... -coverprofile=coverage.out.tmp -covermode atomic
@cat coverage.out.tmp | grep -v "_mock.go" > coverage.out
@cat coverage.out.tmp | grep -v -E "(_mock|.pb).go" > coverage.out
@go tool cover -html=coverage.out -o coverage.html
@go tool cover -func=coverage.out
.PHONY: unit-tests
Expand Down
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
20. [Инкремент 20 (шифрование агент -> сервер)](./docs/tasks/increment20.md)
21. [Инкремент 21 (конфигурационные файлы)](./docs/tasks/increment21.md)
22. [Инкремент 22 (штатное завершение работы)](./docs/tasks/increment22.md)
23. [Инкремент 23 (блокировка запросов из недоверенной подсети)](./docs/tasks/increment23.md)
24. [Инкремент 24 (gRPC)](./docs/tasks/increment24.md)

## Разработка и тестирование
Для получения полного списка доступных команд выполните:
Expand All @@ -45,6 +47,13 @@ make help
make install-tools
```

#### protoc
Для генерации `gRPC` кода необходимо установить [protoc](https://grpc.io/docs/protoc-installation/), а также плагины для `Go`:
```bash
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
```

#### migrate
Для работы с миграциями БД необходимо установить утилиту [golang-migrate](https://github.com/golang-migrate/migrate):
```bash
Expand Down Expand Up @@ -92,9 +101,12 @@ migrate -database ${DATABASE_DSN} -path ./migrations down -all
(!) Переменные окружения имеют приоритет перед опциями командной строки.

```bash
# Адрес и порт, по которым доступно API сервера:
# Адрес и порт, по которым доступно HTTP API сервера:
export ADDRESS=0.0.0.0:8080

# Адрес и порт, по которым доступно gRPC API сервера:
export GRPC_ADDRESS=0.0.0.0:50051

# Интервал времени в секундах, по истечении которого текущие показания
# сервера сбрасываются на диск (значение 0 — делает запись синхронной):
export STORE_INTERVAL=300s
Expand All @@ -114,6 +126,10 @@ export KEY=
# Ключ должен быть сохранен в PEM формате.
export CRYPTO_KEY=

# Доверенная подсеть в CIDR нотации (по умолчанию не задана).
# Если эта переменная задана, сервер блокирует запросы, отправленные не из доверенной подсети.
export TRUSTED_SUBNET=

# Полный URL для установления соединения с базой (по умолчанию не задан).
# Сервер автоматически запустит все необходимые миграции после установления соединения с базой.
# (!) Поддерживается только Postgres.
Expand Down Expand Up @@ -152,6 +168,9 @@ export CONFIG=
# Адрес и порт сервера, агрегирующего метрики:
export ADDRESS=0.0.0.0:8080

# Тип транспорта используемого для сбора метрик (http или gRPC):
export TRANSPORT=http

# Интервал опроса метрик (в секундах):
export POLL_INTERVAL=2s

Expand Down
7 changes: 7 additions & 0 deletions api/kreya/local.krenv
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"id": "5cf6f40c-e242-418f-a8f3-2cf627269ad0",
"color": "#60A5FA",
"globalContent": {
"grpc_endpoint": "::50051"
}
}
19 changes: 19 additions & 0 deletions api/kreya/metrics-collectors.krproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"id": "1391c613-27e1-4895-9db8-2af74f3edee3",
"importStreams": [
{
"id": "8697db12-5cc2-4fb7-a80b-5579c72e685c",
"name": "grpc-proto",
"importerName": "ProtoFile",
"createMissingOperations": true,
"options": {
"files": [
"../proto"
],
"importPaths": []
}
}
],
"authConfigs": [],
"certificates": []
}
1 change: 1 addition & 0 deletions api/kreya/metrics/collector/v1/Health/Ping-request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
13 changes: 13 additions & 0 deletions api/kreya/metrics/collector/v1/Health/Ping.krop
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"details": {
"methodFqn": "metrics.collector.v1.Health.Ping"
},
"requests": [
{
"location": "Ping-request.json"
}
],
"operationType": "unary",
"invokerName": "grpc",
"importStreamId": "8697db12-5cc2-4fb7-a80b-5579c72e685c"
}
14 changes: 14 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/BatchUpdate-request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"data": [
{
"id": "PollCount",
"mtype": "counter",
"delta": 452
},
{
"id": "Alloc",
"mtype": "gauge",
"value": 568.2049356225625
}
]
}
13 changes: 13 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/BatchUpdate.krop
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"details": {
"methodFqn": "metrics.collector.v1.Metrics.BatchUpdate"
},
"requests": [
{
"location": "BatchUpdate-request.json"
}
],
"operationType": "unary",
"invokerName": "grpc",
"importStreamId": "8697db12-5cc2-4fb7-a80b-5579c72e685c"
}
4 changes: 4 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/Get-request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"id": "MyTest",
"mtype": "gauge"
}
13 changes: 13 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/Get.krop
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"details": {
"methodFqn": "metrics.collector.v1.Metrics.Get"
},
"requests": [
{
"location": "Get-request.json"
}
],
"operationType": "unary",
"invokerName": "grpc",
"importStreamId": "8697db12-5cc2-4fb7-a80b-5579c72e685c"
}
6 changes: 6 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/Update-request.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"id": "MyTest",
"mtype": "gauge",
"delta": "72",
"value": 670.4969946687745
}
13 changes: 13 additions & 0 deletions api/kreya/metrics/collector/v1/Metrics/Update.krop
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"details": {
"methodFqn": "metrics.collector.v1.Metrics.Update"
},
"requests": [
{
"location": "Update-request.json"
}
],
"operationType": "unary",
"invokerName": "grpc",
"importStreamId": "8697db12-5cc2-4fb7-a80b-5579c72e685c"
}
24 changes: 24 additions & 0 deletions api/kreya/metrics/directory.krpref
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"settings": [
{
"options": {
"rest": {
"pathParams": []
}
}
},
{
"environmentId": "5cf6f40c-e242-418f-a8f3-2cf627269ad0",
"options": {
"grpc": {
"endpoint": "http://localhost:50051",
"mode": "grpc",
"disableServerCertificateValidation": true
},
"rest": {
"pathParams": []
}
}
}
]
}
10 changes: 10 additions & 0 deletions api/proto/health.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
syntax = "proto3";

package metrics.collector.v1;
option go_package = "github.com/alkurbatov/metrics-collector/grpcapi";

import "google/protobuf/empty.proto";

service Health {
rpc Ping(google.protobuf.Empty) returns (google.protobuf.Empty);
}
34 changes: 34 additions & 0 deletions api/proto/metrics.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
syntax = "proto3";

package metrics.collector.v1;
option go_package = "github.com/alkurbatov/metrics-collector/grpcapi";

// NB (alkurbatov): The name was intentionally choosen to match the similar structure
// from HTTP API for convenience.
message MetricReq {
string id = 1;
string mtype = 2;
int64 delta = 3;
double value = 4;
string hash = 5;
}

message GetMetricRequest {
string id = 1;
string mtype = 2;
}

message BatchUpdateRequest {
repeated MetricReq data = 1;
}

message BatchUpdateResponse {
repeated MetricReq data = 1;
}

service Metrics {
rpc Update(MetricReq) returns (MetricReq);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше делать типы запросов и ответов разными: UpdateRequest, UpdateResponse, GetResponse.
Так если придется обновить один из типов, изменения удастся внести только в один тип, не затрагивая остальные

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Согласен, спасибо.

rpc BatchUpdate(BatchUpdateRequest) returns (BatchUpdateResponse);

rpc Get(GetMetricRequest) returns (MetricReq);
}
1 change: 1 addition & 0 deletions configs/agent.example.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"address": "localhost:8080",
"transport": "http",
"report_interval": "1s",
"poll_interval": "1s",
"crypto_key": "./build/keys/public.pem",
Expand Down
2 changes: 2 additions & 0 deletions configs/server.example.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
{
"address": "localhost:8080",
"grpc_address": "localhost:8080",
"restore": true,
"store_interval": "1s",
"store_file": "/path/to/file.db",
"database_dsn": "",
"crypto_key": "./build/keys/private.pem",
"trusted_subnet": "192.168.0.0/16",
"debug": true
}
Loading