diff --git a/README.md b/README.md index c096881..7317a0b 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/config_example.json b/config_example.json index ed7a511..fa7b82c 100644 --- a/config_example.json +++ b/config_example.json @@ -1,6 +1,7 @@ { "GraphqlURL": "http://localhost:8090/graphql/", "GraphqlAPIToken": "Token SECRET", + "CacheExpire": 0, "queries":[ { "query": "query {device_list {name serial custom_fields}}", diff --git a/pkg/config/config.go b/pkg/config/config.go index 3f671dc..f4a5a26 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -9,6 +9,7 @@ import ( type Cfg struct { GraphqlURL string GraphqlAPIToken string + CacheExpire int64 Queries []Query } diff --git a/pkg/prometheus/prometheus.go b/pkg/prometheus/prometheus.go index 912a752..b38feb4 100644 --- a/pkg/prometheus/prometheus.go +++ b/pkg/prometheus/prometheus.go @@ -13,6 +13,8 @@ import ( "reflect" "strconv" "strings" + "sync" + "time" ) type Graphql struct { @@ -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) { @@ -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)