Commit 136d9f2c authored by acud's avatar acud Committed by GitHub

fix: allow dirty metrics shutdown (#2428)

parent 5912f5bd
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
package metrics package metrics
import ( import (
"context"
"fmt" "fmt"
"sync" "sync"
"time" "time"
...@@ -341,15 +342,19 @@ func (c *Collector) Flush(addresses ...swarm.Address) error { ...@@ -341,15 +342,19 @@ func (c *Collector) Flush(addresses ...swarm.Address) error {
return mErr return mErr
} }
// Finalize logs out all ongoing peer sessions // Finalize tries to logs out all ongoing peer sessions.
// and flushes all in-memory metrics counters. func (c *Collector) Finalize(ctx context.Context, t time.Time) error {
func (c *Collector) Finalize(t time.Time) error {
var ( var (
mErr error mErr error
batch = new(leveldb.Batch) batch = new(leveldb.Batch)
) )
c.counters.Range(func(_, val interface{}) bool { c.counters.Range(func(_, val interface{}) bool {
select {
case <-ctx.Done():
return false
default:
}
cs := val.(*Counters) cs := val.(*Counters)
PeerLogOut(t)(cs) PeerLogOut(t)(cs)
if err := cs.flush(c.db, batch); err != nil { if err := cs.flush(c.db, batch); err != nil {
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
package metrics_test package metrics_test
import ( import (
"context"
"testing" "testing"
"time" "time"
...@@ -125,7 +126,7 @@ func TestPeerMetricsCollector(t *testing.T) { ...@@ -125,7 +126,7 @@ func TestPeerMetricsCollector(t *testing.T) {
// Finalize. // Finalize.
mc.Record(addr, metrics.PeerLogIn(t1, metrics.PeerConnectionDirectionInbound)) mc.Record(addr, metrics.PeerLogIn(t1, metrics.PeerConnectionDirectionInbound))
if err := mc.Finalize(t3); err != nil { if err := mc.Finalize(context.Background(), t3); err != nil {
t.Fatalf("Finalize(%s): unexpected error: %v", t3, err) t.Fatalf("Finalize(%s): unexpected error: %v", t3, err)
} }
if have, want := len(mc.Snapshot(t2, addr)), 0; have != want { if have, want := len(mc.Snapshot(t2, addr)), 0; have != want {
......
...@@ -1336,9 +1336,11 @@ func (k *Kad) Close() error { ...@@ -1336,9 +1336,11 @@ func (k *Kad) Close() error {
case <-time.After(5 * time.Second): case <-time.After(5 * time.Second):
k.logger.Warning("kademlia manage loop did not shut down properly") k.logger.Warning("kademlia manage loop did not shut down properly")
} }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
k.logger.Info("kademlia persisting peer metrics") k.logger.Info("kademlia persisting peer metrics")
if err := k.collector.Finalize(time.Now()); err != nil { if err := k.collector.Finalize(ctx, time.Now()); err != nil {
k.logger.Debugf("kademlia: unable to finalize open sessions: %v", err) k.logger.Debugf("kademlia: unable to finalize open sessions: %v", err)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment