ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func Incoming(r *http.Request) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
}
|
||||
|
||||
type roundTripper struct{ next http.RoundTripper }
|
||||
|
||||
func Transport(next http.RoundTripper) http.RoundTripper {
|
||||
if next == nil {
|
||||
next = http.DefaultTransport
|
||||
}
|
||||
return &roundTripper{next: next}
|
||||
}
|
||||
|
||||
func (t *roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
ctx, span := Start(r.Context(), "s3.request", trace.SpanKindClient)
|
||||
defer span.End()
|
||||
resp, err := t.next.RoundTrip(r.Clone(ctx))
|
||||
Failure(span, err)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func RoutePattern(r *http.Request) string {
|
||||
if rc := chi.RouteContext(r.Context()); rc != nil {
|
||||
if pattern := rc.RoutePattern(); pattern != "" {
|
||||
return pattern
|
||||
}
|
||||
}
|
||||
return r.URL.Path
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
// Package telemetry exports OTLP metrics, logs and traces without affecting business readiness.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"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"
|
||||
"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"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.32.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const version = "7.0.0-lab"
|
||||
|
||||
var (
|
||||
httpRequests metric.Int64Counter
|
||||
httpDuration metric.Float64Histogram
|
||||
jobsCount metric.Int64Counter
|
||||
jobDuration metric.Float64Histogram
|
||||
readyHist metric.Float64Histogram
|
||||
|
||||
pendingAcquires atomic.Int64
|
||||
busyWorkers atomic.Int64
|
||||
workerCapacity atomic.Int64
|
||||
|
||||
tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
|
||||
)
|
||||
|
||||
func Init(ctx context.Context, service string) (*slog.Logger, func(), error) {
|
||||
host, _ := os.Hostname()
|
||||
res := resource.NewWithAttributes(
|
||||
semconv.SchemaURL,
|
||||
attribute.String("service.name", service),
|
||||
attribute.String("service.version", version),
|
||||
attribute.String("service.instance.id", host),
|
||||
attribute.String("deployment.environment.name", "lab"),
|
||||
)
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
std := slog.NewJSONHandler(os.Stdout, nil)
|
||||
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
||||
return slog.New(&contextHandler{next: std, service: service}), func() {}, nil
|
||||
}
|
||||
|
||||
traceOpts := []otlptracehttp.Option{otlptracehttp.WithTimeout(time.Second)}
|
||||
traceExp, err := otlptracehttp.New(ctx, traceOpts...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))),
|
||||
sdktrace.WithBatcher(traceExp,
|
||||
sdktrace.WithMaxQueueSize(1024),
|
||||
sdktrace.WithMaxExportBatchSize(128),
|
||||
sdktrace.WithBatchTimeout(time.Second),
|
||||
sdktrace.WithExportTimeout(time.Second),
|
||||
),
|
||||
)
|
||||
otel.SetTracerProvider(tp)
|
||||
tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL))
|
||||
|
||||
metricOpts := []otlpmetrichttp.Option{otlpmetrichttp.WithTimeout(time.Second)}
|
||||
metricExp, err := otlpmetrichttp.New(ctx, metricOpts...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120}
|
||||
mp := sdkmetric.NewMeterProvider(
|
||||
sdkmetric.WithResource(res),
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp,
|
||||
sdkmetric.WithInterval(2*time.Second),
|
||||
sdkmetric.WithTimeout(time.Second),
|
||||
)),
|
||||
sdkmetric.WithView(sdkmetric.NewView(
|
||||
sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram},
|
||||
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: buckets}},
|
||||
)),
|
||||
)
|
||||
otel.SetMeterProvider(mp)
|
||||
|
||||
logOpts := []otlploghttp.Option{otlploghttp.WithTimeout(time.Second)}
|
||||
logExp, err := otlploghttp.New(ctx, logOpts...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
lp := sdklog.NewLoggerProvider(
|
||||
sdklog.WithResource(res),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp,
|
||||
sdklog.WithMaxQueueSize(1024),
|
||||
sdklog.WithExportMaxBatchSize(128),
|
||||
sdklog.WithExportInterval(time.Second),
|
||||
sdklog.WithExportTimeout(time.Second),
|
||||
)),
|
||||
)
|
||||
logHandler := slog.New(&contextHandler{
|
||||
next: &tee{
|
||||
a: std,
|
||||
b: otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp)),
|
||||
},
|
||||
service: service,
|
||||
})
|
||||
|
||||
m := otel.Meter("messenger")
|
||||
httpRequests, _ = m.Int64Counter("http.server.requests")
|
||||
httpDuration, _ = m.Float64Histogram("http.server.duration", metric.WithUnit("s"))
|
||||
jobsCount, _ = m.Int64Counter("messenger.jobs")
|
||||
jobDuration, _ = m.Float64Histogram("messenger.job.duration", metric.WithUnit("s"))
|
||||
readyHist, _ = m.Float64Histogram("messenger.attachment.ready.duration", metric.WithUnit("s"))
|
||||
|
||||
shutdown := func() {
|
||||
c, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
_ = tp.Shutdown(c)
|
||||
_ = mp.Shutdown(c)
|
||||
_ = lp.Shutdown(c)
|
||||
}
|
||||
return logHandler, shutdown, nil
|
||||
}
|
||||
|
||||
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
|
||||
return tracer.Start(ctx, name, trace.WithSpanKind(kind))
|
||||
}
|
||||
|
||||
func Failure(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "operation failed")
|
||||
}
|
||||
}
|
||||
|
||||
func Inject(ctx context.Context) (string, string) {
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
return carrier.Get("traceparent"), carrier.Get("tracestate")
|
||||
}
|
||||
|
||||
func Extract(ctx context.Context, parent, state string) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{
|
||||
"traceparent": parent,
|
||||
"tracestate": state,
|
||||
})
|
||||
}
|
||||
|
||||
func TraceID(ctx context.Context) string {
|
||||
return trace.SpanContextFromContext(ctx).TraceID().String()
|
||||
}
|
||||
|
||||
func HTTP(ctx context.Context, method, route string, status int, seconds float64) {
|
||||
switch method {
|
||||
case "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS":
|
||||
default:
|
||||
method = "_OTHER"
|
||||
}
|
||||
if httpRequests == nil {
|
||||
return
|
||||
}
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("method", method),
|
||||
attribute.String("route", route),
|
||||
attribute.String("status_class", fmt.Sprintf("%dxx", status/100)),
|
||||
)
|
||||
httpRequests.Add(ctx, 1, attrs)
|
||||
httpDuration.Record(ctx, seconds, attrs)
|
||||
}
|
||||
|
||||
func Job(ctx context.Context, outcome string, seconds float64) {
|
||||
if jobsCount == nil {
|
||||
return
|
||||
}
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("job_type", "attachment.process.v1"),
|
||||
attribute.String("outcome", outcome),
|
||||
)
|
||||
jobsCount.Add(ctx, 1, attrs)
|
||||
jobDuration.Record(ctx, seconds, attrs)
|
||||
}
|
||||
|
||||
func Ready(ctx context.Context, seconds float64) {
|
||||
if readyHist != nil {
|
||||
readyHist.Record(ctx, seconds)
|
||||
}
|
||||
}
|
||||
|
||||
func SetWorkerCapacity(n int) {
|
||||
workerCapacity.Store(int64(n))
|
||||
}
|
||||
|
||||
func IncBusy() { busyWorkers.Add(1) }
|
||||
func DecBusy() { busyWorkers.Add(-1) }
|
||||
func IncWait() { pendingAcquires.Add(1) }
|
||||
func DecWait() { pendingAcquires.Add(-1) }
|
||||
|
||||
func RegisterPoolObservers(pool *pgxpool.Pool, workerRole bool) {
|
||||
m := otel.Meter("messenger")
|
||||
poolUsed, _ := m.Int64ObservableGauge("messenger.db.pool.used")
|
||||
poolLimit, _ := m.Int64ObservableGauge("messenger.db.pool.limit")
|
||||
poolWaiting, _ := m.Int64ObservableGauge("messenger.db.pool.waiting")
|
||||
queueDepth, _ := m.Int64ObservableGauge("messenger.queue.depth")
|
||||
queueAge, _ := m.Float64ObservableGauge("messenger.queue.oldest_age_seconds", metric.WithUnit("s"))
|
||||
busy, _ := m.Int64ObservableGauge("messenger.worker.busy")
|
||||
capacity, _ := m.Int64ObservableGauge("messenger.worker.capacity")
|
||||
sliTotal, _ := m.Int64ObservableCounter("messenger.attachment.sli.total")
|
||||
sliBad, _ := m.Int64ObservableCounter("messenger.attachment.sli.bad")
|
||||
|
||||
_, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
stat := pool.Stat()
|
||||
o.ObserveInt64(poolUsed, int64(stat.AcquiredConns()))
|
||||
o.ObserveInt64(poolLimit, int64(stat.MaxConns()))
|
||||
o.ObserveInt64(poolWaiting, pendingAcquires.Load())
|
||||
if workerRole {
|
||||
o.ObserveInt64(busy, busyWorkers.Load())
|
||||
o.ObserveInt64(capacity, workerCapacity.Load())
|
||||
qctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
var depth int64
|
||||
var oldest float64
|
||||
err := pool.QueryRow(qctx, `
|
||||
SELECT count(*),
|
||||
COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8
|
||||
FROM attachments
|
||||
WHERE status IN ('queued', 'processing')`).Scan(&depth, &oldest)
|
||||
if err == nil {
|
||||
o.ObserveInt64(queueDepth, depth)
|
||||
o.ObserveFloat64(queueAge, oldest)
|
||||
}
|
||||
var matured, bad int64
|
||||
err = pool.QueryRow(qctx, `
|
||||
SELECT count(*),
|
||||
count(*) FILTER (
|
||||
WHERE status = 'failed'
|
||||
OR (status = 'ready' AND updated_at > created_at + interval '5 seconds')
|
||||
)
|
||||
FROM attachments
|
||||
WHERE created_at <= clock_timestamp() - interval '5 seconds'
|
||||
AND status IN ('ready', 'failed')`).Scan(&matured, &bad)
|
||||
if err == nil {
|
||||
o.ObserveInt64(sliTotal, matured)
|
||||
o.ObserveInt64(sliBad, bad)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, poolUsed, poolLimit, poolWaiting, queueDepth, queueAge, busy, capacity, sliTotal, sliBad)
|
||||
}
|
||||
|
||||
type contextHandler struct {
|
||||
next slog.Handler
|
||||
service string
|
||||
}
|
||||
|
||||
func (h *contextHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return h.next.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *contextHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
r.AddAttrs(
|
||||
slog.String("service.name", h.service),
|
||||
slog.String("event", r.Message),
|
||||
)
|
||||
sc := trace.SpanContextFromContext(ctx)
|
||||
if sc.IsValid() {
|
||||
r.AddAttrs(
|
||||
slog.String("trace_id", sc.TraceID().String()),
|
||||
slog.String("span_id", sc.SpanID().String()),
|
||||
)
|
||||
}
|
||||
return h.next.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func (h *contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &contextHandler{next: h.next.WithAttrs(attrs), service: h.service}
|
||||
}
|
||||
|
||||
func (h *contextHandler) WithGroup(name string) slog.Handler {
|
||||
return &contextHandler{next: h.next.WithGroup(name), service: h.service}
|
||||
}
|
||||
|
||||
type tee struct{ a, b slog.Handler }
|
||||
|
||||
func (t *tee) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return t.a.Enabled(ctx, level) || t.b.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (t *tee) Handle(ctx context.Context, r slog.Record) error {
|
||||
_ = t.a.Handle(ctx, r.Clone())
|
||||
return t.b.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func (t *tee) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &tee{t.a.WithAttrs(attrs), t.b.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
func (t *tee) WithGroup(name string) slog.Handler {
|
||||
return &tee{t.a.WithGroup(name), t.b.WithGroup(name)}
|
||||
}
|
||||
|
||||
func ProcessRSS() int64 {
|
||||
raw, err := os.ReadFile("/proc/self/stat")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
end := strings.LastIndex(string(raw), ")")
|
||||
if end < 0 {
|
||||
return 0
|
||||
}
|
||||
fields := strings.Fields(string(raw)[end+1:])
|
||||
if len(fields) < 22 {
|
||||
return 0
|
||||
}
|
||||
pages, _ := strconv.ParseInt(fields[21], 10, 64)
|
||||
return pages * int64(os.Getpagesize())
|
||||
}
|
||||
Reference in New Issue
Block a user