ntppool-exporter/collector/collector.go

119 lines
3.3 KiB
Go
Raw Normal View History

2024-04-17 12:47:40 +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/ntppool-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, "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) {
httpError := false
var serverApiScore float64 = 0
const apiEndpoint = "https://www.ntppool.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)
httpError = true
}
res, err := client.Do(req)
if err != nil {
level.Error(logger).Log("msg", "Error in HTTP response", "error", err)
return
2024-04-17 12:47:40 +02:00
}
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
2024-04-17 12:47:40 +02:00
}
var response models.ApiResponse
err = json.Unmarshal(body, &response)
if err != nil {
level.Error(logger).Log("msg", "Error unmarshaling JSON body", "error", err)
return
2024-04-17 12:47:40 +02:00
}
if !httpError {
serverApiScore = response.History[0].Score
}
// TODO: Test or delete
serverScoreMetric := prometheus.NewDesc("ntppool_score",
"Shows the server score currently assigned at ntppool.org",
nil, prometheus.Labels{"server": c.target.String()})
// 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
}