-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeseries.py
More file actions
executable file
·87 lines (80 loc) · 2.65 KB
/
timeseries.py
File metadata and controls
executable file
·87 lines (80 loc) · 2.65 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from influxdb import InfluxDBClient
import yaml, datetime, socket, json
clientSet = False
hostname = socket.gethostname()
def setConf(conf):
#check if timeseries is enabled
if conf['timeseries']['alarming'] == True or conf['timeseries']['logging'] == True:
#load gloabl variable
global cfg
#set global cfg
cfg = conf
else:
print("Timeseries is disabled! -> config.yml")
return False
def connectToDB():
#load global variables
global clientSet
global dbClient
#connect to database
dbClient = InfluxDBClient(host=cfg['db']['host'], port=cfg['db']['port'], username=cfg['db']['username'], password=cfg['db']['password'])
#save connection state
clientSet = True
#create / switch to database
dbClient.create_database(cfg['db']['database'])
dbClient.switch_database(cfg['db']['database'])
#unused
def createDB(database):
dbClient.create_database(database)
def insertData(data, stat=None):
#init json data as string
json_data=''
#get timestamp
timestamp = datetime.datetime.now()
#build json structure for single stat
if stat!=None:
json_data+= '[{'
json_data+=f' "measurement": "{stat}",'
json_data+= ' "tags": {'
json_data+=f' "host": "{hostname}"'
json_data+= ' },'
json_data+=f' "time": "{timestamp}",'
json_data+= ' "fields": {'
json_data+=f' "value": "{data[stat]}",'
json_data+=f' "state": "ALARM"'
json_data+= ' }'
json_data+= '}'
json_data+= ']'
else:
#get last stat in dict
keys = []
for key in data:
keys += [key]
#build json array for multiple stats
json_data='['
for i in data:
json_data+= '{'
json_data+=f' "measurement": "{i}",'
json_data+= ' "tags": {'
json_data+=f' "host": "{hostname}",'
json_data+=f' "state": "INFO"'
json_data+= ' },'
json_data+=f' "time": "{timestamp}",'
json_data+= ' "fields": {'
json_data+=f' "value": "{data[i]}",'
json_data+=f' "state": "INFO"'
json_data+= ' }'
if i == keys[-1]:
json_data+= '}'
else:
json_data+= '},'
json_data+=']'
#convert to json object
json_data = json.loads(json_data)
print(json_data)
#check if connected to database / connect to database
if clientSet == True:
dbClient.write_points(json_data)
else:
connectToDB()
dbClient.write_points(json_data)