Skip to content

Instantly share code, notes, and snippets.

@typingincolor
Created October 13, 2015 07:45
Show Gist options
  • Save typingincolor/b36555f37da32792989d to your computer and use it in GitHub Desktop.
Save typingincolor/b36555f37da32792989d to your computer and use it in GitHub Desktop.
package repository
import (
"encoding/json"
"fmt"
"github.com/influxdb/influxdb/client"
"log"
"time"
)
type HealthCheckRepository interface {
GetHealthChecks() string
GetConnection() *client.Client
}
type HealthCheck struct {
Name string
ResponseTime int
StatusCode int
}
type HealthCheckDetails struct {
Timestamp time.Time
ResponseTime int64
StatusCode int64
}
type InfluxDbHealthCheckRepository struct {
con *client.Client
}
func (i InfluxDbHealthCheckRepository) Save(h HealthCheck) error {
point := createPoint(h)
bps := batch([]client.Point{point})
_, err := i.con.Write(bps)
if err != nil {
log.Fatal(err)
}
return err
}
func (i InfluxDbHealthCheckRepository) GetHealthChecks(name string, period string) (result []HealthCheckDetails, err error) {
res, err := i.queryDB(fmt.Sprintf("SELECT response_time, status_code FROM healthchecks WHERE time > now() - %s AND healthcheck = '%s'", period, name))
if len(res[0].Series) == 0 {
return result, err
}
for _, value := range res[0].Series[0].Values {
timestamp, _ := time.Parse(time.RFC3339Nano, value[0].(string))
responseTime, _ := value[1].(json.Number).Int64()
statusCode, _ := value[2].(json.Number).Int64()
healthcheck := HealthCheckDetails{Timestamp: timestamp, ResponseTime: responseTime, StatusCode: statusCode}
result = append(result, healthcheck)
}
return result, err
}
func (i InfluxDbHealthCheckRepository) GetHealthCheckList() (result []string, err error) {
res, err := i.queryDB("SHOW TAG VALUES FROM healthchecks WITH KEY = healthcheck")
if len(res[0].Series) == 0 {
return result, err
}
for _, value := range res[0].Series[0].Values {
result = append(result, value[0].(string))
}
return result, err
}
func (i InfluxDbHealthCheckRepository) queryDB(cmd string) (res []client.Result, err error) {
q := client.Query{
Command: cmd,
Database: MyDB,
}
if response, err := i.con.Query(q); err == nil {
if response.Error() != nil {
return res, response.Error()
}
res = response.Results
}
return
}
func (i InfluxDbHealthCheckRepository) getConnection() *client.Client {
return i.con
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment