Skip to content

Commit

Permalink
refactor: update go
Browse files Browse the repository at this point in the history
  • Loading branch information
Siumauricio committed Jan 4, 2025
1 parent c613328 commit 0b1702b
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 72 deletions.
58 changes: 42 additions & 16 deletions apps/golang/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,24 @@ import (
)

type ServerMetric struct {
Timestamp int64 `json:"timestamp"`
CPUUsage float64 `json:"cpuUsage"`
MemoryUsage float64 `json:"memoryUsage"`
MemoryTotal uint64 `json:"memoryTotal"`
CPUModel string `json:"cpuModel"`
Timestamp int64 `json:"timestamp"`
CPU float64 `json:"cpu"`
CPUModel string `json:"cpuModel"`
CPUCores int32 `json:"cpuCores"`
CPUPhysicalCores int32 `json:"cpuPhysicalCores"`
CPUSpeed float64 `json:"cpuSpeed"`
OS string `json:"os"`
Distro string `json:"distro"`
Kernel string `json:"kernel"`
Arch string `json:"arch"`
MemUsed float64 `json:"memUsed"`
MemUsedGB float64 `json:"memUsedGB"`
MemTotal float64 `json:"memTotal"`
Uptime uint64 `json:"uptime"`
DiskUsed float64 `json:"diskUsed"`
TotalDisk float64 `json:"totalDisk"`
NetworkIn float64 `json:"networkIn"`
NetworkOut float64 `json:"networkOut"`
}

type DB struct {
Expand All @@ -28,10 +41,23 @@ func InitDB() (*DB, error) {
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS server_metrics (
timestamp INTEGER PRIMARY KEY,
cpu_usage REAL,
memory_usage REAL,
memory_total INTEGER,
cpu_model TEXT
cpu REAL,
cpu_model TEXT,
cpu_cores INTEGER,
cpu_physical_cores INTEGER,
cpu_speed REAL,
os TEXT,
distro TEXT,
kernel TEXT,
arch TEXT,
mem_used REAL,
mem_used_gb REAL,
mem_total REAL,
uptime INTEGER,
disk_used REAL,
total_disk REAL,
network_in REAL,
network_out REAL
)
`)
if err != nil {
Expand All @@ -43,15 +69,15 @@ func InitDB() (*DB, error) {

func (db *DB) SaveMetric(metric ServerMetric) error {
_, err := db.Exec(`
INSERT INTO server_metrics (timestamp, cpu_usage, memory_usage, memory_total, cpu_model)
VALUES (?, ?, ?, ?, ?)
`, metric.Timestamp, metric.CPUUsage, metric.MemoryUsage, metric.MemoryTotal, metric.CPUModel)
INSERT INTO server_metrics (timestamp, cpu, cpu_model, cpu_cores, cpu_physical_cores, cpu_speed, os, distro, kernel, arch, mem_used, mem_used_gb, mem_total, uptime, disk_used, total_disk, network_in, network_out)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, metric.Timestamp, metric.CPU, metric.CPUModel, metric.CPUCores, metric.CPUPhysicalCores, metric.CPUSpeed, metric.OS, metric.Distro, metric.Kernel, metric.Arch, metric.MemUsed, metric.MemUsedGB, metric.MemTotal, metric.Uptime, metric.DiskUsed, metric.TotalDisk, metric.NetworkIn, metric.NetworkOut)
return err
}

func (db *DB) GetMetricsInRange(start, end int64) ([]ServerMetric, error) {
rows, err := db.Query(`
SELECT timestamp, cpu_usage, memory_usage, memory_total, cpu_model
SELECT timestamp, cpu, cpu_model, cpu_cores, cpu_physical_cores, cpu_speed, os, distro, kernel, arch, mem_used, mem_used_gb, mem_total, uptime, disk_used, total_disk, network_in, network_out
FROM server_metrics
WHERE timestamp BETWEEN ? AND ?
ORDER BY timestamp DESC
Expand All @@ -64,7 +90,7 @@ func (db *DB) GetMetricsInRange(start, end int64) ([]ServerMetric, error) {
var metrics []ServerMetric
for rows.Next() {
var m ServerMetric
err := rows.Scan(&m.Timestamp, &m.CPUUsage, &m.MemoryUsage, &m.MemoryTotal, &m.CPUModel)
err := rows.Scan(&m.Timestamp, &m.CPU, &m.CPUModel, &m.CPUCores, &m.CPUPhysicalCores, &m.CPUSpeed, &m.OS, &m.Distro, &m.Kernel, &m.Arch, &m.MemUsed, &m.MemUsedGB, &m.MemTotal, &m.Uptime, &m.DiskUsed, &m.TotalDisk, &m.NetworkIn, &m.NetworkOut)
if err != nil {
return nil, err
}
Expand All @@ -75,7 +101,7 @@ func (db *DB) GetMetricsInRange(start, end int64) ([]ServerMetric, error) {

func (db *DB) GetLastNMetrics(n int) ([]ServerMetric, error) {
rows, err := db.Query(`
SELECT timestamp, cpu_usage, memory_usage, memory_total, cpu_model
SELECT timestamp, cpu, cpu_model, cpu_cores, cpu_physical_cores, cpu_speed, os, distro, kernel, arch, mem_used, mem_used_gb, mem_total, uptime, disk_used, total_disk, network_in, network_out
FROM server_metrics
ORDER BY timestamp DESC
LIMIT ?
Expand All @@ -88,7 +114,7 @@ func (db *DB) GetLastNMetrics(n int) ([]ServerMetric, error) {
var metrics []ServerMetric
for rows.Next() {
var m ServerMetric
err := rows.Scan(&m.Timestamp, &m.CPUUsage, &m.MemoryUsage, &m.MemoryTotal, &m.CPUModel)
err := rows.Scan(&m.Timestamp, &m.CPU, &m.CPUModel, &m.CPUCores, &m.CPUPhysicalCores, &m.CPUSpeed, &m.OS, &m.Distro, &m.Kernel, &m.Arch, &m.MemUsed, &m.MemUsedGB, &m.MemTotal, &m.Uptime, &m.DiskUsed, &m.TotalDisk, &m.NetworkIn, &m.NetworkOut)
if err != nil {
return nil, err
}
Expand Down
171 changes: 115 additions & 56 deletions apps/golang/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"fmt"
"log"
"os"
"runtime"
"strconv"
"time"

Expand All @@ -11,24 +13,100 @@ import (
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/joho/godotenv"
"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/shirou/gopsutil/v3/net"
)

type SystemMetrics struct {
CPU string `json:"cpu"`
CPUModel string `json:"cpuModel"`
CPUCores int32 `json:"cpuCores"`
CPUPhysicalCores int32 `json:"cpuPhysicalCores"`
CPUSpeed float64 `json:"cpuSpeed"`
OS string `json:"os"`
Distro string `json:"distro"`
Kernel string `json:"kernel"`
Arch string `json:"arch"`
MemUsed string `json:"memUsed"`
MemUsedGB string `json:"memUsedGB"`
MemTotal string `json:"memTotal"`
Uptime uint64 `json:"uptime"`
DiskUsed string `json:"diskUsed"`
TotalDisk string `json:"totalDisk"`
NetworkIn string `json:"networkIn"`
NetworkOut string `json:"networkOut"`
Timestamp string `json:"timestamp"`
}

func convertToSystemMetrics(metric database.ServerMetric) SystemMetrics {
return SystemMetrics{
CPU: fmt.Sprintf("%.2f", metric.CPU),
CPUModel: metric.CPUModel,
CPUCores: metric.CPUCores,
CPUPhysicalCores: metric.CPUPhysicalCores,
CPUSpeed: metric.CPUSpeed,
OS: metric.OS,
Distro: metric.Distro,
Kernel: metric.Kernel,
Arch: metric.Arch,
MemUsed: fmt.Sprintf("%.2f", metric.MemUsed),
MemUsedGB: fmt.Sprintf("%.2f", metric.MemUsedGB),
MemTotal: fmt.Sprintf("%.2f", metric.MemTotal),
Uptime: metric.Uptime,
DiskUsed: fmt.Sprintf("%.2f", metric.DiskUsed),
TotalDisk: fmt.Sprintf("%.2f", metric.TotalDisk),
NetworkIn: fmt.Sprintf("%.2f", metric.NetworkIn),
NetworkOut: fmt.Sprintf("%.2f", metric.NetworkOut),
Timestamp: time.Unix(metric.Timestamp, 0).Format(time.RFC3339),
}
}

func getServerMetrics() database.ServerMetric {
v, _ := mem.VirtualMemory()
c, _ := cpu.Percent(0, false)
cpuInfo, _ := cpu.Info()
diskInfo, _ := disk.Usage("/")
netInfo, _ := net.IOCounters(false)
hostInfo, _ := host.Info()

cpuModel := ""
if len(cpuInfo) > 0 {
cpuModel = cpuInfo[0].ModelName
cpuModel = fmt.Sprintf("%s %s", cpuInfo[0].VendorID, cpuInfo[0].ModelName)
}

// Calcular memoria en GB
memTotalGB := float64(v.Total) / 1024 / 1024 / 1024
memUsedGB := float64(v.Used) / 1024 / 1024 / 1024
memUsedPercent := (memUsedGB / memTotalGB) * 100

// Calcular red en MB
var networkIn, networkOut float64
if len(netInfo) > 0 {
networkIn = float64(netInfo[0].BytesRecv) / 1024 / 1024
networkOut = float64(netInfo[0].BytesSent) / 1024 / 1024
}

return database.ServerMetric{
Timestamp: time.Now().Unix(),
CPUUsage: c[0],
MemoryUsage: v.UsedPercent,
MemoryTotal: v.Total,
CPUModel: cpuModel,
Timestamp: time.Now().Unix(),
CPU: c[0],
CPUModel: cpuModel,
CPUCores: int32(runtime.NumCPU()),
CPUPhysicalCores: int32(len(cpuInfo)),
CPUSpeed: float64(cpuInfo[0].Mhz),
OS: hostInfo.OS,
Distro: hostInfo.Platform,
Kernel: hostInfo.KernelVersion,
Arch: hostInfo.KernelArch,
MemUsed: memUsedPercent,
MemUsedGB: memUsedGB,
MemTotal: memTotalGB,
Uptime: hostInfo.Uptime,
DiskUsed: float64(diskInfo.UsedPercent),
TotalDisk: float64(diskInfo.Total) / 1024 / 1024 / 1024,
NetworkIn: networkIn,
NetworkOut: networkOut,
}
}

Expand Down Expand Up @@ -56,55 +134,37 @@ func main() {
})
})

// Get current metrics
app.Get("/metrics/current", func(c *fiber.Ctx) error {
metrics := getServerMetrics()
return c.JSON(metrics)
})

// Get metrics in range
app.Get("/metrics/range", func(c *fiber.Ctx) error {
start := c.Query("start")
end := c.Query("end")

startTime, err := strconv.ParseInt(start, 10, 64)
if err != nil {
return c.Status(400).JSON(fiber.Map{
"error": "Invalid start time",
})
}

endTime, err := strconv.ParseInt(end, 10, 64)
if err != nil {
return c.Status(400).JSON(fiber.Map{
"error": "Invalid end time",
})
}

metrics, err := db.GetMetricsInRange(startTime, endTime)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Failed to fetch metrics",
})
}

return c.JSON(metrics)
})

// Get last N metrics
app.Get("/metrics/last/:count", func(c *fiber.Ctx) error {
count, err := strconv.Atoi(c.Params("count"))
if err != nil {
return c.Status(400).JSON(fiber.Map{
"error": "Invalid count",
})
}

metrics, err := db.GetLastNMetrics(count)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Failed to fetch metrics",
})
// Get metrics endpoint (compatible with frontend)
app.Get("/metrics", func(c *fiber.Ctx) error {
limit := c.Query("limit", "50")

var metrics []SystemMetrics
if limit == "all" {
// Get all metrics
dbMetrics, err := db.GetLastNMetrics(10000)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Failed to fetch metrics",
})
}
for _, m := range dbMetrics {
metrics = append(metrics, convertToSystemMetrics(m))
}
} else {
// Get limited metrics
n, err := strconv.Atoi(limit)
if err != nil {
n = 50 // default value
}
dbMetrics, err := db.GetLastNMetrics(n)
if err != nil {
return c.Status(500).JSON(fiber.Map{
"error": "Failed to fetch metrics",
})
}
for _, m := range dbMetrics {
metrics = append(metrics, convertToSystemMetrics(m))
}
}

return c.JSON(metrics)
Expand All @@ -115,7 +175,6 @@ func main() {
ticker := time.NewTicker(10 * time.Second)
for range ticker.C {
metrics := getServerMetrics()
log.Printf("Saving metrics: %v", metrics)
if err := db.SaveMetric(metrics); err != nil {
log.Printf("Error saving metrics: %v", err)
}
Expand Down
Binary file modified apps/golang/monitoring.db
Binary file not shown.
Binary file removed apps/monitoring/monitoring.db
Binary file not shown.

0 comments on commit 0b1702b

Please sign in to comment.