telemetry

package
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: AGPL-3.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProtocolTCP = "tcp"
	ProtocolUDP = "udp"
)

Protocol labels (low-cardinality)

View Source
const (
	ReasonServerRequest  = "server_request"
	ReasonTimeout        = "timeout"
	ReasonPeerClose      = "peer_close"
	ReasonNetworkChange  = "network_change"
	ReasonAuthError      = "auth_error"
	ReasonHandshakeError = "handshake_error"
	ReasonConfigChange   = "config_change"
	ReasonError          = "error"
)

Reconnect reason bins (fixed, low-cardinality)

View Source
const (
	ProxyConnectionOpened = "opened"
	ProxyConnectionClosed = "closed"
)

Proxy connection lifecycle events.

Variables

This section is empty.

Functions

func AddTunnelBytes

func AddTunnelBytes(ctx context.Context, tunnelID, direction string, n int64)

func AddTunnelBytesSet

func AddTunnelBytesSet(ctx context.Context, n int64, attrs attribute.Set)

AddTunnelBytesSet adds bytes using a pre-built attribute.Set to avoid per-call allocations.

func IncCertRotation

func IncCertRotation(ctx context.Context, result string)

func IncConfigReload

func IncConfigReload(ctx context.Context, result string)

Config reloads

func IncConnAttempt

func IncConnAttempt(ctx context.Context, transport, result string)

func IncConnError

func IncConnError(ctx context.Context, transport, typ string)

func IncProxyAccept

func IncProxyAccept(ctx context.Context, tunnelID, protocol, result, reason string)

func IncProxyConnectionEvent

func IncProxyConnectionEvent(ctx context.Context, tunnelID, protocol, event string)

IncProxyConnectionEvent records proxy connection lifecycle events (opened/closed).

func IncProxyDrops

func IncProxyDrops(ctx context.Context, tunnelID, protocol string)

func IncReconnect

func IncReconnect(ctx context.Context, tunnelID, initiator, reason string)

func IncSiteRegistration

func IncSiteRegistration(ctx context.Context, result string)

func IncWSDisconnect

func IncWSDisconnect(ctx context.Context, reason, result string)

func IncWSKeepaliveFailure

func IncWSKeepaliveFailure(ctx context.Context, reason string)

func IncWSMessage

func IncWSMessage(ctx context.Context, direction, msgType string)

func IncWSReconnect

func IncWSReconnect(ctx context.Context, reason string)

IncWSReconnect increments the WebSocket reconnect counter with a bounded reason label.

func ObserveConfigApply

func ObserveConfigApply(ctx context.Context, phase, result string, seconds float64)

func ObserveProxyActiveConnsObs

func ObserveProxyActiveConnsObs(o metric.Observer, value int64, attrs []attribute.KeyValue)

func ObserveProxyAsyncBacklogObs

func ObserveProxyAsyncBacklogObs(o metric.Observer, value int64, attrs []attribute.KeyValue)

func ObserveProxyBufferBytesObs

func ObserveProxyBufferBytesObs(o metric.Observer, value int64, attrs []attribute.KeyValue)

func ObserveProxyConnectionDuration

func ObserveProxyConnectionDuration(ctx context.Context, tunnelID, protocol, result string, seconds float64)

func ObserveTunnelLatency

func ObserveTunnelLatency(ctx context.Context, tunnelID, transport string, seconds float64)

func ObserveWSConnectLatency

func ObserveWSConnectLatency(ctx context.Context, seconds float64, result, errorType string)

func ObserveWSSessionDuration

func ObserveWSSessionDuration(ctx context.Context, seconds float64, result string)

func RegisterBuildInfo

func RegisterBuildInfo(version, commit string)

Build info registration

func RegisterStateView

func RegisterStateView(v StateView)

RegisterStateView sets the global StateView used by the default observable callback.

func SetObservableCallback

func SetObservableCallback(cb func(context.Context, metric.Observer) error)

SetObservableCallback registers a single callback that will be invoked on collection. Use the provided observer to emit values for the observable gauges defined here.

Example inside your code (where you have access to current state):

telemetry.SetObservableCallback(func(ctx context.Context, o metric.Observer) error {
    o.ObserveInt64(mSiteOnline, 1)
    o.ObserveFloat64(mSiteLastHeartbeat, float64(lastHB.Unix()))
    o.ObserveInt64(mTunnelSessions, int64(len(activeSessions)))
    return nil
})

func SetProxyObservableCallback

func SetProxyObservableCallback(cb func(context.Context, metric.Observer) error)

SetProxyObservableCallback registers a callback to observe proxy gauges.

func SetWSConnectionState

func SetWSConnectionState(connected bool)

SetWSConnectionState updates the backing gauge for the WebSocket connected state.

func ShouldIncludeSiteLabels

func ShouldIncludeSiteLabels() bool

ShouldIncludeSiteLabels returns whether site_id/region should be emitted as metric labels in addition to resource attributes.

func ShouldIncludeTunnelID

func ShouldIncludeTunnelID() bool

ShouldIncludeTunnelID returns whether tunnel_id labels should be emitted.

func SiteLabelKVs

func SiteLabelKVs() []attribute.KeyValue

SiteLabelKVs exposes site label KVs for other packages (e.g., proxy manager).

func UpdateSiteInfo

func UpdateSiteInfo(siteID, region string)

UpdateSiteInfo updates the global site_id and region used for metric labels. Thread-safe via atomic.Value: subsequent metric emissions will include the new labels, prior emissions remain unchanged.

Types

type Config

type Config struct {
	ServiceName    string
	ServiceVersion string

	// Optional resource attributes
	SiteID string
	Region string

	PromEnabled bool
	OTLPEnabled bool

	OTLPEndpoint string // host:port
	OTLPInsecure bool

	MetricExportInterval time.Duration
	AdminAddr            string // e.g.: ":2112"

	// Optional build info for newt_build_info metric
	BuildVersion string
	BuildCommit  string
}

Config controls telemetry initialization via env flags.

Defaults align with the issue requirements:

  • Prometheus exporter enabled by default (/metrics)
  • OTLP exporter disabled by default
  • Durations in seconds, bytes in raw bytes
  • Admin HTTP server address configurable (for mounting /metrics)

func FromEnv

func FromEnv() Config

FromEnv reads configuration from environment variables.

NEWT_METRICS_PROMETHEUS_ENABLED (default: true)
NEWT_METRICS_OTLP_ENABLED       (default: false)
OTEL_EXPORTER_OTLP_ENDPOINT     (default: "localhost:4317")
OTEL_EXPORTER_OTLP_INSECURE     (default: true)
OTEL_METRIC_EXPORT_INTERVAL     (default: 15s)
OTEL_SERVICE_NAME               (default: "newt")
OTEL_SERVICE_VERSION            (default: "")
NEWT_ADMIN_ADDR                 (default: ":2112")

type Setup

type Setup struct {
	MeterProvider  *metric.MeterProvider
	TracerProvider *trace.TracerProvider

	PrometheusHandler http.Handler // nil if Prometheus exporter disabled
	// contains filtered or unexported fields
}

Setup holds initialized telemetry providers and (optionally) a /metrics handler. Call Shutdown when the process terminates to flush exporters.

func Init

func Init(ctx context.Context, cfg Config) (*Setup, error)

Init configures OpenTelemetry metrics and (optionally) tracing.

It sets a global MeterProvider and TracerProvider, registers runtime instrumentation, installs recommended histogram views for *_latency_seconds, and returns a Setup with a Shutdown method to flush exporters.

func (*Setup) Shutdown

func (s *Setup) Shutdown(ctx context.Context) error

Shutdown flushes exporters and providers in reverse init order.

type StateView

type StateView interface {
	// ListSites returns a stable, low-cardinality list of site IDs to expose.
	ListSites() []string
	// Online returns whether the site is online.
	Online(siteID string) (online bool, ok bool)
	// LastHeartbeat returns the last heartbeat time for a site.
	LastHeartbeat(siteID string) (t time.Time, ok bool)
	// ActiveSessions returns the current number of active sessions for a site (across tunnels),
	// or scoped to site if your model is site-scoped.
	ActiveSessions(siteID string) (n int64, ok bool)
}

StateView provides a read-only view for observable gauges. Implementations must be concurrency-safe and avoid blocking operations. All methods should be fast and use RLocks where applicable.

Jump to

Keyboard shortcuts

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