56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
|
package internal
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"strings"
|
||
|
|
||
|
dto "github.com/prometheus/client_model/go"
|
||
|
"github.com/prometheus/common/expfmt"
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
func ParseMetrics(metrics string) (map[string]*dto.MetricFamily, error) {
|
||
|
reader := strings.NewReader(metrics)
|
||
|
|
||
|
var parser expfmt.TextParser
|
||
|
mf, err := parser.TextToMetricFamilies(reader)
|
||
|
if err != nil {
|
||
|
return nil, errors.New(fmt.Sprintf("Error decoding metrics: %s", err.Error()))
|
||
|
}
|
||
|
return mf, nil
|
||
|
}
|
||
|
|
||
|
func GetMetrics(cfg *Config, endpoint string) (string, error) {
|
||
|
resp, err := http.Get(fmt.Sprintf("%s://%s", cfg.Protocol, endpoint))
|
||
|
if err != nil {
|
||
|
return "", errors.New(fmt.Sprintf("Error getting metrics: %s", err.Error()))
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
if resp.StatusCode == http.StatusOK {
|
||
|
bodyBytes, err := io.ReadAll(resp.Body)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
bodyString := string(bodyBytes)
|
||
|
return bodyString, nil
|
||
|
}
|
||
|
return "", errors.New(fmt.Sprintf("None ok return code from metrics endoint: %s", resp.Status))
|
||
|
}
|
||
|
|
||
|
func GetIpFromMetrics(metrics *dto.MetricFamily) (string, error) {
|
||
|
for _, metric := range metrics.Metric {
|
||
|
for _, label := range metric.Label {
|
||
|
if *label.Name == "ip" {
|
||
|
log.WithFields(log.Fields{
|
||
|
"Caller": "Main",
|
||
|
}).Info(fmt.Sprintf("Found IP Label: %s", *label.Value))
|
||
|
return *label.Value, nil
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return "", errors.New("Could not find 'ip' in metrics labels")
|
||
|
}
|