Skip to content

Commit

Permalink
refactor: update dockerfile
Browse files Browse the repository at this point in the history
  • Loading branch information
Siumauricio committed Jan 4, 2025
1 parent 64c5c0d commit dbbabe7
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 38 deletions.
17 changes: 10 additions & 7 deletions Dockerfile.golang
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,34 @@ 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

# Etapa final
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

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
Expand Down
20 changes: 14 additions & 6 deletions apps/golang/containers/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
39 changes: 18 additions & 21 deletions apps/golang/database/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package database
import (
"encoding/json"
"fmt"
"log"
"strings"
)

Expand Down Expand Up @@ -50,28 +49,26 @@ 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, "/")
parts := strings.Split(name, "-")
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 (
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
11 changes: 9 additions & 2 deletions apps/golang/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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()
Expand Down
Binary file modified apps/golang/monitoring.db
Binary file not shown.
4 changes: 2 additions & 2 deletions packages/server/src/setup/monitoring-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)}`,
Expand Down

0 comments on commit dbbabe7

Please sign in to comment.