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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package api
import (
"context"
"encoding/json"
"log"
"net"
"sinanmohd.com/redq/db"
"sinanmohd.com/redq/usage"
)
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
}
func Close(a *Api) {
a.sock.Close()
}
func New() (*Api, error) {
var err error
var a Api
a.sock, err = net.Listen("unix", sockPath)
if err != nil {
log.Printf("listening on unix socket: %s", err)
return nil, err
}
return &a, nil
}
func (a *Api) Run(u *usage.Usage, queries *db.Queries, ctxDb context.Context) {
for {
conn, err := a.sock.Accept()
if err != nil {
log.Printf("accepting connection: %s", err)
continue
}
go handleConn(conn, u, queries, ctxDb)
}
}
func handleConn(conn net.Conn, u *usage.Usage, queries *db.Queries, ctxDb context.Context) {
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)
case "usage":
handleUsage(conn, u, queries, ctxDb)
default:
log.Printf("invalid request type: %s", req.Type)
}
}
|