85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"pleroma_stats_exporter/config"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
)
|
|
|
|
type metrics struct {
|
|
InstancesCount prometheus.Gauge
|
|
FollowersCount prometheus.Gauge
|
|
}
|
|
|
|
func SetMetricsOpts(reg prometheus.Registerer) *metrics {
|
|
metricsOpts := &metrics{
|
|
InstancesCount: prometheus.NewGauge(
|
|
prometheus.GaugeOpts{
|
|
Name: "pleroma_instances_count",
|
|
Help: "Количество инстансов",
|
|
},
|
|
),
|
|
FollowersCount: prometheus.NewGauge(
|
|
prometheus.GaugeOpts{
|
|
Name: "pleroma_user_followers",
|
|
Help: "Количество подписчиков",
|
|
},
|
|
),
|
|
}
|
|
reg.MustRegister(metricsOpts.InstancesCount)
|
|
reg.MustRegister(metricsOpts.FollowersCount)
|
|
return metricsOpts
|
|
}
|
|
|
|
func getJson(url string) string {
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
return string(body)
|
|
}
|
|
|
|
func unmJson(jsonString string) map[string]any {
|
|
decodedJson := map[string]any{}
|
|
err := json.Unmarshal([]byte(jsonString), &decodedJson)
|
|
if err != nil {
|
|
log.Println(err)
|
|
}
|
|
return decodedJson
|
|
}
|
|
|
|
func updateMetrics(instanceMetrics *metrics, confFile config.InstanceVars) {
|
|
instanceStat := unmJson(getJson("https://" + confFile.Target.Instance + "/api/v1/instance"))["stats"]
|
|
instanceCount := instanceStat.(map[string]interface{})
|
|
userFollowers := unmJson(getJson("https://" + confFile.Target.Instance + "/api/v1/accounts/" + confFile.Target.UserID))["followers_count"]
|
|
instanceMetrics.InstancesCount.Set(instanceCount["domain_count"].(float64))
|
|
instanceMetrics.FollowersCount.Set(userFollowers.(float64))
|
|
}
|
|
|
|
func main() {
|
|
confFile := config.UnmYamlConfig("config.yaml")
|
|
|
|
reg := prometheus.NewRegistry()
|
|
instanceMetrics := SetMetricsOpts(reg)
|
|
|
|
go func() {
|
|
for {
|
|
updateMetrics(instanceMetrics, confFile)
|
|
time.Sleep(5 * time.Minute)
|
|
}
|
|
}()
|
|
|
|
http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
|
|
log.Fatal(http.ListenAndServe(confFile.Exporter.Listen+":"+confFile.Exporter.Port, nil))
|
|
}
|