Skip to content
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

Add metrics reporting #37

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
module github.com/libp2p/go-libp2p-kbucket

require (
github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803
github.com/ipfs/go-ipfs-util v0.0.1
github.com/ipfs/go-log v0.0.1
github.com/libp2p/go-libp2p-core v0.0.1
github.com/libp2p/go-libp2p-peerstore v0.1.0
github.com/minio/sha256-simd v0.0.0-20190131020904-2d45a736cd16
go.opencensus.io v0.22.0
)
41 changes: 41 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/AndreasBriese/bbloom v0.0.0-20180913140656-343706a395b7/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Kubuxu/go-os-helper v0.0.1/go.mod h1:N8B+I7vPCT80IcP58r50u4+gEEcsZETFUpAzWW2ep1Y=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/btcsuite/btcd v0.0.0-20190213025234-306aecffea32 h1:qkOC5Gd33k54tobS36cXdAzJbeHaduLtnLQQwNoIi78=
github.com/btcsuite/btcd v0.0.0-20190213025234-306aecffea32/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803 h1:j3AgPKKZtZStM2nyhrDSLSYgT7YHrZKdSkq1OYeLjvM=
github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
Expand All @@ -21,9 +25,13 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98=
github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gxed/hashland/keccakpg v0.0.1 h1:wrk3uMNaMxbXiHibbPO4S0ymqJMm41WiudyFSs7UnsU=
github.com/gxed/hashland/keccakpg v0.0.1/go.mod h1:kRzw3HkwxFU1mpmPP8v1WyQzwdGfmKFJ6tItnhQ67kU=
Expand Down Expand Up @@ -99,23 +107,56 @@ github.com/whyrusleeping/go-keyspace v0.0.0-20160322163242-5b898ac5add1/go.mod h
github.com/whyrusleeping/go-logging v0.0.0-20170515211332-0457bb6b88fc h1:9lDbC6Rz4bwmou+oE6Dt4Cb2BGMur5eR/GYptkKUVHo=
github.com/whyrusleeping/go-logging v0.0.0-20170515211332-0457bb6b88fc/go.mod h1:bopw91TMyo8J3tvftk8xmU2kPmlrt4nScJQZU2hE5EM=
github.com/whyrusleeping/mafmt v1.2.8/go.mod h1:faQJFPbLSxzD9xpA02ttW/tS9vZykNvXwGvqIpk20FA=
go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190225124518-7f87c0fbb88b h1:+/WWzjwW6gidDJnMKWLKLX1gxn7irUTF1fLpQovfQ5M=
golang.org/x/crypto v0.0.0-20190225124518-7f87c0fbb88b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190227160552-c95aed5357e7 h1:C2F/nMkR/9sfUTpvR3QrjBuTdvMUC/cFajkphs1YLQo=
golang.org/x/net v0.0.0-20190227160552-c95aed5357e7/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09 h1:KaQtG+aDELoNmXYas3TVkGNYRuq8JQ1aa7LJt8EXVyo=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190219092855-153ac476189d/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd h1:r7DufRZuZbWB7j439YfAzP8RPDa9unLkpwQKUYbIMPI=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
138 changes: 138 additions & 0 deletions metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package metrics

import (
"context"
"github.com/btcsuite/btcutil/base58"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"time"
)

// Keys
var (
keyLocalId, _ = tag.NewKey("local_dht_id")
keyBucketIndex, _ = tag.NewKey("bucket_index")
)

// Constants for measure names are exported and can be used to
// fetch views from the `DefaultViews` map.
const (
MeasureBucketUtilization = "libp2p.io/dht/k-bucket/utilization"
MeasurePeerLatency = "libp2p.io/dht/k-bucket/peer_latency"
MeasurePeersAdded = "libp2p.io/dht/k-bucket/peers_added"
MeasurePeersRejectedHighLatency = "libp2p.io/dht/k-bucket/peers_rejected_high_latency"
MeasurePeersRejectedNoCapacity = "libp2p.io/dht/k-bucket/peers_rejected_capacity"
MeasurePeersRefreshed = "libp2p.io/dht/k-bucket/peers_refreshed"
MeasurePeersRemoved = "libp2p.io/dht/k-bucket/peers_removed"
)

// Measures are exported so that consumers can create their own views if the `DefaultViews`
// aren't sufficient. However, they should be updated using the functions below to avoid
// leaking OpenCensus cruft throughout the rest of the code.
var (
KBucketUtilization = stats.Int64(MeasureBucketUtilization,
"Number of entries per k-bucket.", stats.UnitDimensionless)
KBucketPeerLatency = stats.Float64(MeasurePeerLatency,
"Recorded latency measurements for all peers added to each bucket, per bucket.", stats.UnitMilliseconds)
KBucketPeersAdded = stats.Int64(MeasurePeersAdded,
"Number of peers added to each k-bucket (cumulative). Note that peers can be counted twice if added and removed.", stats.UnitDimensionless)
KBucketPeersRejectedHighLatency = stats.Int64(MeasurePeersRejectedHighLatency,
"Number of peers rejected from k-buckets due to high latency.", stats.UnitDimensionless)
KBucketPeersRejectedNoCapacity = stats.Int64(MeasurePeersRejectedNoCapacity,
"Number of peers rejected from the routing table because their k-bucket was full.", stats.UnitDimensionless)
KBucketPeersRefreshed = stats.Int64(MeasurePeersRefreshed,
"Number of peers moved to the front of a k-bucket that they were already in.", stats.UnitDimensionless)
KBucketPeersRemoved = stats.Int64(MeasurePeersRemoved,
"Number of peers removed from each k-bucket (cumulative). "+
"Peers may be counted twice if added and removed.", stats.UnitDimensionless)
)

// Default Views are exported individually and in the DefaultViews slice for
// convenient registration.
var (
ViewBucketUtilization = &view.View{
Measure: KBucketUtilization,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.LastValue(),
}
ViewPeersAdded = &view.View{
Measure: KBucketPeersAdded,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
}
ViewPeersRejectedHighLatency = &view.View{
Measure: KBucketPeersRejectedHighLatency,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
}
ViewPeersRejectedNoCapacity = &view.View{
Measure: KBucketPeersRejectedNoCapacity,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
}
ViewPeersRemoved = &view.View{
Measure: KBucketPeersRemoved,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
}
DefaultViews = []*view.View{
ViewBucketUtilization,
ViewPeersAdded,
ViewPeersRejectedHighLatency,
ViewPeersRejectedNoCapacity,
ViewPeersRemoved,
}
)

// BucketContext returns `ctx` tagged with the local DHT id `localId` and the current `bucketIndex`.
// It should be used for recording all metrics that correspond to a specific bucket.
func BucketContext(ctx context.Context, localID []byte, bucketIndex int) context.Context {
pretty := base58.Encode(localID)
ctx, _ = tag.New(ctx,
tag.Upsert(keyLocalId, pretty),
tag.Upsert(keyBucketIndex, string(bucketIndex)))
return ctx
}

// RecordBucketUtilization records the current number of entries `n` contained within
// a bucket. It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordBucketUtilization(ctx context.Context, n int) {
stats.Record(ctx, KBucketUtilization.M(int64(n)))
}

// RecordPeerAdded records that a peer was added to a bucket, also recording the
// `measuredLatency` of the peer at the time they were added.
// It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordPeerAdded(ctx context.Context, measuredLatency time.Duration) {
stats.Record(ctx,
KBucketPeersAdded.M(1),
KBucketPeerLatency.M(float64(measuredLatency/time.Millisecond)))
}

// RecordPeerRejectedHighLatency records that a peer was rejected from a bucket
// because their measured connection latency was too high.
// It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordPeerRejectedHighLatency(ctx context.Context, bucketIndex int) {
stats.Record(ctx, KBucketPeersRejectedHighLatency.M(1))
}

// RecordPeerRejectedNoCapacity records that a peer was rejected from a bucket
// because the bucket was full, and no members were eligible for eviction.
// It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordPeerRejectedNoCapacity(ctx context.Context) {
stats.Record(ctx, KBucketPeersRejectedNoCapacity.M(1))
}

// RecordPeerRefreshed records that a peer in a bucket had its "last seen" status updated,
// moving it to the head of its bucket.
// It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordPeerRefreshed(ctx context.Context) {
stats.Record(ctx, KBucketPeersRefreshed.M(1))
}

// RecordPeerRemoved records that a peer was removed from a bucket.
// It is assumed that `ctx` is tagged with the current bucket id - see BucketContext.
func RecordPeerRemoved(ctx context.Context, bucketIndex int) {
stats.Record(ctx, KBucketPeersRemoved.M(1))
}
38 changes: 34 additions & 4 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
package kbucket

import (
"context"
"errors"
"fmt"
"github.com/libp2p/go-libp2p-kbucket/metrics"
"sync"
"time"

Expand All @@ -20,7 +22,6 @@ var ErrPeerRejectedNoCapacity = errors.New("peer rejected; insufficient capacity

// RoutingTable defines the routing table.
type RoutingTable struct {

// ID of the local peer
local ID

Expand Down Expand Up @@ -57,8 +58,9 @@ func NewRoutingTable(bucketsize int, localID ID, latency time.Duration, m peerst
return rt
}

// Update adds or moves the given peer to the front of its respective bucket
func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
// UpdateCtx adds or moves the given peer to the front of its respective bucket, while recording
// metrics about bucket capacities and peer additions and removals.
func (rt *RoutingTable) UpdateCtx(ctx context.Context, p peer.ID) (evicted peer.ID, err error) {
peerID := ConvertPeerID(p)
cpl := CommonPrefixLen(peerID, rt.local)

Expand All @@ -70,22 +72,30 @@ func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
}

bucket := rt.Buckets[bucketID]
ctx = metrics.BucketContext(ctx, rt.local, bucketID)
metrics.RecordBucketUtilization(ctx, bucket.Len())

if bucket.Has(p) {
// If the peer is already in the table, move it to the front.
// This signifies that it it "more active" and the less active nodes
// Will as a result tend towards the back of the list
bucket.MoveToFront(p)
metrics.RecordPeerRefreshed(ctx)
return "", nil
}

if rt.metrics.LatencyEWMA(p) > rt.maxLatency {
peerLatency := rt.metrics.LatencyEWMA(p)

if peerLatency > rt.maxLatency {
// Connection doesnt meet requirements, skip!
metrics.RecordPeerRejectedHighLatency(ctx, bucketID)
return "", ErrPeerRejectedHighLatency
}

// We have enough space in the bucket (whether spawned or grouped).
if bucket.Len() < rt.bucketsize {
bucket.PushFront(p)
metrics.RecordPeerAdded(ctx, peerLatency)
rt.PeerAdded(p)
return "", nil
}
Expand All @@ -99,21 +109,38 @@ func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
bucketID = len(rt.Buckets) - 1
}
bucket = rt.Buckets[bucketID]
ctx = metrics.BucketContext(ctx, rt.local, bucketID)
metrics.RecordBucketUtilization(ctx, bucket.Len())

if bucket.Len() >= rt.bucketsize {
// if after all the unfolding, we're unable to find room for this peer, scrap it.
metrics.RecordPeerRejectedNoCapacity(ctx)
return "", ErrPeerRejectedNoCapacity
}
bucket.PushFront(p)
metrics.RecordPeerAdded(ctx, peerLatency)
rt.PeerAdded(p)
return "", nil
}

metrics.RecordPeerRejectedNoCapacity(ctx)
return "", ErrPeerRejectedNoCapacity
}

// Update adds or moves the given peer to the front of its respective bucket
func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
return rt.UpdateCtx(context.Background(), p)
}

// Remove deletes a peer from the routing table. This is to be used
// when we are sure a node has disconnected completely.
func (rt *RoutingTable) Remove(p peer.ID) {
rt.RemoveCtx(context.Background(), p)
}

// RemoveCtx deletes a peer from the routing table, updating metrics on removal.
// This is to be used when we are sure a node has disconnected completely.
lanzafame marked this conversation as resolved.
Show resolved Hide resolved
func (rt *RoutingTable) RemoveCtx(ctx context.Context, p peer.ID) {
peerID := ConvertPeerID(p)
cpl := CommonPrefixLen(peerID, rt.local)

Expand All @@ -127,6 +154,9 @@ func (rt *RoutingTable) Remove(p peer.ID) {

bucket := rt.Buckets[bucketID]
if bucket.Remove(p) {
ctx = metrics.BucketContext(ctx, rt.local, bucketID)
metrics.RecordPeerRemoved(ctx, bucketID)
metrics.RecordBucketUtilization(ctx, bucket.Len())
rt.PeerRemoved(p)
}
}
Expand Down