forked from mtusi2026/mtusi2026lab6
Реализована лабораторная 6 на оценку 4
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Queries are named by operation only. SQL text/args never enter telemetry.
|
||||
type DBTracer struct{}
|
||||
|
||||
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
|
||||
if !trace.SpanContextFromContext(ctx).IsValid() {
|
||||
return ctx
|
||||
}
|
||||
op := "OTHER"
|
||||
f := strings.Fields(d.SQL)
|
||||
if len(f) > 0 {
|
||||
switch strings.ToUpper(f[0]) {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "CREATE", "ALTER":
|
||||
op = strings.ToUpper(f[0])
|
||||
}
|
||||
}
|
||||
c, _ := Span(ctx, "db."+strings.ToLower(op), trace.SpanKindClient, attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
|
||||
return c
|
||||
}
|
||||
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
|
||||
if trace.SpanContextFromContext(ctx).IsValid() {
|
||||
Result(trace.SpanFromContext(ctx), d.Err)
|
||||
}
|
||||
}
|
||||
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
Waiting.Add(1)
|
||||
if trace.SpanContextFromContext(ctx).IsValid() {
|
||||
c, _ := Span(ctx, "db.pool.acquire", trace.SpanKindClient, attribute.String("db.system.name", "postgresql"))
|
||||
return c
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||
Waiting.Add(-1)
|
||||
if trace.SpanContextFromContext(ctx).IsValid() {
|
||||
Result(trace.SpanFromContext(ctx), data.Err)
|
||||
}
|
||||
}
|
||||
|
||||
type RedisHook struct{}
|
||||
|
||||
func (RedisHook) DialHook(next redis.DialHook) redis.DialHook {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) { return next(ctx, network, addr) }
|
||||
}
|
||||
func (RedisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
if !trace.SpanContextFromContext(ctx).IsValid() {
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
c, s := Span(ctx, "redis."+cmd.Name(), trace.SpanKindClient, attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", cmd.Name()))
|
||||
err := next(c, cmd)
|
||||
if err == redis.Nil {
|
||||
s.End()
|
||||
} else {
|
||||
Result(s, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
func (RedisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Monitor(pool *pgxpool.Pool, role string, capacity int) error {
|
||||
m := otel.Meter(Scope)
|
||||
names := []string{"messenger_db_pool_used", "messenger_db_pool_idle", "messenger_db_pool_waiting", "messenger_db_pool_capacity", "messenger_worker_busy", "messenger_worker_capacity", "messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_db_available", "messenger_process_memory_bytes", "messenger_container_memory_bytes", "messenger_container_memory_limit_bytes", "messenger_telemetry_export_errors", "messenger_process_last_observed_seconds"}
|
||||
gauges := map[string]metric.Int64ObservableGauge{}
|
||||
for _, n := range names {
|
||||
g, err := m.Int64ObservableGauge(n)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gauges[n] = g
|
||||
}
|
||||
containerCPU, _ := m.Float64ObservableCounter("messenger_container_cpu", metric.WithUnit("s"))
|
||||
cpu, _ := m.Float64ObservableCounter("messenger_process_cpu", metric.WithUnit("s"))
|
||||
acquired, _ := m.Int64ObservableCounter("messenger_db_pool_acquire_wait")
|
||||
duration, _ := m.Float64ObservableCounter("messenger_db_pool_acquire_wait_duration", metric.WithUnit("s"))
|
||||
instruments := []metric.Observable{cpu, containerCPU, acquired, duration}
|
||||
for _, g := range gauges {
|
||||
instruments = append(instruments, g)
|
||||
}
|
||||
_, err := m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
stat := pool.Stat()
|
||||
observeTime := time.Now().Unix()
|
||||
observe := func(n string, value int64) { o.ObserveInt64(gauges[n], value) }
|
||||
observe("messenger_db_pool_used", int64(stat.AcquiredConns()))
|
||||
observe("messenger_db_pool_idle", int64(stat.IdleConns()))
|
||||
observe("messenger_db_pool_waiting", Waiting.Load())
|
||||
observe("messenger_db_pool_capacity", int64(stat.MaxConns()))
|
||||
o.ObserveInt64(acquired, stat.EmptyAcquireCount())
|
||||
o.ObserveFloat64(duration, stat.EmptyAcquireWaitTime().Seconds())
|
||||
observe("messenger_telemetry_export_errors", ExportErrors.Load())
|
||||
observe("messenger_process_last_observed_seconds", observeTime)
|
||||
if role == "worker" {
|
||||
observe("messenger_worker_busy", Busy.Load())
|
||||
observe("messenger_worker_capacity", int64(capacity))
|
||||
}
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
observe("messenger_process_memory_bytes", int64(mem.Sys))
|
||||
for file, name := range map[string]string{"memory.current": "messenger_container_memory_bytes", "memory.max": "messenger_container_memory_limit_bytes"} {
|
||||
if b, e := os.ReadFile("/sys/fs/cgroup/" + file); e == nil {
|
||||
if n, e := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); e == nil {
|
||||
observe(name, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if raw, e := os.ReadFile("/sys/fs/cgroup/cpu.stat"); e == nil {
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && fields[0] == "usage_usec" {
|
||||
if n, e := strconv.ParseFloat(fields[1], 64); e == nil {
|
||||
o.ObserveFloat64(containerCPU, n/1e6)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var usage syscall.Rusage
|
||||
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
|
||||
o.ObserveFloat64(cpu, float64(usage.Utime.Sec+usage.Stime.Sec)+float64(usage.Utime.Usec+usage.Stime.Usec)/1e6)
|
||||
}
|
||||
if role == "dispatcher" {
|
||||
c, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
var depth, age int64
|
||||
e := pool.QueryRow(c, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(created_at))::bigint,0) FROM attachment_jobs WHERE state='queued'`).Scan(&depth, &age)
|
||||
if e == nil {
|
||||
o.ObserveInt64(gauges["messenger_queue_depth"], depth, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
|
||||
o.ObserveInt64(gauges["messenger_queue_oldest_age_seconds"], age, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
|
||||
observe("messenger_db_available", 1)
|
||||
} else {
|
||||
observe("messenger_db_available", 0)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, instruments...)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// Package telemetry exports bounded, asynchronous OTLP signals without business payloads.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
logglobal "go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const Scope = "mtusi-messenger/telemetry-v1"
|
||||
|
||||
var Service = "messenger-api"
|
||||
var Busy atomic.Int64
|
||||
var Waiting atomic.Int64
|
||||
var ExportErrors atomic.Int64
|
||||
var signals *Signals
|
||||
|
||||
type Signals struct {
|
||||
Requests metric.Int64Counter
|
||||
HTTPDuration metric.Float64Histogram
|
||||
Jobs metric.Int64Counter
|
||||
JobDuration metric.Float64Histogram
|
||||
ReadyDuration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func Start(ctx context.Context, service, instance string) (func(context.Context) error, error) {
|
||||
Service = service
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "lab6-v1"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")}
|
||||
res := resource.NewWithAttributes("https://opentelemetry.io/schemas/1.37.0", attrs...)
|
||||
traceExp, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(2*time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metricExp, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(2*time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logExp, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(2*time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(traceExp, sdktrace.WithMaxQueueSize(256), sdktrace.WithMaxExportBatchSize(64), sdktrace.WithBatchTimeout(500*time.Millisecond), sdktrace.WithExportTimeout(2*time.Second)))
|
||||
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second))))
|
||||
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp, sdklog.WithMaxQueueSize(256), sdklog.WithExportMaxBatchSize(64), sdklog.WithExportInterval(500*time.Millisecond), sdklog.WithExportTimeout(2*time.Second))))
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
logglobal.SetLoggerProvider(lp)
|
||||
// No exporter/network details, payloads or credentials are logged on errors.
|
||||
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
|
||||
meter := otel.Meter(Scope)
|
||||
s := &Signals{}
|
||||
s.Requests, err = meter.Int64Counter("messenger_http_requests")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}
|
||||
s.HTTPDuration, _ = meter.Float64Histogram("messenger_http_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
|
||||
s.Jobs, _ = meter.Int64Counter("messenger_jobs_processed")
|
||||
s.JobDuration, _ = meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
|
||||
s.ReadyDuration, _ = meter.Float64Histogram("messenger_time_to_ready", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.1, .5, 1, 5, 10, 30, 60, 120, 300, 900, 3600, 86400))
|
||||
signals = s
|
||||
return func(c context.Context) error {
|
||||
// Shared deadline bounds shutdown across all signals.
|
||||
a := tp.Shutdown(c)
|
||||
b := mp.Shutdown(c)
|
||||
d := lp.Shutdown(c)
|
||||
if a != nil || b != nil || d != nil {
|
||||
return fmt.Errorf("telemetry shutdown incomplete")
|
||||
}
|
||||
return nil
|
||||
}, nil
|
||||
}
|
||||
func Span(ctx context.Context, name string, kind trace.SpanKind, attrs ...attribute.KeyValue) (context.Context, trace.Span) {
|
||||
return otel.Tracer(Scope).Start(ctx, name, trace.WithSpanKind(kind), trace.WithAttributes(attrs...))
|
||||
}
|
||||
func Result(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "dependency unavailable")
|
||||
span.SetAttributes(attribute.Bool("error", true))
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
func Inject(ctx context.Context) (string, string) {
|
||||
c := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, c)
|
||||
return c.Get("traceparent"), c.Get("tracestate")
|
||||
}
|
||||
func Extract(ctx context.Context, parent, state string) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||
}
|
||||
|
||||
type requestKey struct{}
|
||||
|
||||
func WithRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestKey{}, id)
|
||||
}
|
||||
func RequestID(ctx context.Context) string { v, _ := ctx.Value(requestKey{}).(string); return v }
|
||||
func Event(ctx context.Context, event string, fields map[string]any) {
|
||||
sc := trace.SpanContextFromContext(ctx)
|
||||
body := map[string]any{"timestamp": time.Now().UTC().Format(time.RFC3339Nano), "severity": "INFO", "service.name": Service, "event": event}
|
||||
if sc.IsValid() {
|
||||
body["trace_id"] = sc.TraceID().String()
|
||||
body["span_id"] = sc.SpanID().String()
|
||||
}
|
||||
if id, ok := ctx.Value(requestKey{}).(string); ok {
|
||||
body["request_id"] = id
|
||||
}
|
||||
for k, v := range fields {
|
||||
body[k] = v
|
||||
}
|
||||
severity := otellog.SeverityInfo
|
||||
if status, ok := fields["status"].(int); ok && status >= 500 {
|
||||
severity = otellog.SeverityError
|
||||
}
|
||||
if outcome, ok := fields["outcome"].(string); ok && (outcome == "failed" || outcome == "retry" || outcome == "abandoned") {
|
||||
severity = otellog.SeverityError
|
||||
}
|
||||
if severity == otellog.SeverityError {
|
||||
body["severity"] = "ERROR"
|
||||
}
|
||||
encoded, _ := json.Marshal(body)
|
||||
_, _ = os.Stdout.Write(append(encoded, '\n'))
|
||||
var record otellog.Record
|
||||
record.SetTimestamp(time.Now())
|
||||
record.SetSeverity(severity)
|
||||
record.SetSeverityText(body["severity"].(string))
|
||||
record.SetBody(otellog.StringValue(string(encoded)))
|
||||
record.AddAttributes(otellog.String("event", event))
|
||||
logglobal.GetLoggerProvider().Logger(Scope).Emit(ctx, record)
|
||||
}
|
||||
func HTTP(ctx context.Context, method, route string, status int, elapsed time.Duration) {
|
||||
if signals == nil {
|
||||
return
|
||||
}
|
||||
a := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100)))
|
||||
signals.Requests.Add(ctx, 1, a)
|
||||
signals.HTTPDuration.Record(ctx, elapsed.Seconds(), a)
|
||||
}
|
||||
func Job(ctx context.Context, outcome string, d time.Duration) {
|
||||
if signals == nil {
|
||||
return
|
||||
}
|
||||
a := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
||||
signals.Jobs.Add(ctx, 1, a)
|
||||
signals.JobDuration.Record(ctx, d.Seconds(), a)
|
||||
}
|
||||
func Ready(ctx context.Context, d time.Duration) {
|
||||
if signals != nil {
|
||||
signals.ReadyDuration.Record(ctx, d.Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
|
||||
}
|
||||
}
|
||||
func Method(s string) string {
|
||||
switch s {
|
||||
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
|
||||
return s
|
||||
}
|
||||
return "OTHER"
|
||||
}
|
||||
func Route(path string) string {
|
||||
switch path {
|
||||
case "/health/live", "/health/ready", "/api/v1/users", "/api/v1/users/me", "/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
|
||||
return path
|
||||
}
|
||||
parts := strings.Split(strings.Trim(path, "/"), "/")
|
||||
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" {
|
||||
if parts[2] == "chats" {
|
||||
if len(parts) == 4 {
|
||||
return "/api/v1/chats/{chat_id}"
|
||||
}
|
||||
if len(parts) == 5 && (parts[4] == "messages" || parts[4] == "attachments") {
|
||||
return "/api/v1/chats/{chat_id}/" + parts[4]
|
||||
}
|
||||
}
|
||||
if parts[2] == "attachments" {
|
||||
if len(parts) == 4 {
|
||||
return "/api/v1/attachments/{attachment_id}"
|
||||
}
|
||||
if len(parts) == 5 && parts[4] == "content" {
|
||||
return "/api/v1/attachments/{attachment_id}/content"
|
||||
}
|
||||
}
|
||||
}
|
||||
return "/unmatched"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRouteLabelsNeverContainResourceIDs(t *testing.T) {
|
||||
ids := []string{"11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"}
|
||||
for _, id := range ids {
|
||||
cases := map[string]string{
|
||||
"/api/v1/chats/" + id: "/api/v1/chats/{chat_id}",
|
||||
"/api/v1/chats/" + id + "/messages": "/api/v1/chats/{chat_id}/messages",
|
||||
"/api/v1/chats/" + id + "/attachments": "/api/v1/chats/{chat_id}/attachments",
|
||||
"/api/v1/attachments/" + id + "/content": "/api/v1/attachments/{attachment_id}/content",
|
||||
"/arbitrary/" + id: "/unmatched",
|
||||
}
|
||||
for input, want := range cases {
|
||||
got := Route(input)
|
||||
if got != want || strings.Contains(got, id) {
|
||||
t.Fatalf("unsafe route label %q for %q", got, input)
|
||||
}
|
||||
}
|
||||
}
|
||||
if Method("CUSTOM-USER-METHOD") != "OTHER" {
|
||||
t.Fatal("unbounded method label")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user