Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: adding sqldb check #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions checks/sqldb/sqldb.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package mysqldb

import (
"context"
"database/sql"
"net/http"
"time"

"github.com/nelkinda/health-go"
)

type sqldb struct {
client *sql.DB
componentID string
timeout time.Duration
threshold time.Duration
}

func (m *sqldb) HealthChecks() map[string][]health.Checks {
start := time.Now().UTC()
startTime := start.Format(time.RFC3339Nano)
ctx, cancel := context.WithTimeout(context.Background(), m.timeout)
defer cancel()

checks := health.Checks{
ComponentID: m.componentID,
Time: startTime,
}

err := m.client.PingContext(ctx)
if err != nil {
checks.Output = err.Error()
checks.Status = health.Fail

return map[string][]health.Checks{"mysqldb:responseTime": {checks}}
}

end := time.Now().UTC()
responseTime := end.Sub(start)
checks.ObservedValue = responseTime.Nanoseconds()
checks.ObservedUnit = "ns"
if responseTime > m.threshold {
checks.Status = health.Warn
} else {
checks.Status = health.Pass
}

return map[string][]health.Checks{"mongodb:responseTime": {checks}}
}

// AuthorizeHealth return authorize flag status for health checks
func (m *sqldb) AuthorizeHealth(*http.Request) bool {
return true
}

// Health returns a ChecksProvider for health checks about the process uptime.
// Note that it does not really return the process uptime, but the time since calling this function.
func Health(componentID string, client *sql.DB, timeout time.Duration, threshold time.Duration) health.ChecksProvider {
return &sqldb{componentID: componentID, client: client, timeout: timeout, threshold: threshold}
}