diff --git a/Dockerfile.golang b/Dockerfile.golang index cbeacb767..a7f4f1daf 100644 --- a/Dockerfile.golang +++ b/Dockerfile.golang @@ -7,15 +7,15 @@ RUN apk add --no-cache gcc musl-dev sqlite-dev # Establecer el directorio de trabajo WORKDIR /app -# Copiar los archivos de dependencias -COPY apps/golang/go.mod apps/golang/go.sum ./ +# Copiar todo el código fuente primero +COPY . . + +# Movernos al directorio de la aplicación golang +WORKDIR /app/apps/golang # Descargar dependencias RUN go mod download -# Copiar el código fuente -COPY apps/golang/ ./ - # Compilar la aplicación RUN CGO_ENABLED=1 GOOS=linux go build -o monitoring main.go @@ -23,7 +23,7 @@ RUN CGO_ENABLED=1 GOOS=linux go build -o monitoring main.go FROM alpine:3.19 # Instalar SQLite y otras dependencias necesarias -RUN apk add --no-cache sqlite-libs +RUN apk add --no-cache sqlite-libs docker-cli # Crear el directorio para la base de datos RUN mkdir -p /etc/dokploy/monitoring @@ -31,7 +31,10 @@ RUN mkdir -p /etc/dokploy/monitoring WORKDIR /app # Copiar el binario compilado desde la etapa de construcción -COPY --from=builder /app/monitoring . +COPY --from=builder /app/apps/golang/monitoring . + +# Copiar el archivo .env si existe +COPY --from=builder /app/apps/golang/.env ./.env # Exponer el puerto ENV PORT=3001 diff --git a/apps/golang/containers/monitor.go b/apps/golang/containers/monitor.go index 34e2fd0e8..672ea6217 100644 --- a/apps/golang/containers/monitor.go +++ b/apps/golang/containers/monitor.go @@ -34,17 +34,22 @@ func NewContainerMonitor(db *database.DB) (*ContainerMonitor, error) { func (cm *ContainerMonitor) Start() error { if err := LoadConfig(); err != nil { - return fmt.Errorf("failed to load config: %v", err) + return fmt.Errorf("error loading config: %v", err) } - refreshRate := 10000 // default 10 seconds + // 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 { - refreshRate = rate + refreshRateSeconds = rate } } - ticker := time.NewTicker(time.Duration(refreshRate) * time.Millisecond) + // Convertir segundos a milisegundos para el ticker + refreshRateMs := refreshRateSeconds * 1000 + log.Printf("Container metrics collection will run every %d seconds", refreshRateSeconds) + + ticker := time.NewTicker(time.Duration(refreshRateMs) * time.Millisecond) go func() { for { select { @@ -111,15 +116,18 @@ func (cm *ContainerMonitor) collectMetrics() { } serviceName := GetServiceName(container.Name) + + log.Printf("Processing container: %+v", container) if seenServices[serviceName] { continue } + seenServices[serviceName] = true // Procesar métricas metric := processContainerMetrics(container) - log.Printf("Saving metrics for %s: %+v", serviceName, metric) + // log.Printf("Saving metrics for %s: %+v", serviceName, metric) if err := cm.db.SaveContainerMetric(metric); err != nil { log.Printf("Error saving metrics for %s: %v", serviceName, err) @@ -132,7 +140,7 @@ func processContainerMetrics(container Container) *database.ContainerMetric { // Procesar CPU cpu, _ := strconv.ParseFloat(strings.TrimSuffix(container.CPUPerc, "%"), 64) - // log.Printf("CPU: %v from %v", cpu, container.CPUPerc) + log.Printf("CPU: %v from %v", cpu, container.CPUPerc) // Procesar Memoria memPerc, _ := strconv.ParseFloat(strings.TrimSuffix(container.MemPerc, "%"), 64) diff --git a/apps/golang/database/containers.go b/apps/golang/database/containers.go index 7d7108e1c..152e53c55 100644 --- a/apps/golang/database/containers.go +++ b/apps/golang/database/containers.go @@ -3,7 +3,6 @@ package database import ( "encoding/json" "fmt" - "log" "strings" ) @@ -50,20 +49,18 @@ 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) - } - } - log.Printf("Available container names in database: %v", names) - log.Printf("Searching for container name: %s", containerName) - } + // 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, "/") @@ -71,7 +68,7 @@ func (db *DB) GetContainerMetrics(containerName string, limit int) ([]ContainerM if len(parts) > 1 { containerName = strings.Join(parts[:len(parts)-1], "-") } - log.Printf("Transformed container name for search: %s", containerName) + // log.Printf("Transformed container name for search: %s", containerName) query := ` WITH recent_metrics AS ( @@ -83,7 +80,7 @@ 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) + // 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 @@ -153,10 +150,10 @@ type ContainerMetric struct { type MemoryMetric struct { Percentage float64 `json:"percentage"` - Used float64 `json:"used"` - Total float64 `json:"total"` - UsedUnit string `json:"usedUnit"` - TotalUnit string `json:"totalUnit"` + Used float64 `json:"used"` + Total float64 `json:"total"` + UsedUnit string `json:"usedUnit"` + TotalUnit string `json:"totalUnit"` } type NetworkMetric struct { diff --git a/apps/golang/main.go b/apps/golang/main.go index ba8b4c07b..444f19e14 100644 --- a/apps/golang/main.go +++ b/apps/golang/main.go @@ -17,6 +17,12 @@ 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")) + log.Printf("CONTAINER_MONITORING_CONFIG: %s", os.Getenv("CONTAINER_MONITORING_CONFIG")) + // Initialize database db, err := database.InitDB() if err != nil { @@ -94,7 +100,7 @@ func main() { limitNum = 50 } - log.Printf("Fetching container metrics for app: %s, limit: %d", appName, limitNum) + // log.Printf("Fetching container metrics for app: %s, limit: %d", appName, limitNum) var metrics []database.ContainerMetric if appName != "" { metrics, err = db.GetContainerMetrics(appName, limitNum) @@ -115,7 +121,6 @@ func main() { go func() { refreshRate := os.Getenv("REFRESH_RATE_SERVER") - log.Printf("REFRESH_RATE_SERVER: %v", refreshRate) duration := 10 * time.Second // default value if refreshRate != "" { if seconds, err := strconv.Atoi(refreshRate); err == nil { @@ -124,6 +129,8 @@ func main() { log.Printf("Invalid REFRESH_RATE_SERVER value, using default: %v", err) } } + + log.Printf("Refreshing server metrics every %v", duration) ticker := time.NewTicker(duration) for range ticker.C { metrics := monitoring.GetServerMetrics() diff --git a/apps/golang/monitoring.db b/apps/golang/monitoring.db index 5bfbd8f5b..83fee6fb7 100644 Binary files a/apps/golang/monitoring.db and b/apps/golang/monitoring.db differ diff --git a/packages/server/src/setup/monitoring-setup.ts b/packages/server/src/setup/monitoring-setup.ts index 5b06572dc..874f88c1c 100644 --- a/packages/server/src/setup/monitoring-setup.ts +++ b/packages/server/src/setup/monitoring-setup.ts @@ -12,8 +12,8 @@ export const setupMonitoring = async (serverId: string) => { const settings: ContainerCreateOptions = { name: containerName, Env: [ - `REFRESH_RATE_SERVER=${server.serverRefreshRateMetrics * 1000}`, - `CONTAINER_REFRESH_RATE=${server.containerRefreshRateMetrics * 1000}`, + `REFRESH_RATE_SERVER=${server.serverRefreshRateMetrics}`, + `CONTAINER_REFRESH_RATE=${server.containerRefreshRateMetrics}`, `CONTAINER_MONITORING_CONFIG=${JSON.stringify( server?.containersMetricsDefinition, )}`,