summaryrefslogtreecommitdiff
path: root/api
diff options
context:
space:
mode:
authorsinanmohd <sinan@sinanmohd.com>2024-07-07 07:37:57 +0530
committersinanmohd <sinan@sinanmohd.com>2024-07-07 07:44:48 +0530
commita1692f732078adad272256639f7a3ff14c9e643a (patch)
tree8e3507ebd905e6fec65ac63bb6260b21489c2278 /api
parent22ae2f9b78dfdd2f59340d272ef598deb56cc245 (diff)
api/bandwidth: init
Diffstat (limited to 'api')
-rw-r--r--api/bandwidth.go41
-rw-r--r--api/main.go37
2 files changed, 75 insertions, 3 deletions
diff --git a/api/bandwidth.go b/api/bandwidth.go
new file mode 100644
index 0000000..5f23221
--- /dev/null
+++ b/api/bandwidth.go
@@ -0,0 +1,41 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "net"
+
+ "github.com/cilium/cilium/pkg/mac"
+ "github.com/dustin/go-humanize"
+ "sinanmohd.com/redq/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)
+
+ u.Mutex.RLock()
+ for key, value := range u.Data {
+ 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()
+
+ buf, err := json.Marshal(resp)
+ if err != nil {
+ log.Printf("marshaling json: %s", err)
+ return
+ }
+
+ conn.Write(buf)
+}
diff --git a/api/main.go b/api/main.go
index 69cf981..7081d3c 100644
--- a/api/main.go
+++ b/api/main.go
@@ -1,13 +1,23 @@
package api
import (
+ "encoding/json"
"log"
"net"
"sinanmohd.com/redq/usage"
)
-const sockPath = "/tmp/redq_ebpf.sock"
+const (
+ sockPath = "/tmp/redq_ebpf.sock"
+ bufSize = 4096
+)
+
+type ApiReq struct {
+ Type string `json:"type"`
+ Action string `json:"action"`
+ Arg string `json:"arg"`
+}
type Api struct {
sock net.Listener
@@ -38,10 +48,31 @@ func (a *Api) Run(u *usage.Usage) {
continue
}
- go handleConn(conn)
+ go handleConn(conn, u)
}
}
-func handleConn(conn net.Conn) {
+func handleConn(conn net.Conn, u *usage.Usage) {
defer conn.Close()
+ var req ApiReq
+ buf := make([]byte, bufSize)
+
+ count, err := conn.Read(buf)
+ if err != nil {
+ log.Printf("reading to buffer: %s", err)
+ return
+ }
+
+ err = json.Unmarshal(buf[:count], &req)
+ if err != nil {
+ log.Printf("unmarshaling json: %s", err)
+ return
+ }
+
+ switch req.Type {
+ case "bandwidth":
+ handleBandwidth(conn, u)
+ default:
+ log.Printf("invalid request type: %s", req.Type)
+ }
}