109 lines
2.2 KiB
Go
109 lines
2.2 KiB
Go
package controllers
|
|
|
|
import (
|
|
"api/database"
|
|
"api/models"
|
|
|
|
"github.com/shirou/gopsutil/v3/cpu"
|
|
"github.com/shirou/gopsutil/v3/disk"
|
|
"github.com/shirou/gopsutil/v3/host"
|
|
"github.com/shirou/gopsutil/v3/mem"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
// AddServer - Adds a server to the database
|
|
func AddServer(c *fiber.Ctx) error {
|
|
|
|
var data map[string]string
|
|
|
|
if err := c.BodyParser(&data); err != nil {
|
|
return fiber.ErrBadRequest
|
|
}
|
|
|
|
if data["name"] == "" || data["ip"] == "" {
|
|
return fiber.ErrBadRequest
|
|
}
|
|
|
|
server := models.Server{
|
|
Name: data["name"],
|
|
IP: data["ip"],
|
|
}
|
|
|
|
database.DB.Create(&server)
|
|
|
|
if server.ID == 0 {
|
|
return fiber.ErrNotAcceptable
|
|
}
|
|
|
|
return c.JSON(server)
|
|
}
|
|
|
|
// GetAllServers - Returns all servers
|
|
func GetAllServers(c *fiber.Ctx) error {
|
|
|
|
u := c.Locals("user").(models.User)
|
|
|
|
if u.UserType != "A" {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User is not admin")
|
|
}
|
|
|
|
var servers []models.Server
|
|
|
|
database.DB.Find(&servers)
|
|
|
|
if len(servers) == 0 {
|
|
return fiber.ErrNotFound
|
|
}
|
|
|
|
return c.JSON(servers)
|
|
}
|
|
|
|
func GetServerInfo(c *fiber.Ctx) error {
|
|
|
|
var diskPercent float64 = 0.0
|
|
var memoryPercent float64 = 0.0
|
|
var cpuPercent float64 = 0.0
|
|
|
|
// Get info from the host
|
|
hostStat, _ := host.Info()
|
|
|
|
// Get info from the host disks
|
|
if hostStat.OS == "windows" {
|
|
var total, free uint64 = 0.0, 0.0
|
|
partitions, _ := disk.Partitions(false)
|
|
for _, partition := range partitions {
|
|
v3, _ := disk.Usage(partition.Device)
|
|
total = total + v3.Total
|
|
free = free + v3.Free
|
|
}
|
|
diskPercent = (float64(total-free) / float64(total)) * 100
|
|
} else {
|
|
diskstat, _ := disk.Usage("/")
|
|
diskPercent = diskstat.UsedPercent
|
|
}
|
|
|
|
// Get info from the host memory
|
|
v, _ := mem.VirtualMemory()
|
|
memoryPercent = v.UsedPercent
|
|
|
|
// Get info from the host CPUs
|
|
cpus := 0
|
|
v4, _ := cpu.Percent(0, true)
|
|
for _, cpu := range v4 {
|
|
cpus++
|
|
cpuPercent = cpuPercent + cpu
|
|
}
|
|
cpuPercent = cpuPercent / float64(cpus)
|
|
|
|
c.Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
type result struct {
|
|
Memory float64 `json:"memory"`
|
|
CPU float64 `json:"cpu"`
|
|
Disk float64 `json:"disk"`
|
|
}
|
|
|
|
return c.JSON(result{Memory: memoryPercent, CPU: cpuPercent, Disk: diskPercent})
|
|
}
|