Skip to content

Commit

Permalink
graphql-exporter: implement caching
Browse files Browse the repository at this point in the history
  • Loading branch information
Seitanas committed Oct 12, 2023
1 parent 1759b50 commit 7b889df
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ graphql_exporter_custom_fields_price{name="server",order_contract_id="contract-n
```

API token can be overridden with `GRAPHQLAPITOKEN` env variable.
`CacheExpire` configuration parameter defines cache validity period. Value of `0` disables caching.
1 change: 1 addition & 0 deletions config_example.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"GraphqlURL": "http://localhost:8090/graphql/",
"GraphqlAPIToken": "Token SECRET",
"CacheExpire": 0,
"queries":[
{
"query": "query {device_list {name serial custom_fields}}",
Expand Down
1 change: 1 addition & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
type Cfg struct {
GraphqlURL string
GraphqlAPIToken string
CacheExpire int64
Queries []Query
}

Expand Down
18 changes: 16 additions & 2 deletions pkg/prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"reflect"
"strconv"
"strings"
"sync"
"time"
)

type Graphql struct {
Expand All @@ -32,6 +34,12 @@ type Label struct {
Value string
}

var (
metrics_cache []Metric
cache_time = int64(0)
mutex = sync.RWMutex{}
)

const metric_prepend = "graphql_exporter_"

func buildValueData(val_hash map[string]interface{}, m string) (string, string, error) {
Expand Down Expand Up @@ -152,11 +160,17 @@ func buildPromDesc(name string, description string, labels map[string]string) *p
}

func (collector *graphqlCollector) Collect(ch chan<- prometheus.Metric) {
metrics, err := getMetrics()
var err error
mutex.Lock()
if time.Now().Unix()-cache_time > config.Config.CacheExpire {
metrics_cache, err = getMetrics()
cache_time = time.Now().Unix()
}
mutex.Unlock()
if err != nil {
log.Printf("%s", err)
}
for _, metric := range metrics {
for _, metric := range metrics_cache {
var desc *prometheus.Desc
if value, err := strconv.ParseFloat(metric.Value, 64); err == nil {
desc = buildPromDesc(metric.Name, metric.Description, metric.Labels)
Expand Down

0 comments on commit 7b889df

Please sign in to comment.