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
import asyncdispatch, strutils, tables, httpclient, options, json, uri
import types, vars
proc existsDatabase* (config: InfluxConfig, databaseName: string): Future[bool] {.async.}=
try:
var client = newAsyncHttpClient()
if config.authToken.isSome:
client.headers["Authorization"] = "Token " & $config.authToken.get
let baseUrl = "http://" & config.host & ":" & $config.port & "/"
let response = await client.getContent(baseUrl & "query?" & encodeQuery({"db": databaseName, "q": "select * FROM test LIMIT 1"}))
let data = parseJson(response)
client.close()
if data["results"][0].hasKey("error"):
return false
return true
except:
echo "Error[existsDatabase]:\n", getCurrentExceptionMsg()
proc insertDatabase* (config: InfluxConfig, databaseName: string, tableName: string, tags: Table[string, string], fields: Table[string, string], timestamp: int64): Future[bool] {.async.} =
try:
var client = newAsyncHttpClient()
if config.authToken.isSome:
client.headers["Authorization"] = "Token " & $config.authToken.get
let baseUrl = "http://" & config.host & ":" & $config.port & "/"
var tagsCombined: seq[string]
var fieldsCombined: seq[string]
for key, value in pairs(tags):
tagsCombined.add(key & "=" & value)
for key, value in pairs(fields):
fieldsCombined.add(key & "=" & value)
let body = tableName & "," & tagsCombined.join(",") & " " & fieldsCombined.join(",") & " " & $timestamp
let response = await client.request(baseUrl & "write?db=" & databaseName, httpMethod = HttpPost, body = body)
client.close()
if response.code != Http204:
return false
return true
except:
echo "Error[insertDatabase]:\n", getCurrentExceptionMsg()
proc initInflux* () =
let config = server.config.serverConfig.influx.get
try:
if config.powermetersDatabase.isSome:
if not waitFor config.existsDatabase(config.powermetersDatabase.get):
echo "Specified Influxdatabase for powermeters does not exist!"
quit()
if config.sensorsDatabase.isSome:
if not waitFor config.existsDatabase(config.sensorsDatabase.get):
echo "Specified Influxdatabase for sensors does not exist!"
quit()
except:
echo "Error[initInflux]:\n", getCurrentExceptionMsg()
quit()