2025-01-07 16:01:49 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2025-01-08 19:29:05 +01:00
|
|
|
"os"
|
2025-01-09 17:29:36 +01:00
|
|
|
"strings"
|
2025-01-07 16:01:49 +01:00
|
|
|
|
|
|
|
"git.keyzox.me/42_adjoly/inception/internal/env"
|
|
|
|
"git.keyzox.me/42_adjoly/inception/internal/log"
|
|
|
|
)
|
|
|
|
|
2025-01-08 19:29:05 +01:00
|
|
|
func escapeIdentifier(identifier string) string {
|
|
|
|
// Replace backticks with double backticks to safely escape identifiers
|
|
|
|
return fmt.Sprintf("`%s`", strings.ReplaceAll(identifier, "'", "\""))
|
|
|
|
}
|
|
|
|
|
|
|
|
func escapePassword(password string) string {
|
|
|
|
// Escape single quotes in passwords
|
|
|
|
return strings.ReplaceAll(password, "'", "\\'")
|
|
|
|
}
|
|
|
|
|
2025-01-09 17:29:36 +01:00
|
|
|
func checkHealth(host, user, pass, port, dbName string) bool {
|
2025-01-07 16:01:49 +01:00
|
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, pass, host, port, dbName)
|
2025-01-09 17:29:36 +01:00
|
|
|
|
|
|
|
// Attempt to open a database connection
|
2025-01-07 16:01:49 +01:00
|
|
|
db, err := sql.Open("mysql", dsn)
|
|
|
|
if err != nil {
|
2025-01-09 17:29:36 +01:00
|
|
|
_log.Log("warning", fmt.Sprintf("Failed to open database connection: %v", err))
|
|
|
|
return false
|
2025-01-07 16:01:49 +01:00
|
|
|
}
|
|
|
|
defer db.Close()
|
2025-01-09 17:29:36 +01:00
|
|
|
|
|
|
|
// Attempt to ping the database
|
2025-01-07 16:01:49 +01:00
|
|
|
if err := db.Ping(); err != nil {
|
2025-01-09 17:29:36 +01:00
|
|
|
_log.Log("warning", fmt.Sprintf("Health check failed: %v", err))
|
|
|
|
return false
|
2025-01-07 16:01:49 +01:00
|
|
|
}
|
2025-01-09 17:29:36 +01:00
|
|
|
|
|
|
|
_log.Log("note", "Health check passed successfully")
|
2025-01-07 16:01:49 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2025-01-09 17:29:36 +01:00
|
|
|
func main() {
|
|
|
|
// Load environment variables
|
2025-01-08 19:29:05 +01:00
|
|
|
pass := escapePassword(env.FileEnv("MYSQL_PASSWORD", "default"))
|
|
|
|
user := escapeIdentifier(env.FileEnv("MYSQL_USER", "mariadb"))
|
|
|
|
dbName := escapeIdentifier(env.EnvCheck("MYSQL_DATABASE", "default"))
|
2025-01-09 17:29:36 +01:00
|
|
|
dbHost := "127.0.0.1"
|
2025-01-07 16:01:49 +01:00
|
|
|
|
2025-01-09 17:29:36 +01:00
|
|
|
// Perform the health check
|
2025-01-07 16:01:49 +01:00
|
|
|
res := checkHealth(dbHost, user, pass, "3306", dbName)
|
2025-01-09 17:29:36 +01:00
|
|
|
if res {
|
|
|
|
_log.Log("note", "MariaDB is healthy")
|
2025-01-08 19:29:05 +01:00
|
|
|
os.Exit(0)
|
2025-01-07 16:01:49 +01:00
|
|
|
}
|
2025-01-09 17:29:36 +01:00
|
|
|
|
|
|
|
_log.Log("warning", "Health check failed")
|
|
|
|
os.Exit(1)
|
2025-01-07 16:01:49 +01:00
|
|
|
}
|