Skip to content

Commit

Permalink
chore: Add memory, CPU, and disk usage endpoints to API
Browse files Browse the repository at this point in the history
  • Loading branch information
andrasbacsai committed May 7, 2024
1 parent 16777f9 commit 3bb95f4
Show file tree
Hide file tree
Showing 7 changed files with 244 additions and 7 deletions.
38 changes: 32 additions & 6 deletions cmd/sentinel/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,49 @@ import (
"github.com/docker/docker/client"
)

type Container struct {
ID string `json:"id"`
Image string `json:"image"`
Name string `json:"name"`
State string `json:"state"`
HealthStatus string `json:"health_status"`
}

func getAllContainers() (string, error) {
ctx := context.Background()
apiClient, err := client.NewClientWithOpts()
if err != nil {
panic(err)
return "", err
}
defer apiClient.Close()

containers, err := apiClient.ContainerList(ctx, container.ListOptions{All: true})
if err != nil {
panic(err)
return "", err
}

jsonData, err := json.Marshal(containers)
var containersData []Container
for _, container := range containers {
inspectData, err := apiClient.ContainerInspect(ctx, container.ID)
if err != nil {
log.Fatalf("Error inspecting container %s: %s", container.ID, err)
return "", err
}
healthStatus := "unhealthy"
if inspectData.State.Health != nil {
healthStatus = inspectData.State.Health.Status
}
containersData = append(containersData, Container{
ID: container.ID,
Image: container.Image,
Name: container.Names[0][1:],
State: container.State,
HealthStatus: healthStatus,
})
}
jsonData, err := json.MarshalIndent(containersData, "", " ")
if err != nil {
log.Fatalf("Error marshalling containers to JSON: %s", err)
return "", err
}

return string(jsonData), nil

}
59 changes: 59 additions & 0 deletions cmd/sentinel/cpu.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package main

import (
"encoding/json"
"fmt"

"github.com/shirou/gopsutil/cpu"
)

type CpuUsage struct {
Cpu string `json:"cpu"`
Usage float64 `json:"usage"`
Idle float64 `json:"idle"`
System float64 `json:"system"`
User float64 `json:"user"`
Percent string `json:"percent"`
}

func getCpuUsage() (string, error) {
times, err := cpu.Times(true)
if err != nil {
fmt.Println("Failed to get CPU times:", err)
return "", err
}
percentage, err := cpu.Percent(0, true)
if err != nil {
fmt.Println("Failed to get CPU percentage:", err)
return "", err
}

usages := make([]CpuUsage, len(times))
for i, time := range times {
usages[i] = CpuUsage{
Cpu: fmt.Sprintf("%d", i),
Usage: time.Total(),
Idle: time.Idle,
System: time.System,
User: time.User,
Percent: fmt.Sprintf("%.2f%%", percentage[i]),
}
}
overallPercentage, err := cpu.Percent(0, false)
if err != nil {
fmt.Println("Failed to get overall CPU percentage:", err)
return "", err
}
usages = append(usages, CpuUsage{
Cpu: "Overall",
Percent: fmt.Sprintf("%.2f%%", overallPercentage[0]),
})

jsonData, err := json.MarshalIndent(usages, "", " ")
if err != nil {
return "", err
}

return string(jsonData), nil

}
55 changes: 55 additions & 0 deletions cmd/sentinel/disk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package main

import (
"encoding/json"
"fmt"

"github.com/shirou/gopsutil/disk"
)

type DiskUsage struct {
Disk string `json:"disk"`
MountPoint string `json:"mount_point"`
Total uint64 `json:"total"`
Free uint64 `json:"free"`
Used uint64 `json:"used"`
Usage float64 `json:"usage"`
}

func getDiskUsage() (string, error) {
partitions, err := disk.Partitions(true)
if err != nil {
fmt.Println("Failed to get disk partitions:", err)
return "", err
}
var usages []DiskUsage
for _, partition := range partitions {
if partition.Mountpoint == "" {
continue
}
if partition.Fstype != "ext4" && partition.Fstype != "xfs" && partition.Fstype != "btrfs" && partition.Fstype != "zfs" && partition.Fstype != "ext3" && partition.Fstype != "ext2" && partition.Fstype != "ntfs" && partition.Fstype != "fat32" && partition.Fstype != "exfat" {
continue
}

usage, err := disk.Usage(partition.Mountpoint)
if err != nil {
fmt.Printf("Failed to get usage for partition %s: %s\n", partition.Mountpoint, err)
continue
}
usages = append(usages, DiskUsage{
Disk: partition.Device,
MountPoint: partition.Mountpoint,
Total: usage.Total,
Free: usage.Free,
Used: usage.Used,
Usage: usage.UsedPercent,
})

}
jsonData, err := json.MarshalIndent(usages, "", " ")
if err != nil {
return "", err
}

return string(jsonData), nil
}
43 changes: 42 additions & 1 deletion cmd/sentinel/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"encoding/json"

"github.com/gin-gonic/gin"
)

Expand All @@ -22,7 +24,46 @@ func main() {
}

c.JSON(200, gin.H{
"containers": containers,
"containers": json.RawMessage(containers),
})
})
r.GET("/api/cpu", func(c *gin.Context) {
usage, err := getCpuUsage()
if err != nil {
c.JSON(500, gin.H{
"error": err.Error(),
})
return
}

c.JSON(200, gin.H{
"cpu_usage": json.RawMessage(usage),
})
})
r.GET("/api/memory", func(c *gin.Context) {
usage, err := getMemUsage()
if err != nil {
c.JSON(500, gin.H{
"error": err.Error(),
})
return
}

c.JSON(200, gin.H{
"mem_usage": json.RawMessage(usage),
})
})
r.GET("/api/disk", func(c *gin.Context) {
usage, err := getDiskUsage()
if err != nil {
c.JSON(500, gin.H{
"error": err.Error(),
})
return
}

c.JSON(200, gin.H{
"disk_usage": json.RawMessage(usage),
})
})
r.Run("0.0.0.0:8888")
Expand Down
39 changes: 39 additions & 0 deletions cmd/sentinel/mem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"encoding/json"
"fmt"

"github.com/shirou/gopsutil/mem"
)

type MemUsage struct {
Total uint64 `json:"total"`
Available uint64 `json:"available"`
Used uint64 `json:"used"`
UsedPercent float64 `json:"usedPercent"`
Free uint64 `json:"free"`
}

func getMemUsage() (string, error) {
memory, err := mem.VirtualMemory()
if err != nil {
fmt.Println("Failed to get memory usage:", err)
return "", err
}

usages := MemUsage{
Total: memory.Total,
Available: memory.Available,
Used: memory.Used,
UsedPercent: memory.UsedPercent,
Free: memory.Free,
}
jsonData, err := json.MarshalIndent(usages, "", " ")
if err != nil {
return "", err
}

return string(jsonData), nil

}
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
github.com/go-co-op/gocron/v2 v2.5.0 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
Expand All @@ -38,8 +39,12 @@ require (
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/shirou/gopsutil v3.21.11+incompatible // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.8.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.51.0 // indirect
go.opentelemetry.io/otel v1.26.0 // indirect
go.opentelemetry.io/otel/metric v1.26.0 // indirect
Expand Down
12 changes: 12 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
Expand Down Expand Up @@ -80,6 +83,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand All @@ -94,12 +99,18 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY=
github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.51.0 h1:Xs2Ncz0gNihqu9iosIZ5SkBbWo5T8JhhLJFMQL1qmLI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.51.0/go.mod h1:vy+2G/6NvVMpwGX/NyLqcC41fxepnuKHk16E6IZUcJc=
go.opentelemetry.io/otel v1.26.0 h1:LQwgL5s/1W7YiiRwxf03QGnWLb2HW4pLiAhaA5cZXBs=
Expand Down Expand Up @@ -133,6 +144,7 @@ golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down

0 comments on commit 3bb95f4

Please sign in to comment.