Compare commits

...

11 Commits
v0.0.1 ... main

Author SHA1 Message Date
304d22ffba updated dependencies 2025-02-13 17:58:03 +01:00
ed1a1d67fc updated dependencies 2025-02-12 13:27:39 +01:00
8687a608f6 updated dependencies 2025-02-04 22:07:45 +01:00
b8d946cd31 panic on any http error 2025-02-02 22:35:06 +01:00
51842a0656 updated dependencies 2025-02-02 20:08:39 +01:00
37072c247f updated dependencies 2025-02-02 20:05:12 +01:00
a82184ee33 refactor 2025-02-02 19:47:56 +01:00
8bf2e7b687 remove debug logs and panic if auto refresh failed 2025-02-02 10:59:05 +01:00
1fd0ecc167 use AutoRefresh to refresh accessToken 2025-02-02 10:56:30 +01:00
a3c8c3ad59 added logging 2025-02-02 02:35:05 +01:00
64de05523e show pre-formatted values 2025-02-01 21:15:53 +01:00
5 changed files with 92 additions and 68 deletions

View File

@ -14,10 +14,10 @@ func CalculateClientTraffic(site *omadamodel.Site, client *omadamodel.Client, du
ClientMac: client.MacAddress,
}
trafficTotal := TrafficRate{
Received: uint64(client.TrafficDownBytes),
Transferred: uint64(client.TrafficUpBytes),
}
trafficTotal := MakeTrafficRate(
uint64(client.TrafficDownBytes),
uint64(client.TrafficUpBytes),
)
defer func() {
TrafficByClient[uniqueID] = trafficTotal
@ -26,14 +26,14 @@ func CalculateClientTraffic(site *omadamodel.Site, client *omadamodel.Client, du
lastTotal, ok := TrafficByClient[uniqueID]
if !ok {
return TrafficRate{}
return MakeTrafficRate(0, 0)
}
trafficInDur := trafficTotal.Sub(lastTotal)
seconds := duration.Seconds()
return TrafficRate{
Received: uint64(float64(trafficInDur.Received) / seconds),
Transferred: uint64(float64(trafficInDur.Transferred) / seconds),
}
return MakeTrafficRate(
uint64(float64(trafficInDur.Received)/seconds),
uint64(float64(trafficInDur.Transferred)/seconds),
)
}

8
go.mod
View File

@ -3,11 +3,11 @@ module git.tordarus.net/tordarus/omada-bandwidth
go 1.23.5
require (
git.tordarus.net/tordarus/channel v0.1.18
git.tordarus.net/tordarus/channel v0.1.19
git.tordarus.net/tordarus/envvars v0.0.0-20250114175450-d73e12b838a5
git.tordarus.net/tordarus/gmath v0.0.7
git.tordarus.net/tordarus/omada-api v0.0.1
git.tordarus.net/tordarus/slices v0.0.13
git.tordarus.net/tordarus/omada-api v0.0.10
git.tordarus.net/tordarus/slices v0.0.14
)
require git.tordarus.net/tordarus/ezhttp v0.0.3 // indirect
require git.tordarus.net/tordarus/ezhttp v0.0.9 // indirect

16
go.sum
View File

@ -1,12 +1,12 @@
git.tordarus.net/tordarus/channel v0.1.18 h1:/9BDbkyXbVpFB+dQbToniX6g/ApBnzjslYt4NiycMQo=
git.tordarus.net/tordarus/channel v0.1.18/go.mod h1:8/dWFTdGO7g4AeSZ7cF6GerkGbe9c4dBVMVDBxOd9m4=
git.tordarus.net/tordarus/channel v0.1.19 h1:d9xnSwFyvBh4B1/82mt0A7Gpm2nIZJTc+9ceJMIOu5Q=
git.tordarus.net/tordarus/channel v0.1.19/go.mod h1:8/dWFTdGO7g4AeSZ7cF6GerkGbe9c4dBVMVDBxOd9m4=
git.tordarus.net/tordarus/envvars v0.0.0-20250114175450-d73e12b838a5 h1:rKNDX/YGunqg8TEU6q1rgS2BcDKVmUW2cg61JOE/wws=
git.tordarus.net/tordarus/envvars v0.0.0-20250114175450-d73e12b838a5/go.mod h1:/qVGwrEmqtIrZyuuoIQl4vquSkPWUNJmlGNedDrdYfg=
git.tordarus.net/tordarus/ezhttp v0.0.3 h1:K6IlLmqkAFUF68HJsOTKcP3ejco7qfm+MuEagohoouo=
git.tordarus.net/tordarus/ezhttp v0.0.3/go.mod h1:Zq9o0Hibny61GqSCwJHa0PfGjVoUFv/zt2PjiQHXvmY=
git.tordarus.net/tordarus/ezhttp v0.0.9 h1:YwdQ4YcJwvpMw5CX5NcCEM23XQL+WCz5nWuc2dzX/84=
git.tordarus.net/tordarus/ezhttp v0.0.9/go.mod h1:Zq9o0Hibny61GqSCwJHa0PfGjVoUFv/zt2PjiQHXvmY=
git.tordarus.net/tordarus/gmath v0.0.7 h1:tR48idt9AUL0r556ww3ZxByTKJEr6NWCTlhl2ihzYxQ=
git.tordarus.net/tordarus/gmath v0.0.7/go.mod h1:mO7aPlvNrGVE9UFXEuuACjZgMDsM63l3OcQy6xSQnoE=
git.tordarus.net/tordarus/omada-api v0.0.1 h1:w4WozETL00JygidOXGkGs9UxUQhUNlNnlfqWiYYriHo=
git.tordarus.net/tordarus/omada-api v0.0.1/go.mod h1:Ufp8hdXMyrXK7JFHq4WL1WSIlr9L6rhOBfQnqWNpXyM=
git.tordarus.net/tordarus/slices v0.0.13 h1:S/6PtIxAtERwlyQvZAZZaq6RVo2kLrAsrA+19ThRRvY=
git.tordarus.net/tordarus/slices v0.0.13/go.mod h1:RgE7A1aSAezIvPUgcbUuMHu0q4xGKoRevT+DC0eJmwI=
git.tordarus.net/tordarus/omada-api v0.0.10 h1:SUxpG6HTE2meEyaEXorympNPqOQxRviBCKoOQ9fKlgY=
git.tordarus.net/tordarus/omada-api v0.0.10/go.mod h1:+VjFQyRiDp8fKbRB6E3zfkEPm00ffnidQ1+mfVC2KUI=
git.tordarus.net/tordarus/slices v0.0.14 h1:Jy1VRMs777WewJ7mxTgjyQIMm/Zr+co18/XoQ01YZ3A=
git.tordarus.net/tordarus/slices v0.0.14/go.mod h1:RgE7A1aSAezIvPUgcbUuMHu0q4xGKoRevT+DC0eJmwI=

70
main.go
View File

@ -9,7 +9,7 @@ import (
"git.tordarus.net/tordarus/channel"
"git.tordarus.net/tordarus/envvars"
"git.tordarus.net/tordarus/gmath"
omadaapi "git.tordarus.net/tordarus/omada-api"
omada "git.tordarus.net/tordarus/omada-api"
omadamodel "git.tordarus.net/tordarus/omada-api/model"
"git.tordarus.net/tordarus/slices"
)
@ -17,13 +17,14 @@ import (
var ( // flags
FlagSiteNames = envvars.StringSlice("SITES", ",", []string{})
FlagOmadaURL = envvars.String("OMADA_URL", "http://localhost:8088")
FlagOmadaID = envvars.String("OMADA_ID", "")
FlagOmadaClientID = envvars.String("OMADA_CLIENT_ID", "")
FlagOmadaClientSecret = envvars.String("OMADA_CLIENT_SECRET", "")
FlagOmadaUsername = envvars.String("OMADA_USERNAME", "")
FlagOmadaPassword = envvars.String("OMADA_PASSWORD", "")
FlagRefreshInterval = envvars.Duration("REFRESH_INTERVAL", 30*time.Second)
FlagOmadaURL = envvars.String("OMADA_URL", "http://localhost:8088")
FlagOmadaID = envvars.String("OMADA_ID", "")
FlagOmadaClientID = envvars.String("OMADA_CLIENT_ID", "")
FlagOmadaClientSecret = envvars.String("OMADA_CLIENT_SECRET", "")
FlagOmadaUsername = envvars.String("OMADA_USERNAME", "")
FlagOmadaPassword = envvars.String("OMADA_PASSWORD", "")
FlagRefreshInterval = envvars.Duration("REFRESH_INTERVAL", 30*time.Second)
FlagRefreshBeforeExpiration = envvars.Duration("REFRESH_BEFORE", time.Minute)
FlagHttpInterface = envvars.String("HTTP_INTERFACE", "")
FlagHttpPort = envvars.Uint16("HTTP_PORT", 8080)
@ -36,7 +37,7 @@ var CurrentTraffic = &TrafficStats{}
func main() {
FlagRefreshInterval = gmath.Max(FlagRefreshInterval, MinRefreshInterval)
api, err := omadaapi.NewApi(omadaapi.ApiConfig{
api, err := omada.NewApi(omada.ApiConfig{
BasePath: FlagOmadaURL,
OmadaID: FlagOmadaID,
ClientID: FlagOmadaClientID,
@ -49,38 +50,37 @@ func main() {
panic(err)
}
go func() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(CurrentTraffic); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
})
go StartHttpServer()
http.ListenAndServe(fmt.Sprintf("%s:%d", FlagHttpInterface, FlagHttpPort), nil)
}()
sites := slices.Filter(channel.ToSlice(api.GetSites()), FilterSitesByName(FlagSiteNames...))
sites := slices.Ref(slices.Filter(
channel.ToSlice(channel.Map(api.GetSites(), channel.Result[omadamodel.Site].GetUnsafe)),
FilterSitesByName(FlagSiteNames...),
))
ticker := time.NewTicker(FlagRefreshInterval)
CalculateSiteTraffic(api, sites, 0)
lastTick := time.Now()
CalculateSiteTraffic(api, sites, 0)
for now := range ticker.C {
CurrentTraffic = CalculateSiteTraffic(api, sites, now.Sub(lastTick))
lastTick = now
}
}
func CalculateSiteTraffic(api *omadaapi.Api, sites []*omadamodel.Site, duration time.Duration) *TrafficStats {
func CalculateSiteTraffic(api *omada.Api, sites []*omadamodel.Site, duration time.Duration) *TrafficStats {
siteTraffics := map[string]*SiteTraffic{}
for _, site := range sites {
trafficByClient := map[string]TrafficRate{}
clients := channel.ToSlice(api.GetClients(site.ID))
for _, client := range clients {
traffic := CalculateClientTraffic(site, client, duration)
clientRequests := channel.ToSlice(api.GetClients(site.ID))
for _, clientReq := range clientRequests {
client, err := clientReq.Get()
if err != nil {
panic(err)
}
traffic := CalculateClientTraffic(site, &client, duration)
trafficByClient[client.Name] = traffic
}
@ -90,15 +90,29 @@ func CalculateSiteTraffic(api *omadaapi.Api, sites []*omadamodel.Site, duration
return NewTrafficStats(siteTraffics)
}
func FilterSitesByName(allowedSiteNames ...string) func(site *omadamodel.Site) bool {
func FilterSitesByName(allowedSiteNames ...string) func(site omadamodel.Site) bool {
if len(allowedSiteNames) == 0 {
return func(site *omadamodel.Site) bool { return true }
return func(site omadamodel.Site) bool { return true }
}
siteNames := slices.ToStructMap(allowedSiteNames)
return func(site *omadamodel.Site) bool {
return func(site omadamodel.Site) bool {
_, ok := siteNames[site.Name]
return ok
}
}
func StartHttpServer() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(CurrentTraffic); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
})
connString := fmt.Sprintf("%s:%d", FlagHttpInterface, FlagHttpPort)
if err := http.ListenAndServe(connString, nil); err != nil {
panic(err)
}
}

View File

@ -16,20 +16,32 @@ type ClientUniqueID struct {
type TrafficRate struct {
Received uint64 `json:"received"` // bytes per second
Transferred uint64 `json:"transferred"` // bytes per second
ReceivedFormatted string `json:"received_fmt"`
TransferredFormatted string `json:"transferred_fmt"`
}
func MakeTrafficRate(received, transferred uint64) TrafficRate {
return TrafficRate{
Received: received,
Transferred: transferred,
ReceivedFormatted: FormatBytesPerSecond(received),
TransferredFormatted: FormatBytesPerSecond(transferred),
}
}
func (tr TrafficRate) Add(o TrafficRate) TrafficRate {
return TrafficRate{
Received: tr.Received + o.Received,
Transferred: tr.Transferred + o.Transferred,
}
return MakeTrafficRate(
tr.Received+o.Received,
tr.Transferred+o.Transferred,
)
}
func (tr TrafficRate) Sub(o TrafficRate) TrafficRate {
return TrafficRate{
Received: tr.Received - o.Received,
Transferred: tr.Transferred - o.Transferred,
}
return MakeTrafficRate(
tr.Received-o.Received,
tr.Transferred-o.Transferred,
)
}
type SiteTraffic struct {
@ -38,7 +50,7 @@ type SiteTraffic struct {
}
func NewSiteTraffic(clients map[string]TrafficRate) *SiteTraffic {
total := TrafficRate{}
total := MakeTrafficRate(0, 0)
for _, rate := range clients {
total = total.Add(rate)
}
@ -55,7 +67,7 @@ type TrafficStats struct {
}
func NewTrafficStats(sites map[string]*SiteTraffic) *TrafficStats {
total := TrafficRate{}
total := MakeTrafficRate(0, 0)
for _, siteTraffic := range sites {
total = total.Add(siteTraffic.Total)
}
@ -67,7 +79,7 @@ func NewTrafficStats(sites map[string]*SiteTraffic) *TrafficStats {
}
func (tr TrafficRate) String() string {
return fmt.Sprintf("Rx: %s | Tx: %s", FormatBytes(tr.Received), FormatBytes(tr.Transferred))
return fmt.Sprintf("Rx: %s | Tx: %s", FormatBytesPerSecond(tr.Received), FormatBytesPerSecond(tr.Transferred))
}
func (stats TrafficStats) String() string {
@ -75,18 +87,16 @@ func (stats TrafficStats) String() string {
return string(data)
}
func FormatBytes[T gmath.Integer](bytes T) string {
func FormatBytesPerSecond[T gmath.Integer](bytes T) string {
value := float64(bytes)
if value >= 1000000000000 {
return fmt.Sprintf("%.02fT", value/1000000000000)
} else if value >= 1000000000 {
return fmt.Sprintf("%.02fG", value/1000000000)
if value >= 1000000000 {
return fmt.Sprintf("%.1f GB/s", value/1000000000)
} else if value >= 1000000 {
return fmt.Sprintf("%.02fM", value/1000000)
return fmt.Sprintf("%.1f MB/s", value/1000000)
} else if value >= 1000 {
return fmt.Sprintf("%.02fK", value/1000)
return fmt.Sprintf("%.0f kB/s", value/1000)
} else {
return fmt.Sprintf("%.02fB", value)
return fmt.Sprintf("%.0f B/s", value)
}
}