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 2 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=
163 changes: 163 additions & 0 deletions metrics/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
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 (
MeasureBucketsFull = "libp2p.io/dht/k-bucket/full_buckets"
MeasureBucketsNonEmpty = "libp2p.io/dht/k-bucket/non_empty_buckets"
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 (
KBucketsFull = stats.Int64(MeasureBucketsFull,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: If you are multi-lining a function call, put each parameter on a new line and not a combination. In this particular case, the third parameter is lost at the end of the line.

"Number of k-buckets that are at capacity (have k entries).", stats.UnitDimensionless)
KBucketsNonEmpty = stats.Int64(MeasureBucketsNonEmpty,
"Number of k-buckets with at least one entry.", stats.UnitDimensionless)
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)
)

// LocalContext returns `ctx` tagged with the local dht `id` for metrics reporting.
func LocalContext(ctx context.Context, id []byte) context.Context {
pretty := base58.Encode(id)
ctx, _ = tag.New(ctx, tag.Upsert(keyLocalId, pretty))
return ctx
}

// RecordBucketsFull records the current number of buckets `n` that are at capacity.
func RecordBucketsFull(ctx context.Context, n int) {
stats.Record(ctx, KBucketsFull.M(int64(n)))
}

// RecordBucketsNonEmpty records the current number of buckets `n` that have at least one entry.
func RecordBucketsNonEmpty(ctx context.Context, n int) {
stats.Record(ctx, KBucketsNonEmpty.M(int64(n)))
}

// recordWithBucketIndex is a helper func that applies a tag to the measurements `ms`
// indicating the index of the bucket to which the measurement applies.
func recordWithBucketIndex(ctx context.Context, bucketIndex int, ms ...stats.Measurement) {
_ = stats.RecordWithTags(ctx,
[]tag.Mutator{tag.Upsert(keyBucketIndex, string(bucketIndex))},

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tag.Upsert is a performance killer, unfortunately, so the way that this helper operates results in a lot of extra allocations. I suggest creating a helper that does the same as LocalContext but for bucket index and gets called after the bucketID is defined, just once.

ms...,
)
}

// RecordBucketUtilization records the current number of entries `n` for
// the given `bucketIndex`.
func RecordBucketUtilization(ctx context.Context, bucketIndex int, n int) {
recordWithBucketIndex(ctx, bucketIndex, KBucketUtilization.M(int64(n)))
}

// RecordPeerAdded records that a peer was added to the bucket with index `bucketIndex`.
// It also records the `measuredLatency` of the peer at the time they were added.
func RecordPeerAdded(ctx context.Context, bucketIndex int, measuredLatency time.Duration) {
recordWithBucketIndex(ctx, bucketIndex,
KBucketPeersAdded.M(1),
KBucketPeerLatency.M(float64(measuredLatency/time.Millisecond)))
}

// RecordPeerRejectedHighLatency records that a peer was rejected from the bucket with
// index `bucketIndex` because their measured connection latency was too high.
func RecordPeerRejectedHighLatency(ctx context.Context, bucketIndex int) {
recordWithBucketIndex(ctx, bucketIndex, KBucketPeersRejectedHighLatency.M(1))
}

// RecordPeerRejectedNoCapacity records that a peer was rejected from the bucket with
// index `bucketIndex` because the bucket was full, and no members were eligible for eviction.
func RecordPeerRejectedNoCapacity(ctx context.Context, bucketIndex int) {
recordWithBucketIndex(ctx, bucketIndex, KBucketPeersRejectedNoCapacity.M(1))
}

// RecordPeerRefreshed records that a peer in the bucket with index `bucketIndex`
// had its "last seen" status updated, moving it to the head of its bucket.
func RecordPeerRefreshed(ctx context.Context, bucketIndex int) {
recordWithBucketIndex(ctx, bucketIndex, KBucketPeersRefreshed.M(1))
}

// RecordPeerRemoved records that a peer was removed from the bucket with
// index `bucketIndex`.
func RecordPeerRemoved(ctx context.Context, bucketIndex int) {
recordWithBucketIndex(ctx, bucketIndex, KBucketPeersRemoved.M(1))
}

var DefaultViews = map[string]*view.View{

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initialisation of views should be separate from the construction of the default views. Also DefaultViews should be a slice so that when registered it looks like, err := view.Register(kbmetrics.DefaultsViews...).

MeasureBucketsFull: {
Measure: KBucketsFull,
TagKeys: []tag.Key{keyLocalId},
Aggregation: view.LastValue(),
},

MeasureBucketsNonEmpty: {
Measure: KBucketsNonEmpty,
TagKeys: []tag.Key{keyLocalId},
Aggregation: view.LastValue(),
},

MeasureBucketUtilization: {
Measure: KBucketUtilization,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.LastValue(),
},

MeasurePeersAdded: {
Measure: KBucketPeersAdded,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
},

MeasurePeersRejectedHighLatency: {
Measure: KBucketPeersRejectedHighLatency,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
},

MeasurePeersRejectedNoCapacity: {
Measure: KBucketPeersRejectedNoCapacity,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
},

MeasurePeersRemoved: {
Measure: KBucketPeersRemoved,
TagKeys: []tag.Key{keyLocalId, keyBucketIndex},
Aggregation: view.Count(),
},
}
46 changes: 43 additions & 3 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 Down Expand Up @@ -57,8 +59,10 @@ 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) {
// UpdateAndRecordMetrics 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) UpdateAndRecordMetrics(ctx context.Context, p peer.ID) (evicted peer.ID, err error) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recording metrics shouldn't be considered 'extra' functionality, it is just a requirement of running a production system, if the rename is because of the change to the parameters, it is a common pattern to append Ctx to the function name when the only change is to add the ctx parameter to the function signature, i.e. UpdateCtx.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I didn't like the new name and am glad there's an idiom I can use 😄

ctx = metrics.LocalContext(ctx, rt.local)
peerID := ConvertPeerID(p)
cpl := CommonPrefixLen(peerID, rt.local)

Expand All @@ -69,23 +73,44 @@ func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
bucketID = len(rt.Buckets) - 1
}

var full = 0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something as intensive as this should maybe be enabled with a flag. could just be a module scope var

var nonEmpty = 0
for i, buck := range rt.Buckets {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, we could get a snapshot of all the buckets straight away, but it is really expensive. I think a better way to approach this would be to build up the view of all buckets one bucket at a time. So whichever bucket is chosen for the Update operation is the one we record metrics for.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea - the measures for the # of full and non-empty buckets are redundant with the utilization measure anyway. I'll rewrite this to just record utilization for the buckets we actually visit in the Update method and remove the loop.

n := buck.Len()
metrics.RecordBucketUtilization(ctx, i, n)
if n == 0 {
continue
}
nonEmpty += 1
if n >= rt.bucketsize {
full += 1
}
}
metrics.RecordBucketsNonEmpty(ctx, nonEmpty)
metrics.RecordBucketsFull(ctx, full)

bucket := rt.Buckets[bucketID]
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, bucketID)
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, bucketID, peerLatency)
rt.PeerAdded(p)
return "", nil
}
Expand All @@ -101,19 +126,33 @@ func (rt *RoutingTable) Update(p peer.ID) (evicted peer.ID, err error) {
bucket = rt.Buckets[bucketID]
if bucket.Len() >= rt.bucketsize {
// if after all the unfolding, we're unable to find room for this peer, scrap it.
metrics.RecordPeerRejectedNoCapacity(ctx, bucketID)
return "", ErrPeerRejectedNoCapacity
}
bucket.PushFront(p)
metrics.RecordPeerAdded(ctx, bucketID, peerLatency)
rt.PeerAdded(p)
return "", nil
}

metrics.RecordPeerRejectedNoCapacity(ctx, bucketID)
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.UpdateAndRecordMetrics(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.RemoveAndRecordMetrics(context.Background(), p)
}

// RemoveAndRecordMetrics 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) RemoveAndRecordMetrics(ctx context.Context, p peer.ID) {
peerID := ConvertPeerID(p)
cpl := CommonPrefixLen(peerID, rt.local)

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

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