forked from IDerr/co2_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exporter.py
executable file
·65 lines (58 loc) · 1.71 KB
/
exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
# coding=utf-8
import datetime
import logging
import os
import requests
import time
import traceback
from prometheus_client import start_http_server, Summary, Gauge
URL = "https://opendata.reseaux-energies.fr/api/records/1.0/search/"
# Env Variables
EXPORTER_PORT = int(os.environ.get('EXPORTER_PORT', 9143))
RUN_INTERVAL = int(os.environ.get('RUN_INTERVAL', 180))
pgauge = {}
def isnt_float(value):
try:
float(value)
return False
except:
return True
def isnt_int(value):
try:
int(value)
return False
except:
return True
def get_api():
now = datetime.datetime.utcnow()
params={
"dataset": "eco2mix-national-tr",
"q": "date_heure:[{}-{}-{}T{}:{}:00Z TO {}-{}-{}T{}:{}:00Z]".format(now.year,now.month,now.day,now.hour - 2,now.minute,now.year, now.month,now.day,now.hour-1,now.minute),
"sort": "-date_heure",
"facet": ["nature", "date_heure"],
"timezone": "Europe/Paris",
"rows": 100
}
res = requests.get(URL, params=params).json()
return res
def update_metrics():
res = get_api()
record = {}
for drd in res["records"]:
for field in drd["fields"]:
record[field] = drd["fields"][field]
for field in record:
if isnt_float(record[field]) and isnt_int(record[field]) : continue
if not field in pgauge:
pgauge[field] = Gauge("rte_"+field, field)
pgauge[field].set(record[field])
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
start_http_server(EXPORTER_PORT)
while True:
try:
update_metrics()
except Exception as e:
print(traceback.format_exc())
time.sleep(RUN_INTERVAL)