114 lines
2.6 KiB
Go
114 lines
2.6 KiB
Go
package health
|
|
|
|
import (
|
|
"context"
|
|
"github.com/redis/go-redis/v9"
|
|
"gorm.io/gorm"
|
|
rabbitmq "base/pkg/rabbit"
|
|
"time"
|
|
)
|
|
|
|
func DatabaseHealthChecker(db *gorm.DB) Checker {
|
|
return func(ctx context.Context) HealthCheck {
|
|
start := time.Now()
|
|
check := HealthCheck{
|
|
Name: "database",
|
|
Timestamp: time.Now(),
|
|
}
|
|
|
|
// Perform health check
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
check.Status = StatusUnhealthy
|
|
check.Message = "Failed to get database connection: " + err.Error()
|
|
check.Duration = time.Since(start)
|
|
return check
|
|
}
|
|
|
|
err = sqlDB.PingContext(ctx)
|
|
if err != nil {
|
|
check.Status = StatusUnhealthy
|
|
check.Message = "Database ping failed: " + err.Error()
|
|
check.Duration = time.Since(start)
|
|
return check
|
|
}
|
|
|
|
check.Status = StatusHealthy
|
|
check.Message = "Database connection is healthy"
|
|
check.Duration = time.Since(start)
|
|
check.Details = map[string]interface{}{
|
|
"connected": true,
|
|
}
|
|
|
|
return check
|
|
}
|
|
}
|
|
|
|
func RabbitMQHealthChecker(rabbitmq rabbitmq.Client) Checker {
|
|
return func(ctx context.Context) HealthCheck {
|
|
start := time.Now()
|
|
check := HealthCheck{
|
|
Name: "rabbitmq",
|
|
Timestamp: time.Now(),
|
|
}
|
|
|
|
// Perform health check
|
|
err := rabbitmq.HealthCheck()
|
|
if err != nil {
|
|
check.Status = StatusUnhealthy
|
|
check.Message = "RabbitMQ health check failed: " + err.Error()
|
|
check.Duration = time.Since(start)
|
|
return check
|
|
}
|
|
|
|
check.Status = StatusHealthy
|
|
check.Message = "RabbitMQ connection is healthy"
|
|
check.Duration = time.Since(start)
|
|
check.Details = map[string]interface{}{
|
|
"connected": true,
|
|
}
|
|
|
|
return check
|
|
}
|
|
}
|
|
|
|
func RedisHealthChecker(redis *redis.Client) Checker {
|
|
return func(ctx context.Context) HealthCheck {
|
|
start := time.Now()
|
|
check := HealthCheck{
|
|
Name: "redis",
|
|
Timestamp: time.Now(),
|
|
}
|
|
|
|
// Perform health check
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
|
|
_, err := redis.Ping(ctx).Result()
|
|
if err != nil {
|
|
check.Status = StatusUnhealthy
|
|
check.Message = "Redis ping failed: " + err.Error()
|
|
check.Duration = time.Since(start)
|
|
return check
|
|
}
|
|
|
|
// Get Redis info
|
|
info, err := redis.Info(ctx, "server", "clients", "memory", "stats").Result()
|
|
if err != nil {
|
|
check.Status = StatusDegraded
|
|
check.Message = "Redis is responding but info command failed: " + err.Error()
|
|
check.Duration = time.Since(start)
|
|
return check
|
|
}
|
|
|
|
check.Status = StatusHealthy
|
|
check.Message = "Redis connection is healthy"
|
|
check.Duration = time.Since(start)
|
|
check.Details = map[string]interface{}{
|
|
"info": info,
|
|
}
|
|
|
|
return check
|
|
}
|
|
}
|