-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[proxy] refactor metrics and add usage logs #5533
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c2fec57
switch proxy to use opentelemetry
pascal-fischer 9ab6138
fix mapping counting and metrics registry
pascal-fischer d9418dd
do log throughput and requests. Also add throughput to the log entries
pascal-fischer 1aa1eef
account for streaming
pascal-fischer 8db71b5
add certificate issue duration metrics
pascal-fischer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ package accesslog | |
| import ( | ||
| "context" | ||
| "net/netip" | ||
| "sync" | ||
| "time" | ||
|
|
||
| log "github.com/sirupsen/logrus" | ||
|
|
@@ -13,6 +14,23 @@ import ( | |
| "github.com/netbirdio/netbird/shared/management/proto" | ||
| ) | ||
|
|
||
| const ( | ||
| requestThreshold = 10000 // Log every 10k requests | ||
| bytesThreshold = 1024 * 1024 * 1024 // Log every 1GB | ||
| usageCleanupPeriod = 1 * time.Hour // Clean up stale counters every hour | ||
| usageInactiveWindow = 24 * time.Hour // Consider domain inactive if no traffic for 24 hours | ||
| ) | ||
|
|
||
| type domainUsage struct { | ||
| requestCount int64 | ||
| requestStartTime time.Time | ||
|
|
||
| bytesTransferred int64 | ||
| bytesStartTime time.Time | ||
|
|
||
| lastActivity time.Time // Track last activity for cleanup | ||
| } | ||
|
|
||
| type gRPCClient interface { | ||
| SendAccessLog(ctx context.Context, in *proto.SendAccessLogRequest, opts ...grpc.CallOption) (*proto.SendAccessLogResponse, error) | ||
| } | ||
|
|
@@ -22,6 +40,11 @@ type Logger struct { | |
| client gRPCClient | ||
| logger *log.Logger | ||
| trustedProxies []netip.Prefix | ||
|
|
||
| usageMux sync.Mutex | ||
| domainUsage map[string]*domainUsage | ||
|
|
||
| cleanupCancel context.CancelFunc | ||
| } | ||
|
|
||
| // NewLogger creates a new access log Logger. The trustedProxies parameter | ||
|
|
@@ -31,10 +54,26 @@ func NewLogger(client gRPCClient, logger *log.Logger, trustedProxies []netip.Pre | |
| if logger == nil { | ||
| logger = log.StandardLogger() | ||
| } | ||
| return &Logger{ | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| l := &Logger{ | ||
| client: client, | ||
| logger: logger, | ||
| trustedProxies: trustedProxies, | ||
| domainUsage: make(map[string]*domainUsage), | ||
| cleanupCancel: cancel, | ||
| } | ||
|
|
||
| // Start background cleanup routine | ||
| go l.cleanupStaleUsage(ctx) | ||
|
|
||
| return l | ||
| } | ||
|
|
||
| // Close stops the cleanup routine. Should be called during graceful shutdown. | ||
| func (l *Logger) Close() { | ||
| if l.cleanupCancel != nil { | ||
| l.cleanupCancel() | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -51,6 +90,8 @@ type logEntry struct { | |
| AuthMechanism string | ||
| UserId string | ||
| AuthSuccess bool | ||
| BytesUpload int64 | ||
| BytesDownload int64 | ||
| } | ||
|
|
||
| func (l *Logger) log(ctx context.Context, entry logEntry) { | ||
|
|
@@ -84,6 +125,8 @@ func (l *Logger) log(ctx context.Context, entry logEntry) { | |
| AuthMechanism: entry.AuthMechanism, | ||
| UserId: entry.UserId, | ||
| AuthSuccess: entry.AuthSuccess, | ||
| BytesUpload: entry.BytesUpload, | ||
| BytesDownload: entry.BytesDownload, | ||
| }, | ||
| }); err != nil { | ||
| // If it fails to send on the gRPC connection, then at least log it to the error log. | ||
|
|
@@ -103,3 +146,82 @@ func (l *Logger) log(ctx context.Context, entry logEntry) { | |
| } | ||
| }() | ||
| } | ||
|
|
||
| // trackUsage records request and byte counts per domain, logging when thresholds are hit. | ||
| func (l *Logger) trackUsage(domain string, bytesTransferred int64) { | ||
| if domain == "" { | ||
| return | ||
| } | ||
|
|
||
| l.usageMux.Lock() | ||
| defer l.usageMux.Unlock() | ||
|
|
||
| now := time.Now() | ||
| usage, exists := l.domainUsage[domain] | ||
| if !exists { | ||
| usage = &domainUsage{ | ||
| requestStartTime: now, | ||
| bytesStartTime: now, | ||
| lastActivity: now, | ||
| } | ||
| l.domainUsage[domain] = usage | ||
| } | ||
|
|
||
| usage.lastActivity = now | ||
|
|
||
| usage.requestCount++ | ||
| if usage.requestCount >= requestThreshold { | ||
| elapsed := time.Since(usage.requestStartTime) | ||
| l.logger.WithFields(log.Fields{ | ||
|
mlsmaycon marked this conversation as resolved.
|
||
| "domain": domain, | ||
| "requests": usage.requestCount, | ||
| "duration": elapsed.String(), | ||
| }).Infof("domain %s had %d requests over %s", domain, usage.requestCount, elapsed) | ||
|
|
||
| usage.requestCount = 0 | ||
| usage.requestStartTime = now | ||
| } | ||
|
|
||
| usage.bytesTransferred += bytesTransferred | ||
| if usage.bytesTransferred >= bytesThreshold { | ||
| elapsed := time.Since(usage.bytesStartTime) | ||
| bytesInGB := float64(usage.bytesTransferred) / (1024 * 1024 * 1024) | ||
| l.logger.WithFields(log.Fields{ | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should log based on a module calculation |
||
| "domain": domain, | ||
| "bytes": usage.bytesTransferred, | ||
| "bytes_gb": bytesInGB, | ||
| "duration": elapsed.String(), | ||
| }).Infof("domain %s transferred %.2f GB over %s", domain, bytesInGB, elapsed) | ||
|
|
||
| usage.bytesTransferred = 0 | ||
| usage.bytesStartTime = now | ||
| } | ||
| } | ||
|
|
||
| // cleanupStaleUsage removes usage entries for domains that have been inactive. | ||
| func (l *Logger) cleanupStaleUsage(ctx context.Context) { | ||
| ticker := time.NewTicker(usageCleanupPeriod) | ||
| defer ticker.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return | ||
| case <-ticker.C: | ||
| l.usageMux.Lock() | ||
| now := time.Now() | ||
| removed := 0 | ||
| for domain, usage := range l.domainUsage { | ||
| if now.Sub(usage.lastActivity) > usageInactiveWindow { | ||
| delete(l.domainUsage, domain) | ||
| removed++ | ||
| } | ||
| } | ||
| l.usageMux.Unlock() | ||
|
|
||
| if removed > 0 { | ||
| l.logger.Debugf("cleaned up %d stale domain usage entries", removed) | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,39 @@ | ||
| package accesslog | ||
|
|
||
| import ( | ||
| "io" | ||
|
|
||
| "github.com/netbirdio/netbird/proxy/internal/responsewriter" | ||
| ) | ||
|
|
||
| // statusWriter captures the HTTP status code from WriteHeader calls. | ||
| // statusWriter captures the HTTP status code and bytes written from responses. | ||
| // It embeds responsewriter.PassthroughWriter which handles all the optional | ||
| // interfaces (Hijacker, Flusher, Pusher) automatically. | ||
| type statusWriter struct { | ||
| *responsewriter.PassthroughWriter | ||
| status int | ||
| status int | ||
| bytesWritten int64 | ||
| } | ||
|
|
||
| func (w *statusWriter) WriteHeader(status int) { | ||
| w.status = status | ||
| w.PassthroughWriter.WriteHeader(status) | ||
| } | ||
|
|
||
| func (w *statusWriter) Write(b []byte) (int, error) { | ||
| n, err := w.PassthroughWriter.Write(b) | ||
| w.bytesWritten += int64(n) | ||
| return n, err | ||
| } | ||
|
|
||
| // bodyCounter wraps an io.ReadCloser and counts bytes read from the request body. | ||
| type bodyCounter struct { | ||
| io.ReadCloser | ||
| bytesRead *int64 | ||
| } | ||
|
|
||
| func (bc *bodyCounter) Read(p []byte) (int, error) { | ||
| n, err := bc.ReadCloser.Read(p) | ||
| *bc.bytesRead += int64(n) | ||
| return n, err | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.