Compare commits
2
Commits
b0b02811ce
...
d5ca673aaf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5ca673aaf | ||
|
|
6b004dfbc3 |
No files matched your search
@@ -429,10 +429,12 @@ the routing table, and everything else from the database.
|
|||||||
- Parses BGP UPDATE messages from JSON stream
|
- Parses BGP UPDATE messages from JSON stream
|
||||||
- Dispatches to registered handlers based on message type
|
- Dispatches to registered handlers based on message type
|
||||||
- Each handler has its own queue with backpressure handling
|
- Each handler has its own queue with backpressure handling
|
||||||
- Handlers batch writes for efficiency: the AS, peer and prefix handlers
|
- Handlers batch writes for efficiency. The AS, peer and prefix handlers
|
||||||
write 30,000, 10,000 and 25,000 updates at a time, or after 2, 2 and 1
|
write a batch when it reaches a size, or after a time:
|
||||||
seconds; the peering handler writes the peerings it has collected every 30
|
- the AS handler at 30,000 ASes, or after 2 seconds;
|
||||||
seconds
|
- the peer handler at 10,000 updates, or after 2 seconds;
|
||||||
|
- the prefix handler at 25,000 updates, or after 1 second.
|
||||||
|
- The peering handler writes the peerings it has collected every 30 seconds
|
||||||
|
|
||||||
4. **Handler Details**
|
4. **Handler Details**
|
||||||
- **ASHandler**: Tracks all ASNs seen in AS paths
|
- **ASHandler**: Tracks all ASNs seen in AS paths
|
||||||
@@ -632,16 +634,19 @@ What happens at each limit:
|
|||||||
`STATE` message, which it holds, in feed order, until there is room: a few
|
`STATE` message, which it holds, in feed order, until there is room: a few
|
||||||
hundred bytes each, about ten a second.
|
hundred bytes each, about ten a second.
|
||||||
- Handler batches: while the AS, peer or prefix handler writes a batch to the
|
- Handler batches: while the AS, peer or prefix handler writes a batch to the
|
||||||
database, the updates that arrive collect in its next batch. That batch stops
|
database, the updates that arrive collect in its next batch.
|
||||||
at ten times the batch size:
|
- The AS handler's batch holds one entry per AS, with the earliest and the
|
||||||
- 300,000 updates for the AS handler (`asnBatchMaxSize`, about 10 MiB);
|
latest time of its updates. About 80,000 ASes appear in the feed, so the
|
||||||
- 100,000 for the peer handler (`peerBatchMaxSize`, about 10 MiB);
|
batch takes at most about 10 MiB, however fast the feed runs.
|
||||||
- 250,000 for the prefix handler (`prefixBatchMaxSize`, about 15 MiB).
|
- The peer handler's batch stops at 100,000 updates (`peerBatchMaxSize`),
|
||||||
|
about 10 MiB.
|
||||||
|
- The prefix handler's batch stops at 250,000 updates
|
||||||
|
(`prefixBatchMaxSize`), about 15 MiB.
|
||||||
|
|
||||||
At that size the handler takes nothing more off its queue until the write
|
At that maximum the peer or prefix handler takes nothing more off its queue
|
||||||
ends. The queue then fills, and the streamer drops messages as above. With
|
until the write ends. The queue then fills, and the streamer drops messages
|
||||||
the batches being written, the three handlers' batches take at most about
|
as above. With the batches being written, the three handlers' batches take
|
||||||
0.1 GiB of the Go heap.
|
at most about 0.1 GiB of the Go heap.
|
||||||
|
|
||||||
With `DEBUG=routewatch` the daemon logs a `System stats` line every 60 seconds
|
With `DEBUG=routewatch` the daemon logs a `System stats` line every 60 seconds
|
||||||
with the goroutine count and Go memory figures.
|
with the goroutine count and Go memory figures.
|
||||||
|
|||||||
@@ -35,6 +35,19 @@ tested.
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-11-02: RouteWatch pauses an RIR's or NIC.br's WHOIS server for an hour
|
||||||
|
after the server refuses a query. A refused or reset connection is a refusal.
|
||||||
|
So is an answer with an `%ERROR:201:` or `%ERROR:202:` line. Lookups at the
|
||||||
|
other servers go on. An AS whose RIR is paused is looked up after the pause.
|
||||||
|
IANA is never paused, because a pause of IANA would stop every lookup. A
|
||||||
|
refusal by IANA is an ordinary failure. NIC.br is also paused for an hour
|
||||||
|
after it says RouteWatch has passed NIC.br's query limit. Before, the fetcher
|
||||||
|
asked a server again within seconds of a refusal (closes #218)
|
||||||
|
- 2026-11-02: the AS handler never waits for a database write. Its batch holds
|
||||||
|
one entry per AS, with the earliest and the latest time of its updates. So the
|
||||||
|
batch no longer grows with the feed's rate. It used to hold one entry for each
|
||||||
|
AS of each path and to wait once it held 300,000. In a burst of the feed its
|
||||||
|
queue then filled, and the streamer dropped messages for it (closes #217)
|
||||||
- 2026-10-27: the tests of `internal/routewatch` no longer fail on a loaded
|
- 2026-10-27: the tests of `internal/routewatch` no longer fail on a loaded
|
||||||
host. Five of them gave `HandleMessage` two seconds to apply a full prefix
|
host. Five of them gave `HandleMessage` two seconds to apply a full prefix
|
||||||
batch, which under the race detector can take longer. A test now waits up to
|
batch, which under the race detector can take longer. A test now waits up to
|
||||||
|
|||||||
@@ -644,9 +644,8 @@ func TestShutdownDoesNotWaitForABlockedWrite(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rw.dbHandler = NewASHandler(store, log)
|
rw.dbHandler = NewASHandler(store, log)
|
||||||
fill := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
|
||||||
startBlockedWrite(t, blocking, rw.dbHandler,
|
startBlockedWrite(t, blocking, rw.dbHandler,
|
||||||
[]*ristypes.RISMessage{{Path: fill}})
|
[]*ristypes.RISMessage{{Path: pathOfASes(asnBatchSize)}})
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(t.Context(), deadline)
|
ctx, cancel := context.WithTimeout(t.Context(), deadline)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|||||||
@@ -18,43 +18,34 @@ const (
|
|||||||
// (asnBatchTimeout), so a queue smaller than asnBatchSize is fine.
|
// (asnBatchTimeout), so a queue smaller than asnBatchSize is fine.
|
||||||
asHandlerQueueSize = 20000
|
asHandlerQueueSize = 20000
|
||||||
|
|
||||||
// asnBatchSize is the number of ASN operations to batch together
|
// asnBatchSize is the number of ASes in a full batch, which wakes the
|
||||||
|
// flush goroutine to write it.
|
||||||
asnBatchSize = 30000
|
asnBatchSize = 30000
|
||||||
|
|
||||||
// asnBatchMaxSize is the most ASN operations the batch holds while the
|
|
||||||
// flush goroutine writes the previous one: ten batches, about 10 MiB
|
|
||||||
// (README "Memory"). At this size HandleMessage waits until the flush
|
|
||||||
// goroutine takes the batch.
|
|
||||||
asnBatchMaxSize = 300000
|
|
||||||
|
|
||||||
// asnBatchTimeout is the maximum time to wait before flushing a batch
|
// asnBatchTimeout is the maximum time to wait before flushing a batch
|
||||||
// DO NOT reduce this timeout - larger batches are more efficient
|
// DO NOT reduce this timeout - larger batches are more efficient
|
||||||
asnBatchTimeout = 2 * time.Second
|
asnBatchTimeout = 2 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
// ASHandler processes Autonomous System Number (ASN) information extracted from
|
// ASHandler records every AS in the AS paths of BGP UPDATE messages. Its batch
|
||||||
// BGP UPDATE messages. It uses batched database operations to efficiently store
|
// holds the earliest and the latest time of each AS's updates. The flush
|
||||||
// ASN data, collecting operations into batches that are flushed either when the
|
// goroutine writes the batch to the database when it holds asnBatchSize ASes,
|
||||||
// batch reaches a size threshold or after a timeout period.
|
// and every asnBatchTimeout.
|
||||||
type ASHandler struct {
|
type ASHandler struct {
|
||||||
db database.Store
|
db database.Store
|
||||||
logger *logger.Logger
|
logger *logger.Logger
|
||||||
|
|
||||||
// batchMaxSize is asnBatchMaxSize. Only HandleMessage reads it, so a test
|
// Batching. mu guards batch and writing only. The flush goroutine takes
|
||||||
// may lower it before it hands the handler a message.
|
// the batch under mu and writes it after releasing mu. So HandleMessage
|
||||||
batchMaxSize int
|
// never waits for a database write.
|
||||||
|
mu sync.Mutex
|
||||||
// Batching. mu guards batch and writing only: the flush goroutine takes
|
// batch holds the earliest and the latest time of the updates for each AS
|
||||||
// the batch under mu and writes it after releasing mu, so HandleMessage
|
// since the flush goroutine last took it. It holds one entry per AS,
|
||||||
// waits for a database write only while batch is at batchMaxSize.
|
// however many updates arrive.
|
||||||
mu sync.Mutex
|
batch map[int]database.SeenTimes
|
||||||
batch []asnOp
|
// writing is how many ASes the flush goroutine took from batch and has
|
||||||
// writing is how many operations the flush goroutine took from batch
|
// not finished writing.
|
||||||
// and has not finished writing.
|
writing int
|
||||||
writing int
|
|
||||||
// batchTaken is signalled when the flush goroutine takes batch; its L is
|
|
||||||
// &mu.
|
|
||||||
batchTaken sync.Cond
|
|
||||||
batchFullCh chan struct{} // wakes the flush goroutine when batch is full
|
batchFullCh chan struct{} // wakes the flush goroutine when batch is full
|
||||||
// stopCh hands Stop's context to the flush goroutine. It holds one, so
|
// stopCh hands Stop's context to the flush goroutine. It holds one, so
|
||||||
// Stop does not wait for a write in progress to hand it over.
|
// Stop does not wait for a write in progress to hand it over.
|
||||||
@@ -62,16 +53,10 @@ type ASHandler struct {
|
|||||||
done chan struct{} // closed when the flush goroutine returns
|
done chan struct{} // closed when the flush goroutine returns
|
||||||
}
|
}
|
||||||
|
|
||||||
type asnOp struct {
|
|
||||||
number int
|
|
||||||
timestamp time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewASHandler creates and returns a new ASHandler instance. It initializes
|
// NewASHandler creates and returns a new ASHandler instance. It initializes
|
||||||
// the batching system and starts a background goroutine that periodically
|
// the batching system and starts a background goroutine that periodically
|
||||||
// flushes accumulated ASN operations to the database. The caller must call
|
// writes the collected ASes to the database. The caller must call Stop when
|
||||||
// Stop when finished to ensure all pending operations are flushed and the
|
// finished, to write the pending ASes and end the background goroutine.
|
||||||
// background goroutine is terminated.
|
|
||||||
func NewASHandler(db database.Store, logger *logger.Logger) *ASHandler {
|
func NewASHandler(db database.Store, logger *logger.Logger) *ASHandler {
|
||||||
return newASHandler(db, logger, asnBatchTimeout)
|
return newASHandler(db, logger, asnBatchTimeout)
|
||||||
}
|
}
|
||||||
@@ -83,15 +68,13 @@ func newASHandler(
|
|||||||
db database.Store, logger *logger.Logger, batchTimeout time.Duration,
|
db database.Store, logger *logger.Logger, batchTimeout time.Duration,
|
||||||
) *ASHandler {
|
) *ASHandler {
|
||||||
h := &ASHandler{
|
h := &ASHandler{
|
||||||
db: db,
|
db: db,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
batchMaxSize: asnBatchMaxSize,
|
batch: make(map[int]database.SeenTimes),
|
||||||
batch: make([]asnOp, 0, asnBatchSize),
|
batchFullCh: make(chan struct{}, 1),
|
||||||
batchFullCh: make(chan struct{}, 1),
|
stopCh: make(chan context.Context, 1),
|
||||||
stopCh: make(chan context.Context, 1),
|
done: make(chan struct{}),
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
}
|
||||||
h.batchTaken.L = &h.mu
|
|
||||||
|
|
||||||
// Start the flush timer goroutine
|
// Start the flush timer goroutine
|
||||||
go flushLoop(batchTimeout, h.batchFullCh, h.stopCh, h.done, h.flushBatch)
|
go flushLoop(batchTimeout, h.batchFullCh, h.stopCh, h.done, h.flushBatch)
|
||||||
@@ -115,48 +98,25 @@ func (h *ASHandler) QueueCapacity() int {
|
|||||||
return asHandlerQueueSize
|
return asHandlerQueueSize
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleMessage processes a RIS Live BGP message by extracting all ASNs from
|
// HandleMessage adds the time of msg to the batch entry of each AS in its AS
|
||||||
// the AS path and queuing them for batch insertion into the database. The
|
// path, the origin AS and the members of an AS set included. When the batch
|
||||||
// origin ASN and all transit ASNs are recorded with their associated
|
// holds asnBatchSize ASes, HandleMessage wakes the flush goroutine to write it.
|
||||||
// timestamps. When the batch reaches the configured size threshold, the flush
|
|
||||||
// goroutine is woken to write it.
|
|
||||||
func (h *ASHandler) HandleMessage(msg *ristypes.RISMessage) {
|
func (h *ASHandler) HandleMessage(msg *ristypes.RISMessage) {
|
||||||
// Use the pre-parsed timestamp
|
|
||||||
timestamp := msg.ParsedTimestamp
|
|
||||||
|
|
||||||
originASN := msg.Path.Origin()
|
|
||||||
|
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
defer h.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
// While the batch is at its maximum size, wait until the flush goroutine
|
// The origin AS is the last AS of the sequence, so the loop adds it too.
|
||||||
// takes it. Meanwhile the handler takes nothing off its queue, which
|
|
||||||
// fills, and the streamer drops messages for it.
|
|
||||||
for len(h.batch) >= h.batchMaxSize {
|
|
||||||
h.batchTaken.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Queue origin ASN operation
|
|
||||||
if originASN > 0 {
|
|
||||||
h.batch = append(h.batch, asnOp{
|
|
||||||
number: originASN,
|
|
||||||
timestamp: timestamp,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also track all ASNs in the path, the members of an AS set included
|
|
||||||
for _, asn := range slices.Concat(msg.Path.Sequence, msg.Path.Set) {
|
for _, asn := range slices.Concat(msg.Path.Sequence, msg.Path.Set) {
|
||||||
if asn > 0 {
|
if asn > 0 {
|
||||||
h.batch = append(h.batch, asnOp{
|
seen := h.batch[asn]
|
||||||
number: asn,
|
seen.Add(msg.ParsedTimestamp)
|
||||||
timestamp: timestamp,
|
h.batch[asn] = seen
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A full batch wakes the flush goroutine. If it is writing, the wake-up
|
// A full batch wakes the flush goroutine. If it is writing, the wake-up
|
||||||
// waits in batchFullCh and the batch keeps growing until the write ends
|
// waits in batchFullCh and the batch keeps taking updates until the write
|
||||||
// or the batch reaches batchMaxSize.
|
// ends.
|
||||||
if len(h.batch) >= asnBatchSize {
|
if len(h.batch) >= asnBatchSize {
|
||||||
select {
|
select {
|
||||||
case h.batchFullCh <- struct{}{}:
|
case h.batchFullCh <- struct{}{}:
|
||||||
@@ -165,10 +125,11 @@ func (h *ASHandler) HandleMessage(msg *ristypes.RISMessage) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop stops the flush goroutine, which writes the operations the handler holds
|
// Stop stops the flush goroutine and waits for it until ctx ends. The flush
|
||||||
// before it returns, and waits for it until ctx ends. Once ctx has ended the
|
// goroutine writes the batch before it returns, unless ctx has ended. A write
|
||||||
// flush goroutine skips that last write, and a write still running is lost
|
// still running when the process exits is lost. Stop logs how many entries are
|
||||||
// when the process exits, so Stop logs how many operations are not written.
|
// not written, in the batch being written and in the next batch. An AS in both
|
||||||
|
// batches counts twice.
|
||||||
func (h *ASHandler) Stop(ctx context.Context) {
|
func (h *ASHandler) Stop(ctx context.Context) {
|
||||||
h.stopCh <- ctx
|
h.stopCh <- ctx
|
||||||
|
|
||||||
@@ -183,14 +144,14 @@ func (h *ASHandler) Stop(ctx context.Context) {
|
|||||||
|
|
||||||
if unwritten > 0 {
|
if unwritten > 0 {
|
||||||
h.logger.Error("Stop deadline passed before the AS handler wrote "+
|
h.logger.Error("Stop deadline passed before the AS handler wrote "+
|
||||||
"its updates", "updates", unwritten)
|
"its batches", "batch_entries", unwritten)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// takeBatch returns the pending operations and leaves an empty batch in their
|
// takeBatch returns the pending ASes and leaves an empty batch in their place
|
||||||
// place for HandleMessage to fill. They count in writing until flushBatch has
|
// for HandleMessage to fill. They count in writing until flushBatch has written
|
||||||
// written them.
|
// them.
|
||||||
func (h *ASHandler) takeBatch() []asnOp {
|
func (h *ASHandler) takeBatch() map[int]database.SeenTimes {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
defer h.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
@@ -200,8 +161,7 @@ func (h *ASHandler) takeBatch() []asnOp {
|
|||||||
|
|
||||||
batch := h.batch
|
batch := h.batch
|
||||||
h.writing = len(batch)
|
h.writing = len(batch)
|
||||||
h.batch = make([]asnOp, 0, asnBatchSize)
|
h.batch = make(map[int]database.SeenTimes)
|
||||||
h.batchTaken.Broadcast()
|
|
||||||
|
|
||||||
return batch
|
return batch
|
||||||
}
|
}
|
||||||
@@ -214,21 +174,11 @@ func (h *ASHandler) flushBatch() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The earliest and the latest time the batch saw each AS. The batch holds
|
|
||||||
// several updates for an AS, from many peers, so a new AS is stored first
|
|
||||||
// seen at the earliest of them and last seen at the latest.
|
|
||||||
asns := make(map[int]database.SeenTimes)
|
|
||||||
for _, op := range batch {
|
|
||||||
seen := asns[op.number]
|
|
||||||
seen.Add(op.timestamp)
|
|
||||||
asns[op.number] = seen
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process all ASNs in a single batch transaction
|
// Process all ASNs in a single batch transaction
|
||||||
err := h.db.GetOrCreateASNBatch(asns)
|
err := h.db.GetOrCreateASNBatch(batch)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Error("Failed to process ASN batch",
|
h.logger.Error("Failed to process ASN batch",
|
||||||
"error", err, "count", len(asns))
|
"error", err, "count", len(batch))
|
||||||
}
|
}
|
||||||
|
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
|
|||||||
@@ -5,28 +5,43 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||||
|
"git.eeqj.de/sneak/routewatch/internal/ristypes"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// pathOfASes returns an AS path of n different ASes: AS 1 to AS n. With n up to
|
||||||
|
// asnBatchSize, none of them is testASNA to testASND.
|
||||||
|
func pathOfASes(n int) ristypes.ASPath {
|
||||||
|
sequence := make([]int, n)
|
||||||
|
for i := range sequence {
|
||||||
|
sequence[i] = i + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return ristypes.ASPath{Sequence: sequence}
|
||||||
|
}
|
||||||
|
|
||||||
// TestASHandlerStoresTheEarliestAndLatestTimesOfANewAS handles two updates
|
// TestASHandlerStoresTheEarliestAndLatestTimesOfANewAS handles two updates
|
||||||
// whose path carries an AS the database does not hold yet, the second 5
|
// whose path carries an AS the database does not hold yet, in one batch into a
|
||||||
// seconds after the first, in one batch into a real database. The AS is stored
|
// real database. The second is 5 seconds after the first, and the handler gets
|
||||||
// first seen at the time of the first update and last seen at the time of the
|
// it first. The AS is stored first seen at the time of the first update and
|
||||||
// second.
|
// last seen at the time of the second.
|
||||||
func TestASHandlerStoresTheEarliestAndLatestTimesOfANewAS(t *testing.T) {
|
func TestASHandlerStoresTheEarliestAndLatestTimesOfANewAS(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
db := newTestDatabase(t)
|
db := newTestDatabase(t)
|
||||||
|
|
||||||
// Built without NewASHandler's flush goroutine, so the test flushes itself.
|
// Built without NewASHandler's flush goroutine, so the test flushes itself.
|
||||||
h := &ASHandler{db: db, logger: logger.New(), batchMaxSize: asnBatchMaxSize}
|
h := &ASHandler{
|
||||||
|
db: db, logger: logger.New(), batch: make(map[int]database.SeenTimes),
|
||||||
|
}
|
||||||
|
|
||||||
first := peerAnnouncement(testPeerIP, testV4Prefix)
|
first := peerAnnouncement(testPeerIP, testV4Prefix)
|
||||||
second := peerAnnouncement(testPeerIP, testV4Prefix)
|
second := peerAnnouncement(testPeerIP, testV4Prefix)
|
||||||
second.ParsedTimestamp = first.ParsedTimestamp.Add(secondUpdateAfter)
|
second.ParsedTimestamp = first.ParsedTimestamp.Add(secondUpdateAfter)
|
||||||
|
|
||||||
h.HandleMessage(first)
|
|
||||||
h.HandleMessage(second)
|
h.HandleMessage(second)
|
||||||
|
h.HandleMessage(first)
|
||||||
h.flushBatch()
|
h.flushBatch()
|
||||||
|
|
||||||
asn, _, err := db.GetAS(t.Context(), testASNA)
|
asn, _, err := db.GetAS(t.Context(), testASNA)
|
||||||
@@ -54,7 +69,9 @@ func TestASHandlerRecordsNothingFromAPathWithASZero(t *testing.T) {
|
|||||||
store := newMockStore()
|
store := newMockStore()
|
||||||
|
|
||||||
// Built without NewASHandler's flush goroutine, so the test flushes itself.
|
// Built without NewASHandler's flush goroutine, so the test flushes itself.
|
||||||
h := &ASHandler{db: store, logger: logger.New(), batchMaxSize: asnBatchMaxSize}
|
h := &ASHandler{
|
||||||
|
db: store, logger: logger.New(), batch: make(map[int]database.SeenTimes),
|
||||||
|
}
|
||||||
|
|
||||||
msg := peerAnnouncement(testPeerIP, testV4Prefix)
|
msg := peerAnnouncement(testPeerIP, testV4Prefix)
|
||||||
msg.Path = decodePath(t, testASNA, 0, testASNB)
|
msg.Path = decodePath(t, testASNA, 0, testASNB)
|
||||||
|
|||||||
@@ -287,6 +287,13 @@ func (f *ASNFetcher) fetchNextStale(ctx context.Context) {
|
|||||||
// so the AS stays stale. An AS IANA refers to no RIR is stored with no
|
// so the AS stays stale. An AS IANA refers to no RIR is stored with no
|
||||||
// WHOIS data, so it is not looked up again until it is stale; that counts
|
// WHOIS data, so it is not looked up again until it is stale; that counts
|
||||||
// as neither a success nor a failure.
|
// as neither a success nor a failure.
|
||||||
|
//
|
||||||
|
// The WHOIS client pauses an RIR's or NIC.br's server for whois.PauseTime
|
||||||
|
// after the server refuses a query. Lookups at the other servers go on. IANA
|
||||||
|
// is never paused, so a refusal by IANA is an ordinary failure. A lookup
|
||||||
|
// whose RIR is paused fails with whois.ErrPaused. Such a lookup leaves the
|
||||||
|
// AS stale, and counts as neither a success nor a failure. The lookups that
|
||||||
|
// QueueImmediate asks for also run through fetchAndUpdate.
|
||||||
func (f *ASNFetcher) fetchAndUpdate(ctx context.Context, asn int) bool {
|
func (f *ASNFetcher) fetchAndUpdate(ctx context.Context, asn int) bool {
|
||||||
ctx, cancel := context.WithTimeout(ctx, time.Minute)
|
ctx, cancel := context.WithTimeout(ctx, time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -307,6 +314,13 @@ func (f *ASNFetcher) fetchAndUpdate(ctx context.Context, asn int) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, whois.ErrPaused) {
|
||||||
|
f.logger.Info("Skipped WHOIS lookup, the RIR's server is paused",
|
||||||
|
"asn", asn, "error", err)
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
f.logger.Error("WHOIS lookup failed", "asn", asn, "error", err)
|
f.logger.Error("WHOIS lookup failed", "asn", asn, "error", err)
|
||||||
f.recordFailure()
|
f.recordFailure()
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
|
|
||||||
"git.eeqj.de/sneak/routewatch/internal/database"
|
"git.eeqj.de/sneak/routewatch/internal/database"
|
||||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||||
|
"git.eeqj.de/sneak/routewatch/internal/whois"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The WHOIS servers a lookup asks: IANA first, then the RIR IANA refers it
|
// The WHOIS servers a lookup asks: IANA first, then the RIR IANA refers it
|
||||||
@@ -131,6 +132,109 @@ func TestFetchAndUpdateKeepsTheRowWhenTheLookupFails(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFetchAndUpdateWaitsOutAPause looks up an AS at RIPE while RIPE refuses
|
||||||
|
// the query. The test sets the WHOIS client's clock. The next lookup comes a
|
||||||
|
// second before whois.PauseTime has passed. It sends RIPE nothing and leaves
|
||||||
|
// the AS never looked up. It counts as neither a success nor a failure. A
|
||||||
|
// lookup at whois.PauseTime asks RIPE again.
|
||||||
|
func TestFetchAndUpdateWaitsOutAPause(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
f, db := newFetcherWithWHOISAnswers(t, map[string]string{
|
||||||
|
ianaWHOISServer: ianaRefersToRIPE,
|
||||||
|
ripeWHOISServer: ripeAccessDenied,
|
||||||
|
})
|
||||||
|
|
||||||
|
ripeAsks := 0
|
||||||
|
dial := f.whoisClient.DialContext
|
||||||
|
f.whoisClient.DialContext = func(
|
||||||
|
ctx context.Context, network, address string,
|
||||||
|
) (net.Conn, error) {
|
||||||
|
if address == ripeWHOISServer {
|
||||||
|
ripeAsks++
|
||||||
|
}
|
||||||
|
|
||||||
|
return dial(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
now := start
|
||||||
|
f.whoisClient.Now = func() time.Time { return now }
|
||||||
|
|
||||||
|
f.fetchAndUpdate(t.Context(), testASNA)
|
||||||
|
|
||||||
|
now = start.Add(whois.PauseTime - time.Second)
|
||||||
|
|
||||||
|
f.fetchAndUpdate(t.Context(), testASNA)
|
||||||
|
|
||||||
|
if ripeAsks != 1 {
|
||||||
|
t.Errorf("RIPE was asked %d times during its pause, want 1", ripeAsks)
|
||||||
|
}
|
||||||
|
|
||||||
|
stats, err := db.GetWHOISStats(t.Context(), whoisStaleThreshold)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetWHOISStats: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if stats.NeverFetched != 1 {
|
||||||
|
t.Errorf("never looked up = %d, want 1", stats.NeverFetched)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := f.GetStats()
|
||||||
|
if got.ConsecutiveFails != 1 || got.ErrorsLastHour != 1 ||
|
||||||
|
got.SuccessesLastHour != 0 {
|
||||||
|
t.Errorf("%d failures in a row, %d errors, %d successes; want 1, 1, 0",
|
||||||
|
got.ConsecutiveFails, got.ErrorsLastHour, got.SuccessesLastHour)
|
||||||
|
}
|
||||||
|
|
||||||
|
now = start.Add(whois.PauseTime)
|
||||||
|
|
||||||
|
f.fetchAndUpdate(t.Context(), testASNA)
|
||||||
|
|
||||||
|
if ripeAsks != 2 {
|
||||||
|
t.Errorf("RIPE was asked %d times after its pause, want 2", ripeAsks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFetchAndUpdateKeepsAskingIANA looks up an AS while IANA's server
|
||||||
|
// refuses the connection. The test sets the WHOIS client's clock. The next
|
||||||
|
// lookup comes a second before whois.PauseTime has passed. IANA is never
|
||||||
|
// paused, so that lookup asks IANA again. Each refusal counts as a failure.
|
||||||
|
func TestFetchAndUpdateKeepsAskingIANA(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// With no answers, every server refuses the connection.
|
||||||
|
f, _ := newFetcherWithWHOISAnswers(t, map[string]string{})
|
||||||
|
|
||||||
|
ianaAsks := 0
|
||||||
|
dial := f.whoisClient.DialContext
|
||||||
|
f.whoisClient.DialContext = func(
|
||||||
|
ctx context.Context, network, address string,
|
||||||
|
) (net.Conn, error) {
|
||||||
|
if address == ianaWHOISServer {
|
||||||
|
ianaAsks++
|
||||||
|
}
|
||||||
|
|
||||||
|
return dial(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
now := start
|
||||||
|
f.whoisClient.Now = func() time.Time { return now }
|
||||||
|
|
||||||
|
f.fetchAndUpdate(t.Context(), testASNA)
|
||||||
|
|
||||||
|
now = start.Add(whois.PauseTime - time.Second)
|
||||||
|
|
||||||
|
f.fetchAndUpdate(t.Context(), testASNA)
|
||||||
|
|
||||||
|
got := f.GetStats()
|
||||||
|
if ianaAsks != 2 || got.ConsecutiveFails != 2 {
|
||||||
|
t.Errorf("IANA was asked %d times, with %d failures in a row; "+
|
||||||
|
"want 2 and 2", ianaAsks, got.ConsecutiveFails)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestRecordStepsTheInterval has the fetcher fail from its base interval of
|
// TestRecordStepsTheInterval has the fetcher fail from its base interval of
|
||||||
// 15 seconds, then succeed. Each failure makes the interval 1.5 times as
|
// 15 seconds, then succeed. Each failure makes the interval 1.5 times as
|
||||||
// long, up to one minute, and each success halves it, down to one second.
|
// long, up to one minute, and each success halves it, down to one second.
|
||||||
|
|||||||
@@ -178,6 +178,7 @@ type stopLog struct {
|
|||||||
Updates int `json:"updates"`
|
Updates int `json:"updates"`
|
||||||
TableChanges int `json:"table_changes"`
|
TableChanges int `json:"table_changes"`
|
||||||
Paths int `json:"paths"`
|
Paths int `json:"paths"`
|
||||||
|
BatchEntries int `json:"batch_entries"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// newErrorLogger returns a logger that writes only errors, as JSON lines, to
|
// newErrorLogger returns a logger that writes only errors, as JSON lines, to
|
||||||
@@ -495,20 +496,20 @@ func TestPrefixHandlerStopCountsTheTableChangesOfAWriteInProgress(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestASHandlerSkipsItsLastWriteAfterTheStopDeadline also checks what Stop
|
||||||
|
// logs: the asnBatchSize entries of the held write and the entry for testASNB,
|
||||||
|
// handled since, are not written.
|
||||||
func TestASHandlerSkipsItsLastWriteAfterTheStopDeadline(t *testing.T) {
|
func TestASHandlerSkipsItsLastWriteAfterTheStopDeadline(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
// Each message gives an update for its origin AS and one for each AS
|
const wantEntries = asnBatchSize + 1
|
||||||
// in its path: fill asnBatchSize+1, extra 2.
|
|
||||||
const wantUpdates = asnBatchSize + 1 + 2
|
|
||||||
|
|
||||||
var logs bytes.Buffer
|
var logs bytes.Buffer
|
||||||
|
|
||||||
store := newBlockingStore()
|
store := newBlockingStore()
|
||||||
h := newASHandler(store, newErrorLogger(&logs), longerThanAnyTest)
|
h := newASHandler(store, newErrorLogger(&logs), longerThanAnyTest)
|
||||||
fill := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
|
||||||
stopWhileAWriteIsBlocked(t, store, h, h.done,
|
stopWhileAWriteIsBlocked(t, store, h, h.done,
|
||||||
[]*ristypes.RISMessage{{Path: fill}},
|
[]*ristypes.RISMessage{{Path: pathOfASes(asnBatchSize)}},
|
||||||
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
||||||
|
|
||||||
store.mu.Lock()
|
store.mu.Lock()
|
||||||
@@ -518,26 +519,27 @@ func TestASHandlerSkipsItsLastWriteAfterTheStopDeadline(t *testing.T) {
|
|||||||
t.Errorf("AS%d was written after the stop deadline", testASNB)
|
t.Errorf("AS%d was written after the stop deadline", testASNB)
|
||||||
}
|
}
|
||||||
|
|
||||||
if logged := lastLogged(t, &logs); logged.Updates != wantUpdates {
|
if logged := lastLogged(t, &logs); logged.BatchEntries != wantEntries {
|
||||||
t.Errorf("Stop logged %d updates not written, want %d",
|
t.Errorf("Stop logged %d batch entries not written, want %d",
|
||||||
logged.Updates, wantUpdates)
|
logged.BatchEntries, wantEntries)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestASHandlerSkipsAFullBatchAfterTheStopDeadline hands the AS handler a full
|
// TestASHandlerSkipsAFullBatchAfterTheStopDeadline hands the AS handler a full
|
||||||
// batch while a write is held, so the batch's wake-up of the flush goroutine
|
// batch while a write is held, so the batch's wake-up of the flush goroutine
|
||||||
// waits. The stop deadline passes meanwhile. When the write ends, the flush
|
// waits. The full batch holds the fill's ASes again, and testASNB. The stop
|
||||||
// goroutine must stop instead of writing the batch.
|
// deadline passes meanwhile. When the write ends, the flush goroutine must stop
|
||||||
|
// instead of writing the batch.
|
||||||
func TestASHandlerSkipsAFullBatchAfterTheStopDeadline(t *testing.T) {
|
func TestASHandlerSkipsAFullBatchAfterTheStopDeadline(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
store := newBlockingStore()
|
store := newBlockingStore()
|
||||||
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
||||||
fill := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
fill := &ristypes.RISMessage{Path: pathOfASes(asnBatchSize)}
|
||||||
full := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNB}, asnBatchSize)}
|
|
||||||
stopWhileAWriteIsBlocked(t, store, h, h.done,
|
stopWhileAWriteIsBlocked(t, store, h, h.done,
|
||||||
[]*ristypes.RISMessage{{Path: fill}},
|
[]*ristypes.RISMessage{fill},
|
||||||
&ristypes.RISMessage{Path: full})
|
fill,
|
||||||
|
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
||||||
|
|
||||||
store.mu.Lock()
|
store.mu.Lock()
|
||||||
defer store.mu.Unlock()
|
defer store.mu.Unlock()
|
||||||
@@ -703,9 +705,8 @@ func TestASHandlerHandlesMessagesWhileAWriteIsBlocked(t *testing.T) {
|
|||||||
|
|
||||||
store := newBlockingStore()
|
store := newBlockingStore()
|
||||||
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
||||||
fill := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
|
||||||
handleWhileAWriteIsBlocked(t, store, h,
|
handleWhileAWriteIsBlocked(t, store, h,
|
||||||
[]*ristypes.RISMessage{{Path: fill}},
|
[]*ristypes.RISMessage{{Path: pathOfASes(asnBatchSize)}},
|
||||||
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
||||||
|
|
||||||
store.mu.Lock()
|
store.mu.Lock()
|
||||||
@@ -762,25 +763,41 @@ func TestPrefixHandlerWaitsAtTheMaximumBatchSize(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestASHandlerWaitsAtTheMaximumBatchSize(t *testing.T) {
|
// TestASHandlerNeverWaitsForAWrite starts a write that the store holds. Then it
|
||||||
|
// hands the AS handler twenty messages whose paths each hold one AS
|
||||||
|
// asnBatchSize times. HandleMessage must return each time, and the batch must
|
||||||
|
// hold one entry, for that AS.
|
||||||
|
func TestASHandlerNeverWaitsForAWrite(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
const messages = 20
|
||||||
|
|
||||||
store := newBlockingStore()
|
store := newBlockingStore()
|
||||||
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
h := newASHandler(store, logger.New(), longerThanAnyTest)
|
||||||
h.batchMaxSize = asnBatchSize
|
|
||||||
fill := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
|
||||||
toMax := ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, asnBatchSize)}
|
|
||||||
handleAtMaxBatchSize(t, store, h,
|
|
||||||
[]*ristypes.RISMessage{{Path: fill}},
|
|
||||||
[]*ristypes.RISMessage{{Path: toMax}},
|
|
||||||
&ristypes.RISMessage{Path: ristypes.ASPath{Sequence: []int{testASNB}}})
|
|
||||||
|
|
||||||
store.mu.Lock()
|
defer stopInTime(t, h)
|
||||||
defer store.mu.Unlock()
|
defer store.releaseWrites()
|
||||||
|
|
||||||
if !store.asns[testASNB] {
|
startBlockedWrite(t, store, h,
|
||||||
t.Errorf("Stop did not write AS%d, handled after the batch reached its "+
|
[]*ristypes.RISMessage{{Path: pathOfASes(asnBatchSize)}})
|
||||||
"maximum size", testASNB)
|
|
||||||
|
oneAS := &ristypes.RISMessage{
|
||||||
|
Path: ristypes.ASPath{Sequence: slices.Repeat([]int{testASNB}, asnBatchSize)},
|
||||||
|
}
|
||||||
|
|
||||||
|
if !returnsInTime(func() {
|
||||||
|
for range messages {
|
||||||
|
h.HandleMessage(oneAS)
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
t.Fatal("HandleMessage did not return while a database write was blocked")
|
||||||
|
}
|
||||||
|
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
|
if len(h.batch) != 1 {
|
||||||
|
t.Errorf("the batch holds %d entries for one AS, want 1", len(h.batch))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -844,13 +861,11 @@ func TestHandlersWakeTheFlushGoroutineWhenTheBatchIsFull(t *testing.T) {
|
|||||||
batchSize: asnBatchSize,
|
batchSize: asnBatchSize,
|
||||||
handle: func(n int) chan struct{} {
|
handle: func(n int) chan struct{} {
|
||||||
h := &ASHandler{
|
h := &ASHandler{
|
||||||
batchMaxSize: asnBatchMaxSize,
|
batch: make(map[int]database.SeenTimes),
|
||||||
batchFullCh: make(chan struct{}, 1),
|
batchFullCh: make(chan struct{}, 1),
|
||||||
}
|
}
|
||||||
// The origin AS and each AS in the path are one update each.
|
// Each of the path's n ASes is one entry of the batch.
|
||||||
h.HandleMessage(&ristypes.RISMessage{
|
h.HandleMessage(&ristypes.RISMessage{Path: pathOfASes(n)})
|
||||||
Path: ristypes.ASPath{Sequence: slices.Repeat([]int{testASNA}, n-1)},
|
|
||||||
})
|
|
||||||
|
|
||||||
return h.batchFullCh
|
return h.batchFullCh
|
||||||
},
|
},
|
||||||
|
|||||||
+82
-36
@@ -12,6 +12,7 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
@@ -70,12 +71,12 @@ const nicbrHeader = "% Copyright (c) Nic.br"
|
|||||||
// queries to stop the data being taken in bulk.
|
// queries to stop the data being taken in bulk.
|
||||||
const nicbrLimitReached = "Query rate limit exceeded"
|
const nicbrLimitReached = "Query rate limit exceeded"
|
||||||
|
|
||||||
// NICbrSkipTime is how long the client stops asking NIC.br after NIC.br
|
// PauseTime is how long the client sends an RIR's or NIC.br's server no
|
||||||
// answers that the client is over its query limit. NIC.br publishes
|
// query after that server refuses a query. queryRegistry says what a
|
||||||
// neither the limit nor how long it lasts. An hour outlasts a limit
|
// refusal is. RIPE refuses an address for good when the address keeps
|
||||||
// counted per minute or per hour. The ASes looked up meanwhile get
|
// passing RIPE's limit (see noPersonalFlag). An hour outlasts a limit
|
||||||
// NIC.br's fields when they are next refreshed.
|
// counted per minute or per hour.
|
||||||
const NICbrSkipTime = time.Hour
|
const PauseTime = time.Hour
|
||||||
|
|
||||||
// RIR identifiers.
|
// RIR identifiers.
|
||||||
const (
|
const (
|
||||||
@@ -125,6 +126,10 @@ var (
|
|||||||
errAnswerTooLarge = errors.New("WHOIS answer reached the size cap")
|
errAnswerTooLarge = errors.New("WHOIS answer reached the size cap")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrPaused is returned when a lookup needs a server that refused a query
|
||||||
|
// less than PauseTime ago. The client sends that server nothing meanwhile.
|
||||||
|
var ErrPaused = errors.New("WHOIS server paused after refusing a query")
|
||||||
|
|
||||||
// ASNInfo contains parsed WHOIS information for an ASN.
|
// ASNInfo contains parsed WHOIS information for an ASN.
|
||||||
type ASNInfo struct {
|
type ASNInfo struct {
|
||||||
ASN int
|
ASN int
|
||||||
@@ -156,12 +161,12 @@ type Client struct {
|
|||||||
|
|
||||||
logger *slog.Logger
|
logger *slog.Logger
|
||||||
|
|
||||||
// mu guards nicbrSkipUntil.
|
// mu guards pausedUntil.
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
|
||||||
// nicbrSkipUntil is when the client next asks NIC.br, after NIC.br
|
// pausedUntil maps a server, given as host:port, to the time the client
|
||||||
// answered that the client is over its query limit.
|
// may ask it again.
|
||||||
nicbrSkipUntil time.Time
|
pausedUntil map[string]time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates a new WHOIS client that logs to logger.
|
// NewClient creates a new WHOIS client that logs to logger.
|
||||||
@@ -172,23 +177,29 @@ func NewClient(logger *slog.Logger) *Client {
|
|||||||
DialContext: dialer.DialContext,
|
DialContext: dialer.DialContext,
|
||||||
Now: time.Now,
|
Now: time.Now,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
|
pausedUntil: make(map[string]time.Time),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// LookupASN asks IANA which RIR holds the given ASN, asks that RIR, and
|
// LookupASN asks IANA which RIR holds the given ASN, asks that RIR, and
|
||||||
// returns what the RIR's answer says. When LACNIC's answer is NIC.br's, it
|
// returns what the RIR's answer says. When LACNIC's answer is NIC.br's, it
|
||||||
// returns what NIC.br's own server says instead, unless that query fails or
|
// returns what NIC.br's own server says instead, unless that query fails or
|
||||||
// is skipped, as askNICbr says.
|
// NIC.br is paused, as askNICbr says.
|
||||||
//
|
//
|
||||||
// It returns ErrNoReferral when IANA refers the AS to no RIR, and another
|
// It returns ErrNoReferral when IANA refers the AS to no RIR. Its error
|
||||||
// error when the query to IANA or to the RIR fails, when the RIR refuses
|
// wraps ErrPaused when the RIR is paused. It returns another error in each
|
||||||
// it, when IANA's answer has neither a referral nor the AS's block, when
|
// of these cases:
|
||||||
// IANA refers the AS to a server none of the five RIRs run, or when the
|
//
|
||||||
// answer carries none of ASNInfo's fields.
|
// - the query to IANA or to the RIR fails
|
||||||
|
// - the RIR refuses the query
|
||||||
|
// - IANA's answer has neither a referral nor the AS's block
|
||||||
|
// - IANA refers the AS to a server none of the five RIRs run
|
||||||
|
// - the answer carries none of ASNInfo's fields
|
||||||
func (c *Client) LookupASN(ctx context.Context, asn int) (*ASNInfo, error) {
|
func (c *Client) LookupASN(ctx context.Context, asn int) (*ASNInfo, error) {
|
||||||
// Query IANA first to find the authoritative RIR
|
// Query IANA first to find the authoritative RIR
|
||||||
query := fmt.Sprintf("AS%d", asn)
|
query := fmt.Sprintf("AS%d", asn)
|
||||||
|
|
||||||
|
// IANA is never paused, because a pause of IANA would stop every lookup.
|
||||||
ianaResp, err := c.query(ctx, whoisServerIANA, query)
|
ianaResp, err := c.query(ctx, whoisServerIANA, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("IANA query failed: %w", err)
|
return nil, fmt.Errorf("IANA query failed: %w", err)
|
||||||
@@ -211,7 +222,7 @@ func (c *Client) LookupASN(ctx context.Context, asn int) (*ASNInfo, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Query the authoritative RIR
|
// Query the authoritative RIR
|
||||||
rirResp, err := c.queryRIR(ctx, whoisServer, rirQuery(rir, query))
|
rirResp, err := c.queryRegistry(ctx, whoisServer, rirQuery(rir, query))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("RIR query failed: %w", err)
|
return nil, fmt.Errorf("RIR query failed: %w", err)
|
||||||
}
|
}
|
||||||
@@ -241,22 +252,19 @@ func (c *Client) LookupASN(ctx context.Context, asn int) (*ASNInfo, error) {
|
|||||||
// askNICbr returns lacnicInfo, what LACNIC's answer says, and logs a
|
// askNICbr returns lacnicInfo, what LACNIC's answer says, and logs a
|
||||||
// warning when the query fails, when NIC.br sends the reduced answer for a
|
// warning when the query fails, when NIC.br sends the reduced answer for a
|
||||||
// client over its limit, or when NIC.br's answer carries none of ASNInfo's
|
// client over its limit, or when NIC.br's answer carries none of ASNInfo's
|
||||||
// fields. After the reduced answer, it returns lacnicInfo without asking
|
// fields. The reduced answer pauses NIC.br, as a refusal does. While NIC.br
|
||||||
// NIC.br until NICbrSkipTime has passed.
|
// is paused, askNICbr returns lacnicInfo without a warning. The ASes looked
|
||||||
|
// up meanwhile get NIC.br's fields when they are next refreshed.
|
||||||
func (c *Client) askNICbr(
|
func (c *Client) askNICbr(
|
||||||
ctx context.Context, asQuery string, lacnicInfo *ASNInfo,
|
ctx context.Context, asQuery string, lacnicInfo *ASNInfo,
|
||||||
) *ASNInfo {
|
) *ASNInfo {
|
||||||
asn := lacnicInfo.ASN
|
asn := lacnicInfo.ASN
|
||||||
|
|
||||||
c.mu.Lock()
|
answer, err := c.queryRegistry(ctx, whoisServerNICbr, asQuery)
|
||||||
skipping := c.Now().Before(c.nicbrSkipUntil)
|
if errors.Is(err, ErrPaused) {
|
||||||
c.mu.Unlock()
|
|
||||||
|
|
||||||
if skipping {
|
|
||||||
return lacnicInfo
|
return lacnicInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
answer, err := c.query(ctx, whoisServerNICbr, asQuery)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.logger.Warn("NIC.br query failed, keeping LACNIC's fields",
|
c.logger.Warn("NIC.br query failed, keeping LACNIC's fields",
|
||||||
"asn", asn, "error", err)
|
"asn", asn, "error", err)
|
||||||
@@ -265,13 +273,11 @@ func (c *Client) askNICbr(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if strings.Contains(answer, nicbrLimitReached) {
|
if strings.Contains(answer, nicbrLimitReached) {
|
||||||
c.mu.Lock()
|
c.pause(whoisServerNICbr)
|
||||||
c.nicbrSkipUntil = c.Now().Add(NICbrSkipTime)
|
|
||||||
c.mu.Unlock()
|
|
||||||
|
|
||||||
c.logger.Warn("NIC.br answered that the client is over its query "+
|
c.logger.Warn("NIC.br answered that the client is over its query "+
|
||||||
"limit, keeping LACNIC's fields and skipping NIC.br",
|
"limit, keeping LACNIC's fields and pausing NIC.br",
|
||||||
"asn", asn, "skip_for", NICbrSkipTime)
|
"asn", asn, "pause_for", PauseTime)
|
||||||
|
|
||||||
return lacnicInfo
|
return lacnicInfo
|
||||||
}
|
}
|
||||||
@@ -309,25 +315,65 @@ func rirQuery(rir, asQuery string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// queryRIR sends query to an RIR's server and returns the answer. An answer
|
// queryRegistry sends query to the server of an RIR or of NIC.br, and
|
||||||
// holding an error line with which the server refuses the query is an
|
// returns the answer. The client pauses the server for PauseTime when the
|
||||||
// error, and the error holds that line.
|
// server refuses the query. Each of these is a refusal:
|
||||||
func (c *Client) queryRIR(
|
//
|
||||||
|
// - a refused connection
|
||||||
|
// - a reset connection
|
||||||
|
// - an %ERROR:201: or %ERROR:202: line in the answer
|
||||||
|
//
|
||||||
|
// A refusal is returned as an error. While the server is paused,
|
||||||
|
// queryRegistry sends it nothing and returns an error that wraps ErrPaused.
|
||||||
|
func (c *Client) queryRegistry(
|
||||||
ctx context.Context, server, query string,
|
ctx context.Context, server, query string,
|
||||||
) (string, error) {
|
) (string, error) {
|
||||||
|
c.mu.Lock()
|
||||||
|
pausedUntil := c.pausedUntil[server]
|
||||||
|
c.mu.Unlock()
|
||||||
|
|
||||||
|
if c.Now().Before(pausedUntil) {
|
||||||
|
return "", fmt.Errorf("%w: %s until %s", ErrPaused, server,
|
||||||
|
pausedUntil.UTC().Format(time.RFC3339))
|
||||||
|
}
|
||||||
|
|
||||||
answer, err := c.query(ctx, server, query)
|
answer, err := c.query(ctx, server, query)
|
||||||
|
if err == nil {
|
||||||
|
err = checkRefusal(answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, errRefused) || errors.Is(err, syscall.ECONNREFUSED) ||
|
||||||
|
errors.Is(err, syscall.ECONNRESET) {
|
||||||
|
c.pause(server)
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return answer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkRefusal returns an error holding the first line of answer that
|
||||||
|
// starts with accessDeniedError or accessLimitError. It returns nil when
|
||||||
|
// answer has no such line.
|
||||||
|
func checkRefusal(answer string) error {
|
||||||
for line := range strings.SplitSeq(answer, "\n") {
|
for line := range strings.SplitSeq(answer, "\n") {
|
||||||
if strings.HasPrefix(line, accessDeniedError) ||
|
if strings.HasPrefix(line, accessDeniedError) ||
|
||||||
strings.HasPrefix(line, accessLimitError) {
|
strings.HasPrefix(line, accessLimitError) {
|
||||||
return "", fmt.Errorf("%w: %s", errRefused, line)
|
return fmt.Errorf("%w: %s", errRefused, line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return answer, nil
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pause stops queryRegistry from querying server until PauseTime has passed.
|
||||||
|
func (c *Client) pause(server string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
c.pausedUntil[server] = c.Now().Add(PauseTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
// query performs a raw WHOIS query to the specified server and returns the
|
// query performs a raw WHOIS query to the specified server and returns the
|
||||||
|
|||||||
@@ -718,9 +718,10 @@ func TestLookupASNKeepsLACNICsAnswerWhenNICbrFails(t *testing.T) {
|
|||||||
|
|
||||||
// TestLookupASNSkipsNICbrAfterItsLimit looks up an AS that NIC.br
|
// TestLookupASNSkipsNICbrAfterItsLimit looks up an AS that NIC.br
|
||||||
// registers three times with one client, while NIC.br answers that the
|
// registers three times with one client, while NIC.br answers that the
|
||||||
// client is over its query limit. The first lookup asks NIC.br. The
|
// client is over its query limit. The test sets the client's clock. The
|
||||||
// second, a second before NICbrSkipTime has passed, does not. The third,
|
// first lookup asks NIC.br. The next comes a second before PauseTime has
|
||||||
// once NICbrSkipTime has passed, asks again. Each keeps LACNIC's fields.
|
// passed, and does not ask NIC.br. The last comes at PauseTime and asks
|
||||||
|
// NIC.br again. Each keeps LACNIC's fields.
|
||||||
func TestLookupASNSkipsNICbrAfterItsLimit(t *testing.T) {
|
func TestLookupASNSkipsNICbrAfterItsLimit(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -740,8 +741,8 @@ func TestLookupASNSkipsNICbrAfterItsLimit(t *testing.T) {
|
|||||||
wantAsks int
|
wantAsks int
|
||||||
}{
|
}{
|
||||||
{after: 0, wantAsks: 1},
|
{after: 0, wantAsks: 1},
|
||||||
{after: whois.NICbrSkipTime - time.Second, wantAsks: 1},
|
{after: whois.PauseTime - time.Second, wantAsks: 1},
|
||||||
{after: whois.NICbrSkipTime, wantAsks: 2},
|
{after: whois.PauseTime, wantAsks: 2},
|
||||||
} {
|
} {
|
||||||
now = start.Add(step.after)
|
now = start.Add(step.after)
|
||||||
|
|
||||||
@@ -785,6 +786,142 @@ func TestLookupASNReportsARefusal(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resetServer starts a TCP server on the loopback address and returns the
|
||||||
|
// server's address. The server reads one query on each connection, then
|
||||||
|
// resets the connection.
|
||||||
|
func resetServer(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
var listenConfig net.ListenConfig
|
||||||
|
|
||||||
|
listener, err := listenConfig.Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() { _ = listener.Close() })
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
conn, err := listener.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = bufio.NewReader(conn).ReadString('\n')
|
||||||
|
|
||||||
|
// Closing a connection whose linger time is zero resets it.
|
||||||
|
if tcpConn, ok := conn.(*net.TCPConn); ok {
|
||||||
|
_ = tcpConn.SetLinger(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return listener.Addr().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRIPEClient returns a client whose fake servers send answers. The
|
||||||
|
// client adds one to *ripeAsks each time it connects to RIPE's server. When
|
||||||
|
// reset is true, RIPE's server resets the connection instead of answering.
|
||||||
|
func newRIPEClient(
|
||||||
|
t *testing.T, answers map[string]string, reset bool, ripeAsks *int,
|
||||||
|
) *whois.Client {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dial := fakeServers(t, answers)
|
||||||
|
resetAddress := resetServer(t)
|
||||||
|
|
||||||
|
client := whois.NewClient(slog.New(slog.DiscardHandler))
|
||||||
|
client.DialContext = func(
|
||||||
|
ctx context.Context, network, address string,
|
||||||
|
) (net.Conn, error) {
|
||||||
|
if address == ripeServer {
|
||||||
|
*ripeAsks++
|
||||||
|
}
|
||||||
|
|
||||||
|
if address == ripeServer && reset {
|
||||||
|
var dialer net.Dialer
|
||||||
|
|
||||||
|
return dialer.DialContext(ctx, network, resetAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
return dial(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLookupASNPausesAServerThatRefuses looks up an AS at RIPE while RIPE
|
||||||
|
// refuses the query, in each of the ways a server refuses. The test sets
|
||||||
|
// the client's clock. A lookup a second before PauseTime has passed fails
|
||||||
|
// with ErrPaused and asks RIPE nothing. A lookup of an AS at APNIC succeeds
|
||||||
|
// during the pause. A lookup at PauseTime asks RIPE again.
|
||||||
|
func TestLookupASNPausesAServerThatRefuses(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
for name, test := range map[string]struct {
|
||||||
|
// ripeAnswer is RIPE's answer. With none, RIPE's server refuses
|
||||||
|
// the connection, or resets it when reset is true.
|
||||||
|
ripeAnswer string
|
||||||
|
reset bool
|
||||||
|
}{
|
||||||
|
"access denied": {ripeAnswer: ripeRefusal},
|
||||||
|
"limit reached": {ripeAnswer: ripeLimitReached + "\n"},
|
||||||
|
"refused connection": {},
|
||||||
|
"reset connection": {reset: true},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
answers := map[string]string{
|
||||||
|
ianaQuery: ianaReferral,
|
||||||
|
apnicIANAQuery: "refer: whois.apnic.net\n",
|
||||||
|
apnicQuery: apnicRecord,
|
||||||
|
}
|
||||||
|
if test.ripeAnswer != "" {
|
||||||
|
answers[ripeQuery] = test.ripeAnswer
|
||||||
|
}
|
||||||
|
|
||||||
|
ripeAsks := 0
|
||||||
|
client := newRIPEClient(t, answers, test.reset, &ripeAsks)
|
||||||
|
|
||||||
|
start := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
now := start
|
||||||
|
client.Now = func() time.Time { return now }
|
||||||
|
|
||||||
|
_, err := client.LookupASN(t.Context(), testASN)
|
||||||
|
if err == nil || errors.Is(err, whois.ErrPaused) {
|
||||||
|
t.Fatalf("LookupASN while RIPE refuses: error %v, want a "+
|
||||||
|
"refusal", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now = start.Add(whois.PauseTime - time.Second)
|
||||||
|
|
||||||
|
_, err = client.LookupASN(t.Context(), testASN)
|
||||||
|
if !errors.Is(err, whois.ErrPaused) || ripeAsks != 1 {
|
||||||
|
t.Errorf("LookupASN during the pause: error %v after %d "+
|
||||||
|
"queries to RIPE, want ErrPaused after 1", err, ripeAsks)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = client.LookupASN(t.Context(), apnicASN)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("LookupASN of an AS at APNIC during RIPE's "+
|
||||||
|
"pause: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now = start.Add(whois.PauseTime)
|
||||||
|
|
||||||
|
_, _ = client.LookupASN(t.Context(), testASN)
|
||||||
|
if ripeAsks != 2 {
|
||||||
|
t.Errorf("RIPE was asked %d times after the pause, want 2",
|
||||||
|
ripeAsks)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestLookupASNFailsWhenTheRIRGivesNoAnswer looks up an AS IANA refers to
|
// TestLookupASNFailsWhenTheRIRGivesNoAnswer looks up an AS IANA refers to
|
||||||
// RIPE when RIPE's server refuses the connection, and when it answers only
|
// RIPE when RIPE's server refuses the connection, and when it answers only
|
||||||
// with an error. Neither is a lookup that found the AS.
|
// with an error. Neither is a lookup that found the AS.
|
||||||
|
|||||||
Reference in new issue
Block a user