summaryrefslogtreecommitdiff
path: root/api/bandwidth.go
blob: d42c8466abb344257ee86905d8f4ec969fe44e6e (plain) (blame)
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
40
41
42
43
44
45
46
47
48
49
50
package api

import (
	"encoding/json"
	"fmt"
	"log"
	"net"

	"github.com/cilium/cilium/pkg/mac"
	"github.com/dustin/go-humanize"
	"sinanmohd.com/redq/bpf/usage"
)

type BandwidthStat struct {
	Ingress string `json:"ingress"`
	Egress  string `json:"egress"`
}

type BandwidthResp map[string]BandwidthStat

func handleBandwidth(conn net.Conn, u *usage.Usage) {
	resp := make(BandwidthResp)
	var ingressTotal, egressTotal uint64

	u.Mutex.RLock()
	for key, value := range u.Data {
		ingressTotal += value.BandwidthIngress
		egressTotal += value.BandwidthEgress

		m := mac.Uint64MAC(key)
		resp[m.String()] = BandwidthStat{
			Ingress: fmt.Sprintf("%s/s", humanize.Bytes(value.BandwidthIngress)),
			Egress:  fmt.Sprintf("%s/s", humanize.Bytes(value.BandwidthEgress)),
		}
	}
	u.Mutex.RUnlock()

	resp["total"] = BandwidthStat{
		Ingress: fmt.Sprintf("%s/s", humanize.Bytes(ingressTotal)),
		Egress:  fmt.Sprintf("%s/s", humanize.Bytes(egressTotal)),
	}

	buf, err := json.Marshal(resp)
	if err != nil {
		log.Printf("marshaling json: %s", err)
		return
	}

	conn.Write(buf)
}