fuelprice-exporter/collector/collector.go

139 lines
4 KiB
Go
Raw Normal View History

2024-07-11 10:37:53 +02:00
/*
Copyright 2024 Adora Laura Kalb <adora@lila.network>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package collector
import (
"context"
"encoding/json"
"io"
"net/http"
"net/netip"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"golang.adora.codes/template-exporter/cache"
"golang.adora.codes/template-exporter/models"
)
type Metrics struct {
NtpppolServerScore prometheus.Gauge
}
type Collector struct {
ctx context.Context
target netip.Addr
logger log.Logger
metrics Metrics
}
func New(ctx context.Context, target netip.Addr, logger log.Logger, metrics Metrics) *Collector {
return &Collector{ctx: ctx, target: target, logger: logger, metrics: metrics}
}
// Describe implements Prometheus.Collector.
func (c Collector) Describe(ch chan<- *prometheus.Desc) {
ch <- prometheus.NewDesc("dummy", "dummy", nil, nil)
}
// Collect implements Prometheus.Collector.
func (c Collector) Collect(ch chan<- prometheus.Metric) {
logger := log.With(c.logger, "module", "scraper")
level.Debug(logger).Log("msg", "Starting scrape")
start := time.Now()
c.collect(ch, logger)
duration := time.Since(start).Seconds()
level.Debug(logger).Log("msg", "Finished scrape", "duration_seconds", duration)
}
func (c Collector) collect(ch chan<- prometheus.Metric, logger log.Logger) {
score, err := cache.GlobalScoreCache.Get(c.target)
if err == nil {
level.Debug(logger).Log("msg", "Serving score from cache",
"server", c.target.String(), "score", score.Score)
serverScoreMetric := prometheus.NewDesc("template_server_score",
"Shows the server score currently assigned at template.org",
nil, nil)
m1 := prometheus.MustNewConstMetric(serverScoreMetric, prometheus.GaugeValue, score.Score)
m1 = prometheus.NewMetricWithTimestamp(time.Now(), m1)
ch <- m1
return
}
level.Debug(logger).Log("msg", "Cache miss, querying API",
"server", c.target.String())
var serverApiScore float64 = 0
const apiEndpoint = "https://www.template.org/scores/"
const apiQuery = "/json?limit=1&monitor=24"
url := apiEndpoint + c.target.String() + apiQuery
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
level.Error(logger).Log("msg", "Error sending HTTP request", "url", url, "message", err)
return
}
res, err := client.Do(req)
if err != nil {
level.Error(logger).Log("msg", "Error in HTTP response", "error", err)
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
level.Error(logger).Log("msg", "Error reading HTTP response body", "error", err)
return
}
var response models.ApiResponse
err = json.Unmarshal(body, &response)
if err != nil {
level.Error(logger).Log("msg", "Error unmarshaling JSON body", "error", err)
return
}
serverApiScore = response.History[0].Score
cache.GlobalScoreCache.Add(serverApiScore, c.target, time.Now())
level.Debug(logger).Log("msg", "Added score to cache",
"server", c.target.String(), "score", score.Score)
// TODO: Test or delete
serverScoreMetric := prometheus.NewDesc("template_server_score",
"Shows the server score currently assigned at template.org",
nil, nil)
// TODO: Test or delete
//c.metrics.NtpppolServerScore.Add(serverApiScore)
// TODO: Test or delete
//Write latest value for each metric in the prometheus metric channel.
//Note that you can pass CounterValue, GaugeValue, or UntypedValue types here.
m1 := prometheus.MustNewConstMetric(serverScoreMetric, prometheus.GaugeValue, serverApiScore)
m1 = prometheus.NewMetricWithTimestamp(time.Now(), m1)
ch <- m1
}