forked from mtusi2026/mtusi2026lab6
Compare commits
16
Commits
6bc501ca3e
...
56496cfd03
@@ -72,6 +72,13 @@ func main() {
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
registration, err := postgres.ObservePool(pool)
|
||||
if err != nil {
|
||||
slog.Warn("Не удалось зарегистрировать метрики пула", "error", err)
|
||||
} else {
|
||||
defer registration.Unregister()
|
||||
}
|
||||
|
||||
store := postgres.New(pool)
|
||||
|
||||
objectStorage, err := s3store.New(ctx, s3store.Config{
|
||||
|
||||
@@ -81,6 +81,13 @@ func main() {
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
registration, err := postgres.ObservePool(pool)
|
||||
if err != nil {
|
||||
slog.Warn("Не удалось зарегистрировать метрики пула", "error", err)
|
||||
} else {
|
||||
defer registration.Unregister()
|
||||
}
|
||||
|
||||
store := postgres.New(pool)
|
||||
|
||||
rabbitPub, err := broker.NewRabbitPublisher(cfg.RabbitMQURL)
|
||||
|
||||
+45
-11
@@ -11,6 +11,9 @@ import (
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/config"
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
@@ -56,6 +59,13 @@ func main() {
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
registration, err := postgres.ObservePool(pool)
|
||||
if err != nil {
|
||||
slog.Warn("Не удалось зарегистрировать метрики пула", "error", err)
|
||||
} else {
|
||||
defer registration.Unregister()
|
||||
}
|
||||
|
||||
store := postgres.New(pool)
|
||||
objectStorage, err := s3store.New(ctx, s3store.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
@@ -112,6 +122,7 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
defer signal.Stop(quit)
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -122,18 +133,41 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
|
||||
if !ok {
|
||||
return context.Canceled // Канал закрыт (соединение разорвано)
|
||||
}
|
||||
var msg domain.JobMessage
|
||||
if err := json.Unmarshal(d.Body, &msg); err != nil {
|
||||
slog.Error("Worker получил битое сообщение", "error", err)
|
||||
_ = d.Nack(false, false)
|
||||
continue
|
||||
}
|
||||
if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil {
|
||||
slog.Error("Ошибка обработки задачи", "attachment_id", msg.AttachmentID, "error", err)
|
||||
_ = d.Nack(false, true)
|
||||
} else {
|
||||
_ = d.Ack(false)
|
||||
if err := consume(ctx, d, pipeline); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func consume(ctx context.Context, d amqp.Delivery, pipeline *worker.Pipeline) (ackErr error) {
|
||||
headers := make(map[string]string, 2)
|
||||
for _, key := range []string{"traceparent", "tracestate"} {
|
||||
if value, ok := d.Headers[key].(string); ok {
|
||||
headers[key] = value
|
||||
}
|
||||
}
|
||||
ctx, span := telemetry.Tracer("worker").Start(telemetry.ExtractTrace(ctx, headers),
|
||||
"attachments.process process", trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.destination.name", "attachments.process")))
|
||||
defer func() {
|
||||
if ackErr != nil {
|
||||
span.SetStatus(codes.Error, "ошибка подтверждения доставки")
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
var msg domain.JobMessage
|
||||
if err := json.Unmarshal(d.Body, &msg); err != nil {
|
||||
span.SetStatus(codes.Error, "повреждённое сообщение")
|
||||
slog.ErrorContext(ctx, "Неверный JSON задания", "event", "job.invalid")
|
||||
return d.Nack(false, false)
|
||||
}
|
||||
if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil {
|
||||
span.SetStatus(codes.Error, "ошибка обработки")
|
||||
slog.ErrorContext(ctx, "Повторная доставка задания", "event", "job.requeue")
|
||||
return d.Nack(false, true)
|
||||
}
|
||||
return d.Ack(false)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ require (
|
||||
require (
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
@@ -82,6 +83,7 @@ require (
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.9.1 // indirect
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
|
||||
@@ -31,6 +31,8 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
@@ -179,6 +181,8 @@ go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNR
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4=
|
||||
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.72.0 h1:Vgm7vrC26vvecffpDcy2UINqBvASUg5qkfZle3Yrkug=
|
||||
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.72.0/go.mod h1:zgCChxie/dA3qG7IgZGswax6voxkOR4+33msLT/RgNg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type Publisher interface {
|
||||
@@ -15,11 +20,10 @@ type Publisher interface {
|
||||
}
|
||||
|
||||
type RabbitPublisher struct {
|
||||
url string
|
||||
mu sync.Mutex
|
||||
conn *amqp.Connection
|
||||
ch *amqp.Channel
|
||||
confirms chan amqp.Confirmation
|
||||
url string
|
||||
mu sync.Mutex
|
||||
conn *amqp.Connection
|
||||
ch *amqp.Channel
|
||||
}
|
||||
|
||||
func NewRabbitPublisher(url string) (*RabbitPublisher, error) {
|
||||
@@ -45,7 +49,6 @@ func (p *RabbitPublisher) connect() error {
|
||||
if err := p.ch.Confirm(false); err != nil {
|
||||
return fmt.Errorf("включение режима confirm: %w", err)
|
||||
}
|
||||
p.confirms = p.ch.NotifyPublish(make(chan amqp.Confirmation, 1))
|
||||
|
||||
err = p.ch.ExchangeDeclare("attachments", "direct", true, false, false, false, nil)
|
||||
if err != nil {
|
||||
@@ -65,7 +68,19 @@ func (p *RabbitPublisher) connect() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) error {
|
||||
func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) (publishErr error) {
|
||||
ctx, span := telemetry.Tracer("broker").Start(ctx, "attachments publish",
|
||||
trace.WithSpanKind(trace.SpanKindProducer), trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.destination.name", "attachments"),
|
||||
))
|
||||
defer func() {
|
||||
if publishErr != nil {
|
||||
span.SetStatus(codes.Error, "публикация не подтверждена")
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
@@ -75,26 +90,31 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [
|
||||
}
|
||||
}
|
||||
|
||||
err := p.ch.PublishWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
|
||||
headers := amqp.Table{}
|
||||
for key, value := range telemetry.TraceHeaders(ctx) {
|
||||
headers[key] = value
|
||||
}
|
||||
confirmation, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
|
||||
Headers: headers,
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
Body: body,
|
||||
Timestamp: time.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
select {
|
||||
case confirm := <-p.confirms:
|
||||
if !confirm.Ack {
|
||||
return fmt.Errorf("сообщение отклонено брокером")
|
||||
}
|
||||
return nil
|
||||
case <-time.After(5 * time.Second):
|
||||
return fmt.Errorf("таймаут ожидания подтверждения от rabbitmq")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
acked, err := confirmation.WaitContext(waitCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ожидание подтверждения RabbitMQ: %w", err)
|
||||
}
|
||||
if !acked {
|
||||
return fmt.Errorf("сообщение отклонено брокером")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *RabbitPublisher) Close() error {
|
||||
|
||||
@@ -22,6 +22,7 @@ type OutboxEntry struct {
|
||||
AggregateID string
|
||||
EventType string
|
||||
Payload []byte
|
||||
Headers map[string]string
|
||||
CreatedAt time.Time
|
||||
PublishedAt *time.Time
|
||||
Attempts int
|
||||
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type HealthCheck func(ctx context.Context) error
|
||||
@@ -33,12 +35,16 @@ func (h *HealthHandler) Live(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(c *gin.Context) {
|
||||
ctx, span := telemetry.Tracer("httpapi").Start(c.Request.Context(), "health.ready")
|
||||
defer span.End()
|
||||
|
||||
if h.ready != nil && !h.ready.Load() {
|
||||
span.SetStatus(codes.Error, "shutting down")
|
||||
respondError(c, &domain.UnavailableError{Reason: "shutting down"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
for _, check := range h.checks {
|
||||
@@ -46,6 +52,7 @@ func (h *HealthHandler) Ready(c *gin.Context) {
|
||||
continue
|
||||
}
|
||||
if err := check(ctx); err != nil {
|
||||
span.SetStatus(codes.Error, "зависимость недоступна")
|
||||
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Logging записывает результат запроса с шаблоном маршрута и контекстом серверного спана.
|
||||
func Logging() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unknown"
|
||||
}
|
||||
status := c.Writer.Status()
|
||||
level := slog.LevelInfo
|
||||
if status >= 500 {
|
||||
level = slog.LevelError
|
||||
}
|
||||
slog.LogAttrs(c.Request.Context(), level, "HTTP-запрос завершён",
|
||||
slog.String("instance_id", GetInstanceID()),
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("request_id", GetRequestID(c)),
|
||||
slog.String("http.request.method", c.Request.Method),
|
||||
slog.String("http.route", route),
|
||||
slog.Int("http.response.status_code", status),
|
||||
slog.Float64("duration_seconds", time.Since(start).Seconds()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/httpapi/handler"
|
||||
@@ -20,12 +23,19 @@ func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
gin.EnableJsonDecoderDisallowUnknownFields()
|
||||
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger())
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(middleware.RequestID())
|
||||
r.Use(middleware.Instance())
|
||||
r.Use(middleware.Metrics())
|
||||
r.Use(middleware.OTel())
|
||||
r.Use(middleware.Metrics())
|
||||
r.Use(middleware.Logging())
|
||||
r.Use(gin.CustomRecoveryWithWriter(nil, func(c *gin.Context, err any) {
|
||||
slog.Error("Паника при обработке HTTP-запроса",
|
||||
"panic", err,
|
||||
"http.route", c.FullPath(),
|
||||
"request_id", middleware.GetRequestID(c),
|
||||
)
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
}))
|
||||
|
||||
r.GET("/health/live", h.Health.Live)
|
||||
r.GET("/health/ready", h.Health.Ready)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"high-loud-apps-labs/internal/broker"
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type Publisher struct {
|
||||
@@ -54,7 +55,7 @@ func (p *Publisher) tick(ctx context.Context) {
|
||||
|
||||
var successIDs []string
|
||||
for _, e := range entries {
|
||||
err := p.broker.Publish(ctx, "process", e.Payload)
|
||||
err := p.broker.Publish(telemetry.ExtractTrace(ctx, e.Headers), "process", e.Payload)
|
||||
if err != nil {
|
||||
log.Printf("outbox: ошибка публикации %s: %v", e.ID, err)
|
||||
break // Прерываем пачку
|
||||
|
||||
@@ -108,7 +108,6 @@ func (s *AttachmentService) Upload(
|
||||
sha := sha256.Sum256(buf)
|
||||
id := uuid.NewString()
|
||||
stagingKey := "staging/" + id
|
||||
now := time.Now().UTC()
|
||||
|
||||
a := &domain.Attachment{
|
||||
ID: id,
|
||||
@@ -122,8 +121,6 @@ func (s *AttachmentService) Upload(
|
||||
Status: domain.AttachmentStatusQueued,
|
||||
StagingKey: stagingKey,
|
||||
PipelineVersion: 1,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := s.storage.Put(ctx, stagingKey, bytes.NewReader(buf), int64(len(buf)), contentType); err != nil {
|
||||
@@ -140,6 +137,8 @@ func (s *AttachmentService) Upload(
|
||||
}
|
||||
|
||||
err = s.tx.WithTx(ctx, func(tx domain.Tx) error {
|
||||
a.CreatedAt = time.Now().UTC()
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
if err := s.attachments.CreateInTx(ctx, tx, a); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -7,8 +7,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
const advisoryLockKey int64 = 0x4D5455534904
|
||||
@@ -20,6 +23,7 @@ type Reconciler struct {
|
||||
pool *pgxpool.Pool
|
||||
gracePeriod time.Duration
|
||||
batchSize int
|
||||
metrics *reconcilerMetrics
|
||||
}
|
||||
|
||||
func NewReconciler(
|
||||
@@ -39,6 +43,7 @@ func NewReconciler(
|
||||
pool: pool,
|
||||
gracePeriod: gracePeriod,
|
||||
batchSize: 100,
|
||||
metrics: newReconcilerMetrics(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +51,13 @@ func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
||||
if interval <= 0 {
|
||||
interval = 5 * time.Minute
|
||||
}
|
||||
registration, err := r.metrics.observeLeader()
|
||||
if err != nil {
|
||||
log.Printf("reconciler: ошибка регистрации метрики лидерства: %v", err)
|
||||
} else {
|
||||
defer registration.Unregister()
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -64,15 +76,23 @@ func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
||||
}
|
||||
|
||||
func (r *Reconciler) tick(ctx context.Context) {
|
||||
ctx, span := telemetry.Tracer("reconciler").Start(ctx, "reconciler.tick")
|
||||
defer span.End()
|
||||
|
||||
acquired, release, err := r.acquireLock(ctx)
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка получения блокировки: %v", err)
|
||||
return
|
||||
}
|
||||
if !acquired {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
r.metrics.leader.Store(true)
|
||||
defer func() {
|
||||
release()
|
||||
r.metrics.leader.Store(false)
|
||||
}()
|
||||
|
||||
leasesReset := r.sweepExpiredLeases(ctx)
|
||||
stagingDeleted := r.sweepStaging(ctx)
|
||||
@@ -100,9 +120,10 @@ func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
||||
}
|
||||
|
||||
release := func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
unlockCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка снятия блокировки: %v", err)
|
||||
}
|
||||
conn.Release()
|
||||
@@ -111,15 +132,21 @@ func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
||||
}
|
||||
|
||||
func (r *Reconciler) sweepExpiredLeases(ctx context.Context) int {
|
||||
ctx, span := telemetry.Tracer("reconciler").Start(ctx, "reconciler.leases")
|
||||
defer span.End()
|
||||
|
||||
expired, err := r.attachments.ListExpiredLeases(ctx, r.batchSize)
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка получения истёкших аренд: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
r.metrics.stale.Add(ctx, int64(len(expired)))
|
||||
recovered := 0
|
||||
for _, a := range expired {
|
||||
if err := r.attachments.ResetLease(ctx, a.ID); err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка сброса аренды для %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
@@ -137,18 +164,24 @@ func (r *Reconciler) sweepExpiredLeases(ctx context.Context) int {
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка постановки в очередь восстановленной задачи %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
recovered++
|
||||
}
|
||||
r.metrics.recovered.Add(ctx, int64(recovered))
|
||||
return recovered
|
||||
}
|
||||
|
||||
// Чистим staging в S3 для готовых задач
|
||||
func (r *Reconciler) sweepStaging(ctx context.Context) int {
|
||||
ctx, span := telemetry.Tracer("reconciler").Start(ctx, "reconciler.staging")
|
||||
defer span.End()
|
||||
|
||||
toCleanup, err := r.attachments.ListStagingToCleanup(ctx, r.batchSize)
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка получения списка staging для очистки: %v", err)
|
||||
return 0
|
||||
}
|
||||
@@ -156,10 +189,12 @@ func (r *Reconciler) sweepStaging(ctx context.Context) int {
|
||||
deleted := 0
|
||||
for _, a := range toCleanup {
|
||||
if err := r.storage.Delete(ctx, a.StagingKey); err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка удаления объекта staging %s: %v", a.StagingKey, err)
|
||||
continue
|
||||
}
|
||||
if err := r.attachments.ClearStagingKey(ctx, a.ID); err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка очистки ключа staging %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
@@ -170,8 +205,12 @@ func (r *Reconciler) sweepStaging(ctx context.Context) int {
|
||||
|
||||
// Удаляем старые сиротские объекты (без записи в БД)
|
||||
func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
ctx, span := telemetry.Tracer("reconciler").Start(ctx, "reconciler.orphans")
|
||||
defer span.End()
|
||||
|
||||
objects, err := r.storage.List(ctx, "chats/")
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка получения списка объектов: %v", err)
|
||||
return 0
|
||||
}
|
||||
@@ -192,6 +231,7 @@ func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
|
||||
existing, err := r.attachments.ExistingKeys(ctx, keys)
|
||||
if err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка получения существующих ключей: %v", err)
|
||||
return 0
|
||||
}
|
||||
@@ -207,6 +247,7 @@ func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
continue
|
||||
}
|
||||
if err := r.storage.Delete(ctx, k); err != nil {
|
||||
trace.SpanFromContext(ctx).SetStatus(codes.Error, "ошибка операции сверщика")
|
||||
log.Printf("reconciler: ошибка удаления сиротского объекта %s: %v", k, err)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type reconcilerMetrics struct {
|
||||
stale metric.Int64Counter
|
||||
recovered metric.Int64Counter
|
||||
leader atomic.Bool
|
||||
}
|
||||
|
||||
func newReconcilerMetrics() *reconcilerMetrics {
|
||||
meter := telemetry.Meter("reconciler")
|
||||
stale, err := meter.Int64Counter("reconciler_stale_leases_total",
|
||||
metric.WithDescription("Число наблюдений просроченных аренд"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
recovered, err := meter.Int64Counter("reconciler_recovered_jobs_total",
|
||||
metric.WithDescription("Число задач после успешного сброса аренды и записи в outbox"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return &reconcilerMetrics{stale: stale, recovered: recovered}
|
||||
}
|
||||
|
||||
func (m *reconcilerMetrics) observeLeader() (metric.Registration, error) {
|
||||
meter := telemetry.Meter("reconciler")
|
||||
gauge, err := meter.Int64ObservableGauge("reconciler_leader",
|
||||
metric.WithDescription("1, пока этот экземпляр держит advisory lock"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
var value int64
|
||||
if m.leader.Load() {
|
||||
value = 1
|
||||
}
|
||||
o.ObserveInt64(gauge, value)
|
||||
return nil
|
||||
}, gauge)
|
||||
}
|
||||
@@ -200,10 +200,10 @@ func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, vers
|
||||
UPDATE attachments
|
||||
SET status = 'processing', locked_until = now() + $2, updated_at = now(), attempts = attempts + 1
|
||||
WHERE id = $1::uuid AND status = 'queued' AND pipeline_version = $3
|
||||
RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type, attempts
|
||||
RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type, attempts, created_at
|
||||
`
|
||||
var a domain.Attachment
|
||||
err := r.pool.QueryRow(ctx, q, id, lease, version).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType, &a.Attempts)
|
||||
err := r.pool.QueryRow(ctx, q, id, lease, version).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType, &a.Attempts, &a.CreatedAt)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
|
||||
@@ -47,6 +47,12 @@ func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
}
|
||||
poolCfg.HealthCheckPeriod = 10 * time.Second
|
||||
|
||||
tracer, err := newPoolTracer()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("метрики пула: %w", err)
|
||||
}
|
||||
poolCfg.ConnConfig.Tracer = tracer
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %w", err)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type OutboxRepo struct {
|
||||
@@ -39,14 +40,17 @@ func (r *OutboxRepo) Enqueue(ctx context.Context, tx domain.Tx, e *domain.Outbox
|
||||
e.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
|
||||
if e.Headers == nil {
|
||||
e.Headers = telemetry.TraceHeaders(ctx)
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO outbox
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8)
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at, headers)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8, $9::jsonb)
|
||||
`
|
||||
if err := tx.Exec(ctx, q,
|
||||
e.ID, e.AggregateType, e.AggregateID, e.EventType,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt, e.Headers,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -66,7 +70,7 @@ func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.Outbox
|
||||
SET attempts = attempts + 1
|
||||
FROM claimed c
|
||||
WHERE o.id = c.id
|
||||
RETURNING o.id, o.aggregate_type, o.aggregate_id, o.event_type, o.payload, o.attempts, o.created_at, o.published_at
|
||||
RETURNING o.id, o.aggregate_type, o.aggregate_id, o.event_type, o.payload, o.attempts, o.created_at, o.published_at, o.headers
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
@@ -79,7 +83,7 @@ func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.Outbox
|
||||
var e domain.OutboxEntry
|
||||
if err := rows.Scan(
|
||||
&e.ID, &e.AggregateType, &e.AggregateID, &e.EventType,
|
||||
&e.Payload, &e.Attempts, &e.CreatedAt, &e.PublishedAt,
|
||||
&e.Payload, &e.Attempts, &e.CreatedAt, &e.PublishedAt, &e.Headers,
|
||||
); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -92,14 +96,17 @@ func (r *OutboxRepo) EnqueueDirect(ctx context.Context, e *domain.OutboxEntry) e
|
||||
if e.ID == "" {
|
||||
e.ID = uuid.NewString()
|
||||
}
|
||||
if e.Headers == nil {
|
||||
e.Headers = telemetry.TraceHeaders(ctx)
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO outbox
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8)
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at, headers)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8, $9::jsonb)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
e.ID, e.AggregateType, e.AggregateID, e.EventType,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt, e.Headers,
|
||||
)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type poolTracer struct {
|
||||
tracer trace.Tracer
|
||||
duration metric.Float64Histogram
|
||||
waiting metric.Int64UpDownCounter
|
||||
}
|
||||
|
||||
func newPoolTracer() (*poolTracer, error) {
|
||||
meter := telemetry.Meter("storage.postgres")
|
||||
duration, err := meter.Float64Histogram("db_pool_acquire_duration_seconds",
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
waiting, err := meter.Int64UpDownCounter("db_pool_waiting",
|
||||
metric.WithDescription("Число незавершённых вызовов Acquire"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &poolTracer{tracer: telemetry.Tracer("storage.postgres"), duration: duration, waiting: waiting}, nil
|
||||
}
|
||||
|
||||
type acquireStartKey struct{}
|
||||
|
||||
func (t *poolTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
ctx, _ = t.tracer.Start(ctx, "postgresql.acquire")
|
||||
t.waiting.Add(ctx, 1)
|
||||
return context.WithValue(ctx, acquireStartKey{}, time.Now())
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||
t.waiting.Add(ctx, -1)
|
||||
t.duration.Record(ctx, time.Since(ctx.Value(acquireStartKey{}).(time.Time)).Seconds())
|
||||
endSpan(ctx, data.Err)
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
// Передаём только известный SQL-глагол, без текста запроса и параметров.
|
||||
op := "QUERY"
|
||||
sql := strings.TrimSpace(data.SQL)
|
||||
if i := strings.IndexAny(sql, " \r\n\t;("); i >= 0 {
|
||||
sql = sql[:i]
|
||||
}
|
||||
switch verb := strings.ToUpper(sql); verb {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "WITH":
|
||||
op = verb
|
||||
}
|
||||
ctx, _ = t.tracer.Start(ctx, "postgresql."+op, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op)))
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
endSpan(ctx, data.Err)
|
||||
}
|
||||
|
||||
func endSpan(ctx context.Context, err error) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "операция PostgreSQL не выполнена")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func ObservePool(pool *pgxpool.Pool) (metric.Registration, error) {
|
||||
meter := telemetry.Meter("storage.postgres")
|
||||
connections, err := meter.Int64ObservableGauge("db_pool_connections")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meter.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
||||
stat := pool.Stat()
|
||||
observe := func(state string, count int32) {
|
||||
observer.ObserveInt64(connections, int64(count), metric.WithAttributes(attribute.String("state", state)))
|
||||
}
|
||||
observe("used", stat.AcquiredConns())
|
||||
observe("idle", stat.IdleConns())
|
||||
observe("max", stat.MaxConns())
|
||||
return nil
|
||||
}, connections)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
func NewClient(url string) (*redis.Client, error) {
|
||||
@@ -22,6 +24,7 @@ func NewClient(url string) (*redis.Client, error) {
|
||||
opt.ConnMaxIdleTime = time.Minute
|
||||
|
||||
client := redis.NewClient(opt)
|
||||
client.AddHook(tracingHook{tracer: telemetry.Tracer("storage.redis")})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type tracingHook struct{ tracer trace.Tracer }
|
||||
|
||||
func (h tracingHook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h tracingHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
return h.run(ctx, cmd.Name(), func(ctx context.Context) error { return next(ctx, cmd) })
|
||||
}
|
||||
}
|
||||
|
||||
func (h tracingHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
return h.run(ctx, "pipeline", func(ctx context.Context) error { return next(ctx, cmds) })
|
||||
}
|
||||
}
|
||||
|
||||
func (h tracingHook) run(ctx context.Context, op string, call func(context.Context) error) error {
|
||||
ctx, span := h.tracer.Start(ctx, "redis."+op, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", op)))
|
||||
defer span.End()
|
||||
err := call(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
span.SetStatus(codes.Error, "операция Redis не выполнена")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package s3
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
@@ -25,10 +27,25 @@ type MinioStorage struct {
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
||||
base, err := minio.DefaultTransport(cfg.UseSSL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Оборачиваем базовый транспорт в otelhttp.
|
||||
// Опция WithSpanNameFormatter задаёт красивое имя спана (s3.PUT, s3.GET),
|
||||
// чтобы в Grafana не смотреть на дефолтное "HTTP PUT".
|
||||
tracedTransport := otelhttp.NewTransport(base,
|
||||
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
|
||||
return "s3." + r.Method
|
||||
}),
|
||||
)
|
||||
|
||||
client, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Transport: tracedTransport,
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Один span на HTTP-попытку MinIO до получения заголовков ответа.
|
||||
type tracingTransport struct {
|
||||
next http.RoundTripper
|
||||
tracer trace.Tracer
|
||||
}
|
||||
|
||||
func (t tracingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
ctx, span := t.tracer.Start(req.Context(), "s3."+req.Method, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("http.request.method", req.Method)))
|
||||
defer span.End()
|
||||
|
||||
resp, err := t.next.RoundTrip(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "ошибка соединения с S3")
|
||||
} else {
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
|
||||
if resp.StatusCode >= 400 {
|
||||
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package telemetry
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// multiHandler — slog.Handler, который дублирует записи во все вложенные handler'ы.
|
||||
@@ -32,6 +34,12 @@ func (m *multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
}
|
||||
|
||||
func (m *multiHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
sc := trace.SpanContextFromContext(ctx)
|
||||
var traceID, spanID string
|
||||
if sc.IsValid() {
|
||||
traceID, spanID = sc.TraceID().String(), sc.SpanID().String()
|
||||
}
|
||||
r.AddAttrs(slog.String("trace_id", traceID), slog.String("span_id", spanID))
|
||||
for _, h := range m.handlers {
|
||||
if !h.Enabled(ctx, r.Level) {
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
)
|
||||
|
||||
// TraceHeaders переносит только W3C Trace Context через границу задания.
|
||||
func TraceHeaders(ctx context.Context) map[string]string {
|
||||
headers := propagation.MapCarrier{}
|
||||
propagation.TraceContext{}.Inject(ctx, headers)
|
||||
return headers
|
||||
}
|
||||
|
||||
func ExtractTrace(ctx context.Context, headers map[string]string) context.Context {
|
||||
return propagation.TraceContext{}.Extract(ctx, propagation.MapCarrier(headers))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func TestOutboxTraceHeaders(t *testing.T) {
|
||||
input := map[string]string{
|
||||
"traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
|
||||
"tracestate": "lab=node1",
|
||||
"baggage": "private=example",
|
||||
}
|
||||
ctx := ExtractTrace(context.Background(), input)
|
||||
got := TraceHeaders(ctx)
|
||||
if len(got) != 2 || got["traceparent"] != input["traceparent"] || got["tracestate"] != input["tracestate"] {
|
||||
t.Fatalf("неожиданные заголовки outbox: %v", got)
|
||||
}
|
||||
for _, headers := range []map[string]string{nil, {"traceparent": "broken"}} {
|
||||
if trace.SpanContextFromContext(ExtractTrace(context.Background(), headers)).IsValid() {
|
||||
t.Fatal("отсутствующий или повреждённый контекст дал валидного родителя")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ type Providers struct {
|
||||
// При OTEL_SDK_DISABLED=true, будут пустые Providers.
|
||||
func Setup(ctx context.Context, cfg SetupConfig) (*Providers, error) {
|
||||
if disabled() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
logger := slog.New(newMultiHandler(slog.NewJSONHandler(os.Stdout, nil))).With("service.name", cfg.ServiceName)
|
||||
return &Providers{Logger: logger}, nil
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ func Setup(ctx context.Context, cfg SetupConfig) (*Providers, error) {
|
||||
logger := slog.New(newMultiHandler(
|
||||
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}),
|
||||
otelslog.NewHandler(cfg.ServiceName, otelslog.WithLoggerProvider(lp)),
|
||||
))
|
||||
)).With("service.name", cfg.ServiceName)
|
||||
|
||||
return &Providers{Tracer: tp, Meter: mp, Logs: lp, Logger: logger}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type jobMetrics struct {
|
||||
processed metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
ready metric.Float64Histogram
|
||||
}
|
||||
|
||||
func newJobMetrics() jobMetrics {
|
||||
meter := telemetry.Meter("worker.pipeline")
|
||||
processed, err := meter.Int64Counter("jobs_processed_total")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
unit := metric.WithUnit("s")
|
||||
duration, err := meter.Float64Histogram("job_processing_duration_seconds", unit,
|
||||
metric.WithExplicitBucketBoundaries(.01, .05, .1, .25, .5, 1, 2, 5, 10, 30, 60))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ready, err := meter.Float64Histogram("end_to_end_ready_seconds", unit,
|
||||
metric.WithExplicitBucketBoundaries(.1, .5, 1, 2, 5, 10, 30, 60, 120, 300, 900, 3600))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return jobMetrics{processed: processed, duration: duration, ready: ready}
|
||||
}
|
||||
|
||||
func (m jobMetrics) recordAttempt(ctx context.Context, start time.Time, outcome string) {
|
||||
attrs := metric.WithAttributes(attribute.String("job.type", domain.OutboxEventProcess), attribute.String("outcome", outcome))
|
||||
m.duration.Record(ctx, time.Since(start).Seconds(), attrs)
|
||||
m.processed.Add(ctx, 1, attrs)
|
||||
|
||||
span := trace.SpanFromContext(ctx)
|
||||
span.SetAttributes(attribute.String("job.outcome", outcome))
|
||||
level := slog.LevelInfo
|
||||
switch outcome {
|
||||
case "failed", "error", "retry":
|
||||
level = slog.LevelWarn
|
||||
span.SetStatus(codes.Error, outcome)
|
||||
}
|
||||
slog.Log(ctx, level, "Попытка обработки завершена", "event", "job.processed", "outcome", outcome)
|
||||
}
|
||||
|
||||
func (m jobMetrics) recordReady(ctx context.Context, createdAt time.Time) {
|
||||
if createdAt.IsZero() {
|
||||
return
|
||||
}
|
||||
m.ready.Record(ctx, max(0, time.Since(createdAt).Seconds()),
|
||||
metric.WithAttributes(attribute.String("job.type", domain.OutboxEventProcess)))
|
||||
}
|
||||
@@ -10,8 +10,12 @@ import (
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/imaging"
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type Pipeline struct {
|
||||
@@ -22,6 +26,7 @@ type Pipeline struct {
|
||||
outbox domain.OutboxRepository
|
||||
lease time.Duration
|
||||
maxRetries int
|
||||
metrics jobMetrics
|
||||
}
|
||||
|
||||
func NewPipeline(
|
||||
@@ -39,57 +44,80 @@ func NewPipeline(
|
||||
outbox: outbox,
|
||||
lease: 5 * time.Minute,
|
||||
maxRetries: 5,
|
||||
metrics: newJobMetrics(),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Pipeline) Process(ctx context.Context, attachmentID string, pipelineVersion int) error {
|
||||
start := time.Now()
|
||||
outcome := "error"
|
||||
defer func() { p.metrics.recordAttempt(ctx, start, outcome) }()
|
||||
|
||||
log.Printf("worker: начало обработки %s (версия пайплайна %d)", attachmentID, pipelineVersion)
|
||||
|
||||
jobCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
tracer := telemetry.Tracer("worker.pipeline")
|
||||
|
||||
// 1. Забираем задачу с проверкой версии
|
||||
a, err := p.jobs.ClaimForProcessing(jobCtx, attachmentID, pipelineVersion, p.lease)
|
||||
claimCtx, claimSpan := tracer.Start(jobCtx, "job.claim")
|
||||
a, err := p.jobs.ClaimForProcessing(claimCtx, attachmentID, pipelineVersion, p.lease)
|
||||
endPipelineSpan(claimSpan, err)
|
||||
if err != nil {
|
||||
return fmt.Errorf("захват задачи: %w", err)
|
||||
}
|
||||
if a == nil {
|
||||
outcome = "skipped"
|
||||
log.Printf("worker: задача %s уже взята, выполнена или версия устарела", attachmentID)
|
||||
return nil // no-op
|
||||
}
|
||||
|
||||
fail := func(err error, permanent bool) error {
|
||||
outcome = p.handleFailure(a, err, permanent)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 2. Скачиваем оригинал из staging
|
||||
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
|
||||
getCtx, getSpan := tracer.Start(jobCtx, "job.s3.get")
|
||||
rc, _, _, err := p.store.Get(getCtx, a.StagingKey)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("скачивание staging: %w", err), false)
|
||||
endPipelineSpan(getSpan, err)
|
||||
return fail(fmt.Errorf("скачивание staging: %w", err), false)
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
buf, err := io.ReadAll(rc)
|
||||
endPipelineSpan(getSpan, err)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("чтение staging: %w", err), false)
|
||||
return fail(fmt.Errorf("чтение staging: %w", err), false)
|
||||
}
|
||||
|
||||
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
|
||||
log.Printf("worker: генерация вариантов для %s", a.ID)
|
||||
_, imageSpan := tracer.Start(jobCtx, "job.image.process")
|
||||
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("генерация thumbnail: %w", err), true)
|
||||
endPipelineSpan(imageSpan, err)
|
||||
return fail(fmt.Errorf("генерация thumbnail: %w", err), true)
|
||||
}
|
||||
|
||||
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("генерация crop: %w", err), true)
|
||||
endPipelineSpan(imageSpan, err)
|
||||
return fail(fmt.Errorf("генерация crop: %w", err), true)
|
||||
}
|
||||
|
||||
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
|
||||
endPipelineSpan(imageSpan, err)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("генерация webp: %w", err), true)
|
||||
return fail(fmt.Errorf("генерация webp: %w", err), true)
|
||||
}
|
||||
|
||||
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
||||
if err := p.store.Put(jobCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("загрузка оригинала: %w", err), false)
|
||||
putCtx, putSpan := tracer.Start(jobCtx, "job.s3.put")
|
||||
if err := p.store.Put(putCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
||||
endPipelineSpan(putSpan, err)
|
||||
return fail(fmt.Errorf("загрузка оригинала: %w", err), false)
|
||||
}
|
||||
|
||||
// 5. Загружаем все сгенерированные варианты в S3
|
||||
@@ -109,27 +137,42 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string, pipelineVer
|
||||
data = webpData
|
||||
}
|
||||
|
||||
if err := p.store.Put(jobCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
|
||||
if err := p.store.Put(putCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
|
||||
endPipelineSpan(putSpan, err)
|
||||
return fail(fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
|
||||
}
|
||||
v.ObjectKey = key
|
||||
}
|
||||
|
||||
putSpan.End()
|
||||
|
||||
// 6. Фиксируем результат в БД (переводим в ready)
|
||||
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
|
||||
completeCtx, completeSpan := tracer.Start(jobCtx, "job.db.complete")
|
||||
ok, err := p.jobs.CompleteJob(completeCtx, a.ID, a.PipelineVersion, variants)
|
||||
endPipelineSpan(completeSpan, err)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("фиксация в БД: %w", err), false)
|
||||
return fail(fmt.Errorf("фиксация в БД: %w", err), false)
|
||||
}
|
||||
if !ok {
|
||||
outcome = "skipped"
|
||||
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
outcome = "ready"
|
||||
p.metrics.recordReady(ctx, a.CreatedAt)
|
||||
log.Printf("worker: успешно завершено %s", a.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bool) error {
|
||||
func endPipelineSpan(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "операция завершилась ошибкой")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bool) string {
|
||||
// Если исчерпаны попытки или ошибка постоянная (например, битый файл)
|
||||
if isPermanent || a.Attempts >= p.maxRetries {
|
||||
reason := domain.JobErrorInternal
|
||||
@@ -142,13 +185,16 @@ func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bo
|
||||
log.Printf("worker: финальная ошибка для %s (попытка %d): %v", a.ID, a.Attempts, err)
|
||||
|
||||
// Используем context.Background(), чтобы запись в БД прошла даже при истекшем jobCtx
|
||||
_ = p.jobs.FailJob(context.Background(), a.ID, reason)
|
||||
_ = p.failedJobs.Record(context.Background(), &domain.FailedJob{
|
||||
updateErr := p.jobs.FailJob(context.Background(), a.ID, reason)
|
||||
recordErr := p.failedJobs.Record(context.Background(), &domain.FailedJob{
|
||||
AttachmentID: a.ID,
|
||||
ReasonCode: reason,
|
||||
Attempts: a.Attempts,
|
||||
})
|
||||
return nil
|
||||
if updateErr != nil || recordErr != nil {
|
||||
return "error"
|
||||
}
|
||||
return "failed"
|
||||
}
|
||||
|
||||
// Временная ошибка - делаем Retry с backoff
|
||||
@@ -159,7 +205,7 @@ func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bo
|
||||
jitter := time.Duration(rand.Intn(1000)) * time.Millisecond
|
||||
nextAt := time.Now().UTC().Add(backoff + jitter)
|
||||
|
||||
_ = p.jobs.ScheduleRetry(context.Background(), a.ID, nextAt, "")
|
||||
scheduleErr := p.jobs.ScheduleRetry(context.Background(), a.ID, nextAt, "")
|
||||
|
||||
// Кладем в Outbox отложенное сообщение
|
||||
payload, _ := json.Marshal(domain.JobMessage{
|
||||
@@ -167,7 +213,7 @@ func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bo
|
||||
PipelineVersion: a.PipelineVersion,
|
||||
Attempt: a.Attempts + 1,
|
||||
})
|
||||
_ = p.outbox.EnqueueDirect(context.Background(), &domain.OutboxEntry{
|
||||
enqueueErr := p.outbox.EnqueueDirect(context.Background(), &domain.OutboxEntry{
|
||||
AggregateType: domain.OutboxAggregateAttachment,
|
||||
AggregateID: a.ID,
|
||||
EventType: domain.OutboxEventProcess,
|
||||
@@ -175,5 +221,8 @@ func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bo
|
||||
CreatedAt: nextAt,
|
||||
})
|
||||
|
||||
return nil
|
||||
if scheduleErr != nil || enqueueErr != nil {
|
||||
return "error"
|
||||
}
|
||||
return "retry"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE outbox ADD COLUMN headers JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE outbox DROP COLUMN headers;
|
||||
@@ -74,6 +74,7 @@ services:
|
||||
RABBITMQ_DEFAULT_PASS: "${RABBITMQ_PASSWORD}"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
|
||||
ports:
|
||||
- "15672:15672"
|
||||
- "5672:5672"
|
||||
@@ -171,6 +172,9 @@ services:
|
||||
image: mtusi-messenger-api:lab3
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: "${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}"
|
||||
OTEL_METRIC_EXPORT_INTERVAL: "${OTEL_METRIC_EXPORT_INTERVAL:-15000}"
|
||||
OTEL_SDK_DISABLED: "${OTEL_SDK_DISABLED:-false}"
|
||||
APP_HOST: "0.0.0.0"
|
||||
APP_PORT: "8080"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
@@ -234,6 +238,9 @@ services:
|
||||
command: ["/worker"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: "${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}"
|
||||
OTEL_METRIC_EXPORT_INTERVAL: "${OTEL_METRIC_EXPORT_INTERVAL:-15000}"
|
||||
OTEL_SDK_DISABLED: "${OTEL_SDK_DISABLED:-false}"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
S3_ENDPOINT: "http://minio:9000"
|
||||
S3_BUCKET: "${S3_BUCKET:-messenger-attachments}"
|
||||
@@ -273,6 +280,9 @@ services:
|
||||
command: ["/reconciler"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: "${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}"
|
||||
OTEL_METRIC_EXPORT_INTERVAL: "${OTEL_METRIC_EXPORT_INTERVAL:-15000}"
|
||||
OTEL_SDK_DISABLED: "${OTEL_SDK_DISABLED:-false}"
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
S3_ENDPOINT: "http://minio:9000"
|
||||
S3_BUCKET: "${S3_BUCKET:-messenger-attachments}"
|
||||
@@ -322,6 +332,83 @@ services:
|
||||
networks:
|
||||
- internal
|
||||
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.16.0
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=7d
|
||||
volumes:
|
||||
- ./infra/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||
- prometheus_data:/prometheus
|
||||
networks:
|
||||
- internal
|
||||
|
||||
opensearch:
|
||||
image: opensearchproject/opensearch:2.19.7
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
discovery.type: single-node
|
||||
node.store.allow_mmap: "false"
|
||||
DISABLE_INSTALL_DEMO_CONFIG: "true"
|
||||
DISABLE_SECURITY_PLUGIN: "true"
|
||||
OPENSEARCH_JAVA_OPTS: "-Xms512m -Xmx512m"
|
||||
volumes:
|
||||
- opensearch_data:/usr/share/opensearch/data
|
||||
networks:
|
||||
- internal
|
||||
|
||||
jaeger:
|
||||
image: jaegertracing/all-in-one:1.76.0
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
COLLECTOR_OTLP_ENABLED: "true"
|
||||
COLLECTOR_OTLP_GRPC_HOST_PORT: "0.0.0.0:4317"
|
||||
SPAN_STORAGE_TYPE: badger
|
||||
BADGER_EPHEMERAL: "false"
|
||||
BADGER_DIRECTORY_VALUE: /tmp/jaeger/data
|
||||
BADGER_DIRECTORY_KEY: /tmp/jaeger/key
|
||||
volumes:
|
||||
- jaeger_data:/tmp
|
||||
networks:
|
||||
- internal
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.135.0
|
||||
restart: unless-stopped
|
||||
command: ["--config=/etc/otelcol-contrib/config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||
depends_on:
|
||||
- jaeger
|
||||
- opensearch
|
||||
networks:
|
||||
- internal
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:13.3.0
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: "${GRAFANA_ADMIN_USER:-admin}"
|
||||
GF_SECURITY_ADMIN_PASSWORD: "${GRAFANA_ADMIN_PASSWORD:-admin}"
|
||||
GF_PLUGINS_PREINSTALL_SYNC: grafana-opensearch-datasource@2.34.7
|
||||
ports:
|
||||
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./infra/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||
depends_on:
|
||||
- prometheus
|
||||
- opensearch
|
||||
- jaeger
|
||||
networks:
|
||||
- internal
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
@@ -343,6 +430,10 @@ volumes:
|
||||
redis_data:
|
||||
minio_data:
|
||||
rabbitmq_data:
|
||||
prometheus_data:
|
||||
opensearch_data:
|
||||
jaeger_data:
|
||||
grafana_data:
|
||||
|
||||
networks:
|
||||
internal:
|
||||
|
||||
@@ -0,0 +1,819 @@
|
||||
{
|
||||
"uid": "messenger",
|
||||
"title": "Мессенджер - наблюдаемость",
|
||||
"schemaVersion": 39,
|
||||
"version": 2,
|
||||
"refresh": "30s",
|
||||
"timezone": "browser",
|
||||
"time": {
|
||||
"from": "now-30m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "timeseries",
|
||||
"title": "RPS к API",
|
||||
"description": "Суммарная частота запросов к бизнес-маршрутам всех реплик.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(http_requests_total{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval]))",
|
||||
"legendFormat": "Запросы",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "Доля ошибок 5xx API",
|
||||
"description": "Ответы 5xx среди запросов к бизнес-маршрутам. При отсутствии трафика доля не определена.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
},
|
||||
"max": 100
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "100 * (sum(rate(http_requests_total{service_name=\"messenger-api\",http_route=~\"/api/.*\",http_response_status_class=\"5xx\"}[$__rate_interval])) or (0 * sum(rate(http_requests_total{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval])))) / (sum(rate(http_requests_total{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval])) > 0)",
|
||||
"legendFormat": "Ошибки 5xx",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "Задержка API - p50, p95, p99",
|
||||
"description": "Перцентили длительности запросов по объединённым бакетам всех реплик.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p50",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p95",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p99",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Глубина очереди RabbitMQ",
|
||||
"description": "Ожидающие доставки и доставленные без подтверждения задания RabbitMQ.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "rabbitmq_detailed_queue_messages{job=\"rabbitmq\",vhost=\"/\",queue=\"attachments.process\"}",
|
||||
"legendFormat": "Всего",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "rabbitmq_detailed_queue_messages_ready{job=\"rabbitmq\",vhost=\"/\",queue=\"attachments.process\"}",
|
||||
"legendFormat": "Ожидают",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "rabbitmq_detailed_queue_messages_unacked{job=\"rabbitmq\",vhost=\"/\",queue=\"attachments.process\"}",
|
||||
"legendFormat": "Без подтверждения",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Возраст первого задания в очереди",
|
||||
"description": "Время с отправки первого ожидающего сообщения. У сообщений, отправленных до добавления timestamp, возраст отсутствует.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "clamp_min(time() - (rabbitmq_detailed_queue_head_message_timestamp{job=\"rabbitmq\",vhost=\"/\",queue=\"attachments.process\"} > 0), 0)",
|
||||
"legendFormat": "Возраст",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "timeseries",
|
||||
"title": "Доступность потребителей RabbitMQ",
|
||||
"description": "Доля времени, когда RabbitMQ мог сразу передать сообщение потребителю.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
},
|
||||
"max": 100
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "100 * rabbitmq_detailed_queue_consumer_capacity{job=\"rabbitmq\",vhost=\"/\",queue=\"attachments.process\"}",
|
||||
"legendFormat": "Доступность",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "timeseries",
|
||||
"title": "Пулы PostgreSQL - занято, свободно, лимит",
|
||||
"description": "Занятые и свободные соединения и лимит каждого пула.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "db_pool_connections{state=\"used\"}",
|
||||
"legendFormat": "Занято · {{service_name}} / {{service_instance_id}}",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "db_pool_connections{state=\"idle\"}",
|
||||
"legendFormat": "Свободно · {{service_name}} / {{service_instance_id}}",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "db_pool_connections{state=\"max\"}",
|
||||
"legendFormat": "Лимит · {{service_name}} / {{service_instance_id}}",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "timeseries",
|
||||
"title": "Ожидание соединений PostgreSQL",
|
||||
"description": "Количество незавершённых попыток получить соединение по экземплярам.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "db_pool_waiting",
|
||||
"legendFormat": "{{service_name}} / {{service_instance_id}}",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "timeseries",
|
||||
"title": "Исходы попыток обработки",
|
||||
"description": "Частота завершённых попыток по исходам.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(jobs_processed_total{outcome=\"ready\"}[$__rate_interval]))",
|
||||
"legendFormat": "Готово",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(jobs_processed_total{outcome=\"failed\"}[$__rate_interval]))",
|
||||
"legendFormat": "Окончательный отказ",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(jobs_processed_total{outcome=\"retry\"}[$__rate_interval]))",
|
||||
"legendFormat": "Повтор",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "D",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(jobs_processed_total{outcome=\"error\"}[$__rate_interval]))",
|
||||
"legendFormat": "Ошибка",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "E",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(jobs_processed_total{outcome=\"skipped\"}[$__rate_interval]))",
|
||||
"legendFormat": "Пропущено",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Длительность обработки - p50, p95, p99",
|
||||
"description": "Перцентили длительности попыток обработки вложений.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(job_processing_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p50",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(job_processing_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p95",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(job_processing_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p99",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "timeseries",
|
||||
"title": "Время до готовности - p50, p95, p99",
|
||||
"description": "Перцентили времени от приёма вложения до фиксации статуса готовности.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"fillOpacity": 12,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(end_to_end_ready_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p50",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(end_to_end_ready_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p95",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(end_to_end_ready_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p99",
|
||||
"range": true,
|
||||
"instant": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "Сбор метрик Prometheus",
|
||||
"type": "stat",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"description": "Текущее состояние опроса Collector и RabbitMQ. При доступном Collector данные API и worker зависят от отправки OTLP приложением.",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"h": 8,
|
||||
"w": 12
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "up{job=\"otel-collector\"}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"legendFormat": "OTel Collector",
|
||||
"instant": true,
|
||||
"range": false,
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "up{job=\"rabbitmq\"}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"legendFormat": "RabbitMQ",
|
||||
"instant": true,
|
||||
"range": false,
|
||||
"editorMode": "code"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"mappings": [
|
||||
{
|
||||
"type": "value",
|
||||
"options": {
|
||||
"0": {
|
||||
"text": "Ошибка сбора",
|
||||
"color": "red",
|
||||
"index": 0
|
||||
},
|
||||
"1": {
|
||||
"text": "Доступен",
|
||||
"color": "green",
|
||||
"index": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"graphMode": "none",
|
||||
"colorMode": "value",
|
||||
"textMode": "value_and_name",
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
type: file
|
||||
allowUiUpdates: false
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,33 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
timeInterval: 15s
|
||||
|
||||
- name: OpenSearch
|
||||
uid: opensearch
|
||||
type: grafana-opensearch-datasource
|
||||
access: proxy
|
||||
url: http://opensearch:9200
|
||||
editable: false
|
||||
jsonData:
|
||||
flavor: opensearch
|
||||
version: "2.19.4"
|
||||
database: messenger-logs*
|
||||
timeField: "@timestamp"
|
||||
logMessageField: body
|
||||
logLevelField: severityText
|
||||
|
||||
- name: Jaeger
|
||||
uid: jaeger
|
||||
type: jaeger
|
||||
access: proxy
|
||||
url: http://jaeger:16686
|
||||
editable: false
|
||||
@@ -0,0 +1,55 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 256
|
||||
spike_limit_mib: 64
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 512
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:9464
|
||||
add_metric_suffixes: false
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
opensearch:
|
||||
http:
|
||||
endpoint: http://opensearch:9200
|
||||
logs_index: messenger-logs
|
||||
sending_queue:
|
||||
enabled: true
|
||||
queue_size: 64
|
||||
num_consumers: 2
|
||||
otlp/jaeger:
|
||||
endpoint: jaeger:4317
|
||||
tls:
|
||||
insecure: true
|
||||
sending_queue:
|
||||
enabled: true
|
||||
queue_size: 64
|
||||
num_consumers: 2
|
||||
|
||||
service:
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [opensearch]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp/jaeger]
|
||||
@@ -0,0 +1,18 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/messenger.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
static_configs:
|
||||
- targets: ["otel-collector:9464"]
|
||||
|
||||
- job_name: rabbitmq
|
||||
metrics_path: /metrics/detailed
|
||||
params:
|
||||
vhost: ["/"]
|
||||
family: [queue_coarse_metrics, queue_metrics]
|
||||
static_configs:
|
||||
- targets: ["rabbitmq:15692"]
|
||||
@@ -0,0 +1,33 @@
|
||||
groups:
|
||||
- name: messenger
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MessengerHighAPIErrorRate
|
||||
expr: |
|
||||
(
|
||||
sum(rate(http_requests_total{service_name="messenger-api",http_route=~"/api/.*",http_response_status_class="5xx"}[5m]))
|
||||
/
|
||||
sum(rate(http_requests_total{service_name="messenger-api",http_route=~"/api/.*"}[5m]))
|
||||
) > 0.05
|
||||
and
|
||||
sum(rate(http_requests_total{service_name="messenger-api",http_route=~"/api/.*"}[5m])) >= 0.2
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Повышенная доля ответов 5xx API"
|
||||
description: "Доля 5xx выше 5% при нагрузке от 0,2 запроса/с за последние 5 минут."
|
||||
runbook: "REPORT.md#высокая-доля-ошибок-api"
|
||||
|
||||
- alert: MessengerGrowingAttachmentQueue
|
||||
expr: |
|
||||
rabbitmq_detailed_queue_messages_ready{job="rabbitmq",vhost="/",queue="attachments.process"} >= 5
|
||||
and
|
||||
deriv(rabbitmq_detailed_queue_messages_ready{job="rabbitmq",vhost="/",queue="attachments.process"}[5m]) > 0
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Растёт очередь обработки вложений"
|
||||
description: "В attachments.process ожидают как минимум 5 заданий и глубина очереди растёт в пятиминутном окне."
|
||||
runbook: "REPORT.md#растущая-очередь-вложений"
|
||||
@@ -0,0 +1 @@
|
||||
[rabbitmq_management,rabbitmq_prometheus].
|
||||
Reference in New Issue
Block a user