aboutsummaryrefslogtreecommitdiff
path: root/device/stats.go
blob: 6ccc5013fc26bd3cc7e7f5791c51f85126f9e1dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
 */

package device

import (
	"sync/atomic"
	"time"
)

// PeerStats are connection statistics for a given Peer.
type PeerStats struct {
	RxBytes                uint64
	TxBytes                uint64
	LastHandshakeInitiated time.Time
}

// PeerStats returns statistics for the peer with public key pk,
// and reports whether the peer lookup succeeded.
func (device *Device) PeerStats(pk NoisePublicKey) (stats PeerStats, ok bool) {
	device.peers.RLock()
	peer := device.peers.keyMap[pk]
	device.peers.RUnlock()

	if peer == nil {
		return PeerStats{}, false
	}

	peer.RLock()
	defer peer.RUnlock()
	stats = PeerStats{
		RxBytes:                atomic.LoadUint64(&peer.stats.rxBytes),
		TxBytes:                atomic.LoadUint64(&peer.stats.txBytes),
		LastHandshakeInitiated: time.Unix(0, atomic.LoadInt64(&peer.stats.lastHandshakeNano)),
	}
	return stats, true
}