Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4eb50470c9 | ||
|
|
ad4c3d91f1 | ||
|
|
b4dee48401 | ||
|
|
616f13071f | ||
|
|
521c632087 |
No files matched your search
@@ -144,8 +144,9 @@ routewatch/
|
||||
- **Reconnection**: Exponential backoff (5s-320s) with reset after 30s of stable connection
|
||||
- **IP Lookup**: the most specific live route is found by looking up the
|
||||
address's prefix at each mask length, longest first, in the prefix index
|
||||
(at most 33 lookups for IPv4, 129 for IPv6); prefixes are stored in the
|
||||
text form Go's `net/netip` prints
|
||||
(at most 25 lookups for IPv4, 113 for IPv6); prefixes are stored in the
|
||||
text form Go's `net/netip` prints. Routes shorter than /8 for IPv4 or /16
|
||||
for IPv6, such as a default route, are not used.
|
||||
|
||||
### Database Schema
|
||||
|
||||
|
||||
@@ -43,6 +43,14 @@ const (
|
||||
ipv6Family = "IPv6"
|
||||
)
|
||||
|
||||
// The IP lookup does not use routes shorter than these mask lengths. A default
|
||||
// route or a route this short only says where a peer sends traffic it has no
|
||||
// better route for; it does not say who holds the address.
|
||||
const (
|
||||
minLookupMaskLengthV4 = 8
|
||||
minLookupMaskLengthV6 = 16
|
||||
)
|
||||
|
||||
// SQLite memory tuning. cache_size and busy_timeout go in the DSN so every
|
||||
// pooled connection gets them; the heap limits are process-wide and set once.
|
||||
const (
|
||||
@@ -1685,19 +1693,21 @@ func (d *Database) GetASPeersContext(
|
||||
}
|
||||
|
||||
// GetPrefixDetails returns detailed information about a prefix
|
||||
func (d *Database) GetPrefixDetails(prefix string) ([]LiveRoute, error) {
|
||||
func (d *Database) GetPrefixDetails(
|
||||
prefix string,
|
||||
) ([]LiveRoute, map[int]ASN, error) {
|
||||
return d.GetPrefixDetailsContext(context.Background(), prefix)
|
||||
}
|
||||
|
||||
// GetPrefixDetailsContext returns detailed information about a prefix with
|
||||
// context support
|
||||
// GetPrefixDetailsContext returns the live routes for a prefix and, keyed by
|
||||
// AS number, the handle and description of each AS that originates it.
|
||||
func (d *Database) GetPrefixDetailsContext(
|
||||
ctx context.Context, prefix string,
|
||||
) ([]LiveRoute, error) {
|
||||
) ([]LiveRoute, map[int]ASN, error) {
|
||||
// Determine if it's IPv4 or IPv6 by parsing the prefix
|
||||
_, ipnet, err := net.ParseCIDR(prefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid prefix format: %w", err)
|
||||
return nil, nil, fmt.Errorf("invalid prefix format: %w", err)
|
||||
}
|
||||
|
||||
tableName := tableLiveRoutesV4
|
||||
@@ -1719,12 +1729,14 @@ func (d *Database) GetPrefixDetailsContext(
|
||||
|
||||
rows, err := d.db.QueryContext(ctx, query, prefix)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query prefix details: %w", err)
|
||||
return nil, nil, fmt.Errorf("failed to query prefix details: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var routes []LiveRoute
|
||||
|
||||
origins := make(map[int]ASN)
|
||||
|
||||
for rows.Next() {
|
||||
var (
|
||||
route LiveRoute
|
||||
@@ -1750,18 +1762,23 @@ func (d *Database) GetPrefixDetailsContext(
|
||||
route.IPVersion = ipVersion
|
||||
route.MaskLength, _ = ipnet.Mask.Size()
|
||||
routes = append(routes, route)
|
||||
origins[route.OriginASN] = ASN{
|
||||
ASN: route.OriginASN,
|
||||
Handle: handle.String,
|
||||
Description: description.String,
|
||||
}
|
||||
}
|
||||
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read prefix details: %w", err)
|
||||
return nil, nil, fmt.Errorf("failed to read prefix details: %w", err)
|
||||
}
|
||||
|
||||
if len(routes) == 0 {
|
||||
return nil, fmt.Errorf("%w: %s", ErrNoRoute, prefix)
|
||||
return nil, nil, fmt.Errorf("%w: %s", ErrNoRoute, prefix)
|
||||
}
|
||||
|
||||
return routes, nil
|
||||
return routes, origins, nil
|
||||
}
|
||||
|
||||
// GetRandomPrefixesByLength returns a random sample of prefixes with the
|
||||
@@ -2008,11 +2025,12 @@ const ipInfoQuery = `
|
||||
// GetIPInfoContext returns comprehensive IP information with context support.
|
||||
//
|
||||
// It finds the most specific live route for the address with point lookups on
|
||||
// the prefix index: for each mask length from the longest (32 or 128) down to 0
|
||||
// it looks up the address's network prefix at that length, and the first length
|
||||
// with a live route wins. That is at most 33 or 129 indexed lookups, however
|
||||
// many routes are live. The prefix is looked up in the text form net/netip
|
||||
// prints, which is the form the prefix handler stores.
|
||||
// the prefix index: for each mask length from the longest (32 or 128) down to
|
||||
// minLookupMaskLengthV4 or minLookupMaskLengthV6 it looks up the address's
|
||||
// network prefix at that length, and the first length with a live route wins.
|
||||
// That is at most 25 or 113 indexed lookups, however many routes are live. The
|
||||
// prefix is looked up in the text form net/netip prints, which is the form the
|
||||
// prefix handler stores.
|
||||
func (d *Database) GetIPInfoContext(
|
||||
ctx context.Context, ip string,
|
||||
) (*IPInfo, error) {
|
||||
@@ -2026,8 +2044,11 @@ func (d *Database) GetIPInfoContext(
|
||||
info := &IPInfo{IP: ip, IPVersion: ipVersionV6}
|
||||
|
||||
routesTable, prefixesTable := tableLiveRoutesV6, "prefixes_v6"
|
||||
minMaskLength := minLookupMaskLengthV6
|
||||
|
||||
if addr.Is4() {
|
||||
routesTable, prefixesTable = tableLiveRoutesV4, "prefixes_v4"
|
||||
minMaskLength = minLookupMaskLengthV4
|
||||
info.IPVersion = ipVersionV4
|
||||
}
|
||||
|
||||
@@ -2048,7 +2069,7 @@ func (d *Database) GetIPInfoContext(
|
||||
|
||||
found := false
|
||||
|
||||
for bits := addr.BitLen(); bits >= 0; bits-- {
|
||||
for bits := addr.BitLen(); bits >= minMaskLength; bits-- {
|
||||
prefix := netip.PrefixFrom(addr, bits).Masked().String()
|
||||
|
||||
err := stmt.QueryRowContext(ctx, prefix).Scan(
|
||||
|
||||
@@ -126,6 +126,71 @@ func TestGetIPInfoFindsMostSpecificLiveRoute(t *testing.T) {
|
||||
lookup("2001:db8:1:2::3", "2001:db8:1::/48")
|
||||
}
|
||||
|
||||
// TestGetIPInfoIgnoresShortRoutes checks that the IP lookup does not report a
|
||||
// default route, or a route shorter than /8 for IPv4 or /16 for IPv6, as the
|
||||
// route for an address, and that a route of exactly /8 or /16, or longer, still
|
||||
// is. The prefixes are written out so that a wrong limit fails the test.
|
||||
func TestGetIPInfoIgnoresShortRoutes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cfg := &config.Config{StateDir: t.TempDir()}
|
||||
|
||||
db, err := New(cfg, logger.New())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create database: %v", err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
// announce writes one live route for prefix, originated by asn.
|
||||
announce := func(prefix string, asn int) {
|
||||
t.Helper()
|
||||
|
||||
writeOriginRoutes(t, db, map[string]int{prefix: asn})
|
||||
}
|
||||
|
||||
// lookup checks that ip resolves to the live prefix netblock from asn.
|
||||
lookup := func(ip, netblock string, asn int) {
|
||||
t.Helper()
|
||||
|
||||
info, err := db.GetIPInfo(ip)
|
||||
if err != nil {
|
||||
t.Errorf("GetIPInfo(%s): %v", ip, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if info.Netblock != netblock || info.ASN != asn {
|
||||
t.Errorf("GetIPInfo(%s) = %s AS%d, want %s AS%d",
|
||||
ip, info.Netblock, info.ASN, netblock, asn)
|
||||
}
|
||||
}
|
||||
|
||||
// Default and very short routes, and routes one bit shorter than each limit.
|
||||
announce("2000::/3", 64500)
|
||||
announce("0.0.0.0/0", 64500)
|
||||
announce("2000::/15", 64500)
|
||||
announce("192.0.0.0/7", 64500)
|
||||
|
||||
for _, ip := range []string{"2001:db8::1", "192.0.2.1"} {
|
||||
info, err := db.GetIPInfo(ip)
|
||||
if !errors.Is(err, ErrNoRoute) {
|
||||
t.Errorf("GetIPInfo(%s) with only short routes = %+v, %v; "+
|
||||
"want ErrNoRoute", ip, info, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Routes of exactly the minimum length are used.
|
||||
announce("2001::/16", 64501)
|
||||
announce("192.0.0.0/8", 64501)
|
||||
|
||||
lookup("2001:db8::1", "2001::/16", 64501)
|
||||
lookup("192.0.2.1", "192.0.0.0/8", 64501)
|
||||
|
||||
announce("2001:db8::/32", 64502)
|
||||
|
||||
lookup("2001:db8::1", "2001:db8::/32", 64502)
|
||||
}
|
||||
|
||||
// writeOriginRoutes writes one live route from testPeerIP for each prefix in
|
||||
// origins, originated by the AS it maps to.
|
||||
func writeOriginRoutes(t *testing.T, db *Database, origins map[string]int) {
|
||||
|
||||
@@ -80,8 +80,8 @@ type Store interface {
|
||||
GetASDetailsContext(ctx context.Context, asn int) (*ASN, []LiveRoute, error)
|
||||
GetASPeers(asn int) ([]ASPeer, error)
|
||||
GetASPeersContext(ctx context.Context, asn int) ([]ASPeer, error)
|
||||
GetPrefixDetails(prefix string) ([]LiveRoute, error)
|
||||
GetPrefixDetailsContext(ctx context.Context, prefix string) ([]LiveRoute, error)
|
||||
GetPrefixDetails(prefix string) ([]LiveRoute, map[int]ASN, error)
|
||||
GetPrefixDetailsContext(ctx context.Context, prefix string) ([]LiveRoute, map[int]ASN, error)
|
||||
GetRandomPrefixesByLength(maskLength, ipVersion, limit int) ([]LiveRoute, error)
|
||||
GetRandomPrefixesByLengthContext(
|
||||
ctx context.Context, maskLength, ipVersion, limit int,
|
||||
|
||||
@@ -115,7 +115,7 @@ func (rw *RouteWatch) Run(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// Start HTTP server
|
||||
err = rw.server.Start()
|
||||
err = rw.server.Start(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -263,15 +263,17 @@ func (m *mockStore) GetASDetailsContext(
|
||||
}
|
||||
|
||||
// GetPrefixDetails mock implementation
|
||||
func (m *mockStore) GetPrefixDetails(_ string) ([]database.LiveRoute, error) {
|
||||
func (m *mockStore) GetPrefixDetails(
|
||||
_ string,
|
||||
) ([]database.LiveRoute, map[int]database.ASN, error) {
|
||||
// Return empty routes for now
|
||||
return []database.LiveRoute{}, nil
|
||||
return []database.LiveRoute{}, map[int]database.ASN{}, nil
|
||||
}
|
||||
|
||||
// GetPrefixDetailsContext mock implementation with context support
|
||||
func (m *mockStore) GetPrefixDetailsContext(
|
||||
_ context.Context, prefix string,
|
||||
) ([]database.LiveRoute, error) {
|
||||
) ([]database.LiveRoute, map[int]database.ASN, error) {
|
||||
return m.GetPrefixDetails(prefix)
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ const (
|
||||
debugInterval = 60 * time.Second
|
||||
// bytesPerMB is bytes per megabyte
|
||||
bytesPerMB = 1024 * 1024
|
||||
// failureExitCode is the exit status when RouteWatch stops on an error
|
||||
failureExitCode = 1
|
||||
)
|
||||
|
||||
// logDebugStats logs goroutine count and memory usage
|
||||
@@ -91,6 +93,12 @@ func CLIEntry() {
|
||||
err := rw.Run(ctx)
|
||||
if err != nil {
|
||||
logger.Error("RouteWatch error", "error", err)
|
||||
|
||||
err = shutdowner.Shutdown(fx.ExitCode(failureExitCode))
|
||||
if err != nil {
|
||||
logger.Error("Failed to shutdown gracefully",
|
||||
"error", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
@@ -218,7 +218,7 @@ func checkPrefixRoutes(
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
routes, err := db.GetPrefixDetailsContext(ctx, prefix)
|
||||
routes, _, err := db.GetPrefixDetailsContext(ctx, prefix)
|
||||
if err != nil && !errors.Is(err, database.ErrNoRoute) {
|
||||
t.Fatalf("GetPrefixDetailsContext: %v", err)
|
||||
}
|
||||
|
||||
+28
-22
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -864,10 +865,17 @@ func (s *Server) handlePrefixDetailJSON() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// Combine prefix and length into CIDR notation
|
||||
prefix := prefixParam + "/" + lenParam
|
||||
// Look the prefix up in the text form net/netip prints, the form the
|
||||
// tables store, so that any valid way of writing it finds the route.
|
||||
parsed, err := netip.ParsePrefix(prefixParam + "/" + lenParam)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
|
||||
routes, err := s.db.GetPrefixDetailsContext(r.Context(), prefix)
|
||||
return
|
||||
}
|
||||
prefix := parsed.Masked().String()
|
||||
|
||||
routes, _, err := s.db.GetPrefixDetailsContext(r.Context(), prefix)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNoRoute) {
|
||||
s.writeJSONError(w, http.StatusNotFound, err.Error())
|
||||
@@ -992,10 +1000,17 @@ func (s *Server) handlePrefixDetail() http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// Combine prefix and length into CIDR notation
|
||||
prefix := prefixParam + "/" + lenParam
|
||||
// Look the prefix up in the text form net/netip prints, the form the
|
||||
// tables store, so that any valid way of writing it finds the route.
|
||||
parsed, err := netip.ParsePrefix(prefixParam + "/" + lenParam)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid prefix", http.StatusBadRequest)
|
||||
|
||||
routes, err := s.db.GetPrefixDetailsContext(r.Context(), prefix)
|
||||
return
|
||||
}
|
||||
prefix := parsed.Masked().String()
|
||||
|
||||
routes, originNames, err := s.db.GetPrefixDetailsContext(r.Context(), prefix)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNoRoute) {
|
||||
http.Error(w, "Prefix not found", http.StatusNotFound)
|
||||
@@ -1008,7 +1023,7 @@ func (s *Server) handlePrefixDetail() http.HandlerFunc {
|
||||
}
|
||||
|
||||
// Group by origin AS and collect unique AS info
|
||||
originMap := s.originASNs(r.Context(), routes)
|
||||
originMap := originASNs(routes, originNames)
|
||||
|
||||
// Get the first route to extract some common info
|
||||
var maskLength, ipVersion int
|
||||
@@ -1073,29 +1088,20 @@ type ASNInfo struct {
|
||||
}
|
||||
|
||||
// originASNs groups routes by origin AS, with each AS's handle and description
|
||||
// from the database and the number of routes it originates.
|
||||
func (s *Server) originASNs(
|
||||
ctx context.Context,
|
||||
// from names, as the prefix query returned them, and the number of routes it
|
||||
// originates.
|
||||
func originASNs(
|
||||
routes []database.LiveRoute,
|
||||
names map[int]database.ASN,
|
||||
) map[int]*ASNInfo {
|
||||
originMap := make(map[int]*ASNInfo)
|
||||
|
||||
for _, route := range routes {
|
||||
if _, exists := originMap[route.OriginASN]; !exists {
|
||||
// Get AS info from database
|
||||
asInfo, _, _ := s.db.GetASDetailsContext(ctx, route.OriginASN)
|
||||
handle := ""
|
||||
description := ""
|
||||
|
||||
if asInfo != nil {
|
||||
handle = asInfo.Handle
|
||||
description = asInfo.Description
|
||||
}
|
||||
|
||||
originMap[route.OriginASN] = &ASNInfo{
|
||||
ASN: route.OriginASN,
|
||||
Handle: handle,
|
||||
Description: description,
|
||||
Handle: names[route.OriginASN].Handle,
|
||||
Description: names[route.OriginASN].Description,
|
||||
PeerCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -15,6 +18,7 @@ import (
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
"git.eeqj.de/sneak/routewatch/internal/metrics"
|
||||
"git.eeqj.de/sneak/routewatch/internal/streamer"
|
||||
"git.eeqj.de/sneak/routewatch/pkg/asinfo"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
@@ -167,6 +171,124 @@ func TestStatsHandlersAnswerFromMemory(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrefixDetailHandlersParsePrefix checks that both prefix pages find a
|
||||
// stored route whatever valid text form the URL writes its prefix in, and
|
||||
// answer 400 for a prefix that does not parse. The tables store the form
|
||||
// net/netip prints. Before the fix the URL text was looked up as typed, so
|
||||
// "2001:DB8:0:0::/32" was not found although "2001:db8::/32" was stored, and
|
||||
// "foo/24" answered 500 (https://git.eeqj.de/sneak/routewatch/issues/71).
|
||||
func TestPrefixDetailHandlersParsePrefix(t *testing.T) {
|
||||
db, err := database.New(&config.Config{StateDir: t.TempDir()}, logger.New())
|
||||
if err != nil {
|
||||
t.Fatalf("database.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
ts := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
if err := db.UpsertLiveRouteBatch([]*database.LiveRoute{
|
||||
{
|
||||
ID: uuid.New(), Prefix: "192.0.2.0/24", MaskLength: 24, IPVersion: 4,
|
||||
OriginASN: 64500, PeerIP: "198.51.100.1", ASPath: []int{64500}, NextHop: "198.51.100.1",
|
||||
LastUpdated: ts,
|
||||
},
|
||||
{
|
||||
ID: uuid.New(), Prefix: "2001:db8::/32", MaskLength: 32, IPVersion: 6,
|
||||
OriginASN: 64501, PeerIP: "2001:db8::1", ASPath: []int{64501}, NextHop: "2001:db8::1",
|
||||
LastUpdated: ts,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("UpsertLiveRouteBatch: %v", err)
|
||||
}
|
||||
|
||||
s := New(db, streamer.New(logger.New(), metrics.New()), logger.New(), &config.Config{})
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"/api/v1/prefix/foo/24", http.StatusBadRequest},
|
||||
{"/prefix/foo/24", http.StatusBadRequest},
|
||||
{"/api/v1/prefix/2001:DB8:0:0::/32", http.StatusOK},
|
||||
{"/prefix/2001:DB8:0:0::/32", http.StatusOK},
|
||||
{"/api/v1/prefix/192.0.2.1/24", http.StatusOK},
|
||||
{"/prefix/192.0.2.1/24", http.StatusOK},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
rec := httptest.NewRecorder()
|
||||
s.router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, tt.path, nil))
|
||||
if rec.Code != tt.want {
|
||||
t.Errorf("%s: status %d, want %d; body %s", tt.path, rec.Code, tt.want, rec.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// failingASDetailsDB wraps a real store and fails every AS details lookup.
|
||||
type failingASDetailsDB struct {
|
||||
database.Store
|
||||
}
|
||||
|
||||
func (failingASDetailsDB) GetASDetailsContext(_ context.Context, _ int) (*database.ASN, []database.LiveRoute, error) {
|
||||
return nil, nil, errors.New("AS details lookup failed")
|
||||
}
|
||||
|
||||
// TestPrefixDetailShowsOriginNames checks that the prefix page shows each
|
||||
// origin AS's handle and description without looking up the AS's details,
|
||||
// which also read every route the AS originates. Before the fix the page did
|
||||
// that lookup once per origin, so with it failing the names were missing
|
||||
// (https://git.eeqj.de/sneak/routewatch/issues/67). The AS path column shows
|
||||
// handles too, so the test looks for the origin list's "(handle)" form.
|
||||
func TestPrefixDetailShowsOriginNames(t *testing.T) {
|
||||
db, err := database.New(&config.Config{StateDir: t.TempDir()}, logger.New())
|
||||
if err != nil {
|
||||
t.Fatalf("database.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
ts := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
origins := []int{15169, 13335}
|
||||
for _, asn := range origins {
|
||||
if _, err := db.GetOrCreateASN(asn, ts); err != nil {
|
||||
t.Fatalf("GetOrCreateASN(%d): %v", asn, err)
|
||||
}
|
||||
}
|
||||
if err := db.UpsertLiveRouteBatch([]*database.LiveRoute{
|
||||
{
|
||||
ID: uuid.New(), Prefix: "192.0.2.0/24", MaskLength: 24, IPVersion: 4,
|
||||
OriginASN: origins[0], PeerIP: "198.51.100.1", ASPath: []int{origins[0]}, NextHop: "198.51.100.1",
|
||||
LastUpdated: ts,
|
||||
},
|
||||
{
|
||||
ID: uuid.New(), Prefix: "192.0.2.0/24", MaskLength: 24, IPVersion: 4,
|
||||
OriginASN: origins[1], PeerIP: "198.51.100.2", ASPath: []int{origins[1]}, NextHop: "198.51.100.2",
|
||||
LastUpdated: ts,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("UpsertLiveRouteBatch: %v", err)
|
||||
}
|
||||
|
||||
s := New(failingASDetailsDB{db}, streamer.New(logger.New(), metrics.New()), logger.New(), &config.Config{})
|
||||
rec := httptest.NewRecorder()
|
||||
s.router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/prefix/192.0.2.0/24", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d, want %d; body %s", rec.Code, http.StatusOK, rec.Body)
|
||||
}
|
||||
|
||||
page := rec.Body.String()
|
||||
for _, asn := range origins {
|
||||
info, ok := asinfo.Get(asn)
|
||||
if !ok {
|
||||
t.Fatalf("AS%d is not in the AS info data", asn)
|
||||
}
|
||||
if want := "(" + html.EscapeString(info.Handle) + ")"; !strings.Contains(page, want) {
|
||||
t.Errorf("page does not show AS%d's handle %q", asn, want)
|
||||
}
|
||||
if want := html.EscapeString(info.Description); !strings.Contains(page, want) {
|
||||
t.Errorf("page does not show AS%d's description %q", asn, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// settledGoroutineCount lets transient goroutines finish, then reports the
|
||||
// current count.
|
||||
func settledGoroutineCount() int {
|
||||
|
||||
@@ -4,6 +4,8 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -59,9 +61,12 @@ func New(
|
||||
return s
|
||||
}
|
||||
|
||||
// Start starts the HTTP server
|
||||
func (s *Server) Start() error {
|
||||
// Start listens on the configured port and serves HTTP in the background.
|
||||
// It returns an error if it cannot listen, for example because the port is
|
||||
// already in use. ctx bounds only opening the port, not serving.
|
||||
func (s *Server) Start(ctx context.Context) error {
|
||||
const (
|
||||
network = "tcp"
|
||||
readHeaderTimeout = 40 * time.Second
|
||||
readTimeout = 60 * time.Second
|
||||
writeTimeout = 60 * time.Second
|
||||
@@ -79,11 +84,17 @@ func (s *Server) Start() error {
|
||||
|
||||
s.logger.Info("Starting HTTP server", "port", s.port, "addr", s.srv.Addr)
|
||||
|
||||
// Start in goroutine but log when actually listening
|
||||
go func() {
|
||||
s.logger.Info("HTTP server listening", "addr", s.srv.Addr)
|
||||
var listenConfig net.ListenConfig
|
||||
|
||||
err := s.srv.ListenAndServe()
|
||||
listener, err := listenConfig.Listen(ctx, network, s.srv.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("starting HTTP server: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("HTTP server listening", "addr", listener.Addr().String())
|
||||
|
||||
go func() {
|
||||
err := s.srv.Serve(listener)
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
s.logger.Error("HTTP server error", "error", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"git.eeqj.de/sneak/routewatch/internal/config"
|
||||
"git.eeqj.de/sneak/routewatch/internal/logger"
|
||||
"git.eeqj.de/sneak/routewatch/internal/metrics"
|
||||
"git.eeqj.de/sneak/routewatch/internal/server"
|
||||
"git.eeqj.de/sneak/routewatch/internal/streamer"
|
||||
)
|
||||
|
||||
// TestStartFailsWhenPortIsHeld holds a port with a listener of its own and
|
||||
// checks that Start on that port returns an error. Before the fix Start
|
||||
// listened in a goroutine, only logged the failure and returned nil, so the
|
||||
// daemon kept running without its web server.
|
||||
func TestStartFailsWhenPortIsHeld(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var listenConfig net.ListenConfig
|
||||
|
||||
held, err := listenConfig.Listen(t.Context(), "tcp", ":0")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open the test listener: %v", err)
|
||||
}
|
||||
defer func() { _ = held.Close() }()
|
||||
|
||||
addr, ok := held.Addr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
t.Fatalf("test listener address %v is not a TCP address", held.Addr())
|
||||
}
|
||||
|
||||
port := addr.Port
|
||||
log := logger.New()
|
||||
s := server.New(nil, streamer.New(log, metrics.New()), log,
|
||||
&config.Config{Port: port})
|
||||
defer func() { _ = s.Stop(context.Background()) }()
|
||||
|
||||
err = s.Start(t.Context())
|
||||
if err == nil {
|
||||
t.Fatalf("Start returned nil while port %d was held by another listener",
|
||||
port)
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,7 @@
|
||||
<div class="origin-item">
|
||||
<a href="/as/{{.ASN}}" class="as-link">AS{{.ASN}}</a>
|
||||
{{if .Handle}} ({{.Handle}}){{end}}
|
||||
{{if .Description}} {{.Description}}{{end}}
|
||||
<span style="color: #7f8c8d; margin-left: 10px;">{{.PeerCount}} peer{{if ne .PeerCount 1}}s{{end}}</span>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
Reference in new issue
Block a user