-
Notifications
You must be signed in to change notification settings - Fork 10
telemetry: submit BGP session status onchain per user #3487
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
10 commits
Select commit
Hold shift + click to select a range
3b00c85
smartcontract/sdk/go: add BGPStatus type and SetUserBGPStatus executo…
juan-malbeclabs d1981f4
telemetry: add BGP status submitter
juan-malbeclabs 0e543e8
e2e: add TestE2E_UserBGPStatus and update user list fixtures
juan-malbeclabs 3808219
telemetry: add BGP status submitter CHANGELOG entry
juan-malbeclabs 9291609
telemetry: fix BGP status Down not submitted after tunnel disappears
juan-malbeclabs c88506f
telemetry: cache shared GetProgramData calls with CachingFetcher
juan-malbeclabs a47d4e0
telemetry: add Prometheus metrics for BGP status submitter
juan-malbeclabs cfc6729
telemetry: pass shared CachingFetcher to peer discovery and collector
juan-malbeclabs 6223851
telemetry/bgpstatus: fix three review issues
juan-malbeclabs 80faf91
bgpstatus: clear pending flag when pruning deactivated user state
juan-malbeclabs 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
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 |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| package bgpstatus | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "net" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/gagliardetto/solana-go" | ||
| "github.com/jonboulle/clockwork" | ||
| "github.com/malbeclabs/doublezero/controlplane/telemetry/internal/netutil" | ||
| "github.com/malbeclabs/doublezero/smartcontract/sdk/go/serviceability" | ||
| ) | ||
|
|
||
| const ( | ||
| taskChannelCapacity = 256 | ||
| defaultInterval = 60 * time.Second | ||
| defaultRefreshInterval = 6 * time.Hour | ||
| submitMaxRetries = 3 | ||
| submitBaseBackoff = 100 * time.Millisecond | ||
| ) | ||
|
|
||
| // BGPStatusExecutor submits a SetUserBGPStatus instruction onchain. | ||
| type BGPStatusExecutor interface { | ||
| SetUserBGPStatus(ctx context.Context, u serviceability.UserBGPStatusUpdate) (solana.Signature, error) | ||
| } | ||
|
|
||
| // ServiceabilityClient fetches the current program state from the ledger. | ||
| type ServiceabilityClient interface { | ||
| GetProgramData(ctx context.Context) (*serviceability.ProgramData, error) | ||
| } | ||
|
|
||
| // Config holds all parameters for the BGP status submitter. | ||
| type Config struct { | ||
| Log *slog.Logger | ||
| Executor BGPStatusExecutor | ||
| ServiceabilityClient ServiceabilityClient | ||
| LocalNet netutil.LocalNet | ||
| LocalDevicePK solana.PublicKey | ||
| BGPNamespace string | ||
| Interval time.Duration // default: 60s | ||
| PeriodicRefreshInterval time.Duration // default: 6h | ||
| DownGracePeriod time.Duration // default: 0 | ||
| Clock clockwork.Clock | ||
| } | ||
|
|
||
| func (c *Config) validate() error { | ||
| if c.Log == nil { | ||
| return errors.New("log is required") | ||
| } | ||
| if c.Executor == nil { | ||
| return errors.New("executor is required") | ||
| } | ||
| if c.ServiceabilityClient == nil { | ||
| return errors.New("serviceability client is required") | ||
| } | ||
| if c.LocalNet == nil { | ||
| return errors.New("local net is required") | ||
| } | ||
| if c.LocalDevicePK.IsZero() { | ||
| return errors.New("local device pubkey is required") | ||
| } | ||
| if c.BGPNamespace == "" { | ||
| return errors.New("bgp namespace is required") | ||
| } | ||
| if c.Interval <= 0 { | ||
| c.Interval = defaultInterval | ||
| } | ||
| if c.PeriodicRefreshInterval <= 0 { | ||
| c.PeriodicRefreshInterval = defaultRefreshInterval | ||
| } | ||
| if c.Clock == nil { | ||
| c.Clock = clockwork.NewRealClock() | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // userState tracks submission state for a single user. | ||
| type userState struct { | ||
| lastOnchainStatus serviceability.BGPStatus | ||
| lastWriteTime time.Time | ||
| lastUpObservedAt time.Time | ||
| } | ||
|
|
||
| // submitTask is queued to the background worker for onchain submission. | ||
| type submitTask struct { | ||
| user serviceability.User | ||
| status serviceability.BGPStatus | ||
| } | ||
|
|
||
| // Submitter collects BGP socket state on each tick, determines per-user BGP | ||
| // status, and submits SetUserBGPStatus onchain via a non-blocking worker. | ||
| type Submitter struct { | ||
| cfg Config | ||
| log *slog.Logger | ||
| userState map[string]*userState // keyed by user PubKey base58 | ||
| pending map[string]bool // users currently in-flight in the worker | ||
| mu sync.Mutex | ||
| taskCh chan submitTask | ||
| } | ||
|
|
||
| // NewSubmitter creates a Submitter after validating the config. | ||
| func NewSubmitter(cfg Config) (*Submitter, error) { | ||
| if err := cfg.validate(); err != nil { | ||
| return nil, fmt.Errorf("invalid bgpstatus config: %w", err) | ||
| } | ||
| return &Submitter{ | ||
| cfg: cfg, | ||
| log: cfg.Log, | ||
| userState: make(map[string]*userState), | ||
| pending: make(map[string]bool), | ||
| taskCh: make(chan submitTask, taskChannelCapacity), | ||
| }, nil | ||
| } | ||
|
|
||
| // Start launches the submitter in the background and returns a channel that | ||
| // receives a fatal error (or is closed on clean shutdown). It mirrors the | ||
| // state.Collector.Start pattern. | ||
| func (s *Submitter) Start(ctx context.Context, cancel context.CancelFunc) <-chan error { | ||
| errCh := make(chan error, 1) | ||
| go func() { | ||
| defer close(errCh) | ||
| defer cancel() | ||
| if err := s.run(ctx); err != nil { | ||
| s.log.Error("bgpstatus: submitter failed", "error", err) | ||
| errCh <- err | ||
| } | ||
| }() | ||
| return errCh | ||
| } | ||
|
|
||
| // userStateFor returns or creates the per-user tracking entry (caller must hold s.mu). | ||
| // initialStatus is used only when creating a new entry; it seeds lastOnchainStatus so | ||
| // that a restarted submitter correctly handles users whose onchain state is already Up. | ||
| func (s *Submitter) userStateFor(key string, initialStatus serviceability.BGPStatus) *userState { | ||
| us, ok := s.userState[key] | ||
| if !ok { | ||
| us = &userState{lastOnchainStatus: initialStatus} | ||
| s.userState[key] = us | ||
| } | ||
| return us | ||
| } | ||
|
|
||
| // bgpSocket is the minimal BGP socket representation used by the pure helpers. | ||
| // The Linux-specific submitter.go converts state.BGPSocketState to this type. | ||
| type bgpSocket struct { | ||
| RemoteIP string | ||
| State string | ||
| } | ||
|
|
||
| // --- Pure helpers (no Linux syscalls; fully testable on all platforms) --- | ||
|
|
||
| // buildEstablishedIPSet returns a set of remote IP strings for BGP sessions | ||
| // that are currently in the ESTABLISHED state. | ||
| func buildEstablishedIPSet(sockets []bgpSocket) map[string]struct{} { | ||
| m := make(map[string]struct{}, len(sockets)) | ||
| for _, sock := range sockets { | ||
| if sock.State == "ESTABLISHED" { | ||
| m[sock.RemoteIP] = struct{}{} | ||
| } | ||
| } | ||
| return m | ||
| } | ||
|
|
||
| // tunnelNetToIPNet parses the onchain [5]byte tunnel-net encoding into a | ||
| // *net.IPNet. The format is [4 bytes IPv4 prefix | 1 byte CIDR length]. | ||
| func tunnelNetToIPNet(b [5]byte) *net.IPNet { | ||
| ip := net.IPv4(b[0], b[1], b[2], b[3]) | ||
| mask := net.CIDRMask(int(b[4]), 32) | ||
| return &net.IPNet{IP: ip.To4(), Mask: mask} | ||
| } | ||
|
|
||
| // computeEffectiveStatus derives the BGP status to report, applying the down | ||
| // grace period: if observedUp is false but the user was last seen Up within | ||
| // gracePeriod, we still report Up to avoid transient flaps. | ||
| func computeEffectiveStatus( | ||
| observedUp bool, | ||
| us *userState, | ||
| now time.Time, | ||
| gracePeriod time.Duration, | ||
| ) serviceability.BGPStatus { | ||
| if observedUp { | ||
| return serviceability.BGPStatusUp | ||
| } | ||
| if us.lastUpObservedAt.IsZero() { | ||
| return serviceability.BGPStatusDown | ||
| } | ||
| if gracePeriod > 0 && now.Sub(us.lastUpObservedAt) < gracePeriod { | ||
| return serviceability.BGPStatusUp | ||
| } | ||
| return serviceability.BGPStatusDown | ||
| } | ||
|
|
||
| // shouldSubmit returns true when a submission is warranted: either the status | ||
| // has changed from what was last confirmed onchain, or it is time for a | ||
| // periodic keepalive write. | ||
| func shouldSubmit( | ||
| us *userState, | ||
| newStatus serviceability.BGPStatus, | ||
| now time.Time, | ||
| refreshInterval time.Duration, | ||
| ) bool { | ||
| if us.lastWriteTime.IsZero() { | ||
| return true | ||
| } | ||
| if us.lastOnchainStatus != newStatus { | ||
| return true | ||
| } | ||
| return now.Sub(us.lastWriteTime) >= refreshInterval | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package bgpstatus | ||
|
|
||
| import ( | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promauto" | ||
| ) | ||
|
|
||
| var ( | ||
| metricSubmissionsTotal = promauto.NewCounterVec( | ||
| prometheus.CounterOpts{ | ||
| Name: "doublezero_bgpstatus_submissions_total", | ||
| Help: "Total onchain BGP status submissions by BGP status and result", | ||
| }, | ||
| []string{"bgp_status", "result"}, | ||
| ) | ||
|
|
||
| metricSubmissionDuration = promauto.NewHistogram( | ||
| prometheus.HistogramOpts{ | ||
| Name: "doublezero_bgpstatus_submission_duration_seconds", | ||
| Help: "Duration of successful onchain BGP status submissions", | ||
| Buckets: []float64{0.1, 0.5, 1, 2, 5, 10, 30, 60}, | ||
| }, | ||
| ) | ||
| ) |
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.