Skip to content

Commit

Permalink
refactor: update monitoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Siumauricio committed Jan 4, 2025
1 parent 24c00dd commit f6b0b0b
Show file tree
Hide file tree
Showing 5 changed files with 1 addition and 56 deletions.
3 changes: 0 additions & 3 deletions apps/golang/containers/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,12 @@ func ShouldMonitorContainer(containerName string) bool {
return false
}

// Si está en la lista de excluidos, no monitorear
for _, excluded := range config.ExcludeServices {
if strings.Contains(containerName, excluded.AppName) {
return false
}
}

// Si hay servicios incluidos, solo monitorear esos
if len(config.IncludeServices) > 0 {
for _, included := range config.IncludeServices {
if strings.Contains(containerName, included.AppName) {
Expand Down Expand Up @@ -62,7 +60,6 @@ func GetContainerConfig(containerName string) *ContainerConfig {
}

func GetServiceName(containerName string) string {
// Eliminar caracteres especiales y obtener el nombre base
name := strings.TrimPrefix(containerName, "/")
parts := strings.Split(name, "-")
if len(parts) > 1 {
Expand Down
2 changes: 0 additions & 2 deletions apps/golang/containers/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,13 @@ func (cm *ContainerMonitor) Start() error {
return fmt.Errorf("error loading config: %v", err)
}

// El refresh rate se especifica en segundos en la variable de entorno
refreshRateSeconds := 10 // default 10 segundos
if rateStr := os.Getenv("CONTAINER_REFRESH_RATE"); rateStr != "" {
if rate, err := strconv.Atoi(rateStr); err == nil {
refreshRateSeconds = rate
}
}

// Convertir segundos a milisegundos para el ticker
refreshRateMs := refreshRateSeconds * 1000
log.Printf("Container metrics collection will run every %d seconds", refreshRateSeconds)

Expand Down
17 changes: 0 additions & 17 deletions apps/golang/database/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,11 @@ func (db *DB) SaveContainerMetric(metric *ContainerMetric) error {
}

func (db *DB) GetContainerMetrics(containerName string, limit int) ([]ContainerMetric, error) {
// First, let's see what container names we have
// debugQuery := `SELECT DISTINCT container_name FROM container_metrics`
// debugRows, err := db.Query(debugQuery)
// if err == nil {
// defer debugRows.Close()
// var names []string
// for debugRows.Next() {
// var name string
// if err := debugRows.Scan(&name); err == nil {
// names = append(names, name)
// }
// }
// }

// Transform the container name to match how it's stored
name := strings.TrimPrefix(containerName, "/")
parts := strings.Split(name, "-")
if len(parts) > 1 {
containerName = strings.Join(parts[:len(parts)-1], "-")
}
// log.Printf("Transformed container name for search: %s", containerName)

query := `
WITH recent_metrics AS (
Expand All @@ -80,7 +64,6 @@ func (db *DB) GetContainerMetrics(containerName string, limit int) ([]ContainerM
)
SELECT metrics_json FROM recent_metrics ORDER BY json_extract(metrics_json, '$.timestamp') ASC
`
// log.Printf("Executing query with container_name=%s and limit=%d", containerName, limit)
rows, err := db.Query(query, containerName, limit)
if err != nil {
return nil, err
Expand Down
5 changes: 0 additions & 5 deletions apps/golang/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
func main() {
godotenv.Load()

// Print environment variables at startup
log.Printf("Environment variables:")
log.Printf("REFRESH_RATE_SERVER: %s", os.Getenv("REFRESH_RATE_SERVER"))
log.Printf("CONTAINER_REFRESH_RATE: %s", os.Getenv("CONTAINER_REFRESH_RATE"))
Expand Down Expand Up @@ -80,7 +79,6 @@ func main() {
return c.JSON(metrics)
})

// Iniciar el monitoreo de contenedores
containerMonitor, err := containers.NewContainerMonitor(db)
if err != nil {
log.Fatalf("Failed to create container monitor: %v", err)
Expand All @@ -90,7 +88,6 @@ func main() {
}
defer containerMonitor.Stop()

// Endpoint para obtener métricas de contenedores
app.Get("/metrics/containers", func(c *fiber.Ctx) error {
limit := c.Query("limit", "50")
appName := c.Query("appName", "")
Expand All @@ -100,7 +97,6 @@ func main() {
limitNum = 50
}

// log.Printf("Fetching container metrics for app: %s, limit: %d", appName, limitNum)
var metrics []database.ContainerMetric
if appName != "" {
metrics, err = db.GetContainerMetrics(appName, limitNum)
Expand Down Expand Up @@ -134,7 +130,6 @@ func main() {
ticker := time.NewTicker(duration)
for range ticker.C {
metrics := monitoring.GetServerMetrics()
// log.Printf("Saving metrics: %v", metrics)
if err := db.SaveMetric(metrics); err != nil {
log.Printf("Error saving metrics: %v", err)
}
Expand Down
30 changes: 1 addition & 29 deletions apps/golang/monitoring/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package monitoring

import (
"fmt"
"log"
"os"
"os/exec"
"runtime"
Expand Down Expand Up @@ -40,7 +39,6 @@ type SystemMetrics struct {
}

func getRealOS() string {
// Primero intentamos con /etc/os-release que tiene información más específica
if content, err := os.ReadFile("/etc/os-release"); err == nil {
lines := strings.Split(string(content), "\n")
var id, name, version string
Expand Down Expand Up @@ -99,7 +97,6 @@ func getRealOS() string {
}
}

// Si todo lo demás falla, usamos el OS base
return runtime.GOOS
}

Expand All @@ -112,51 +109,26 @@ func GetServerMetrics() database.ServerMetric {
hostInfo, _ := host.Info()
distro := getRealOS()

log.Print("CPU: ", distro)

// CPU
// Apple M1 Pro

// 8 Physical Cores (8 Threads) @ 2.4GHz

// Operating System
// macOS

// Kernel: 23.4.0 (arm64)

// CPU
// Apple M1 Pro

// 1 Physical Cores (8 Threads) @ 3228GHz

// Operating System
// darwin

// Kernel: 23.4.0 (arm64)

cpuModel := ""
if len(cpuInfo) > 0 {
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
}
log.Printf("Host Info: %v, Network In: %f MB, Network Out: %f MB", hostInfo, networkIn, networkOut)
return database.ServerMetric{
Timestamp: time.Now().Unix(),
CPU: c[0],
CPUModel: cpuModel,
CPUCores: int32(runtime.NumCPU()),
CPUPhysicalCores: int32(len(cpuInfo)), // En Apple Silicon, los cores físicos son iguales a los lógicos
CPUPhysicalCores: int32(len(cpuInfo)),
CPUSpeed: float64(cpuInfo[0].Mhz),
OS: getRealOS(),
Distro: distro,
Expand Down

0 comments on commit f6b0b0b

Please sign in to comment.