iobroker.influxdb 2.1.1 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +106 -57
  3. package/admin/i18n/de/translations.json +8 -2
  4. package/admin/i18n/en/translations.json +7 -1
  5. package/admin/i18n/es/translations.json +7 -1
  6. package/admin/i18n/fr/translations.json +7 -1
  7. package/admin/i18n/it/translations.json +7 -1
  8. package/admin/i18n/nl/translations.json +7 -1
  9. package/admin/i18n/pl/translations.json +7 -1
  10. package/admin/i18n/pt/translations.json +9 -3
  11. package/admin/i18n/ru/translations.json +7 -1
  12. package/admin/i18n/zh-cn/translations.json +7 -1
  13. package/admin/influxdb.png +0 -0
  14. package/admin/jsonConfig.json +36 -5
  15. package/admin/jsonCustom.json +43 -6
  16. package/admin/words.js +17 -11
  17. package/docs/de/img/influxdb_Filtern_loggen.jpg +0 -0
  18. package/docs/de/img/influxdb_ioBroker_Adapter_SQL_objects_Data.jpg +0 -0
  19. package/docs/de/img/influxdb_ioBroker_Adapter_SQL_objects_filter.jpg +0 -0
  20. package/docs/de/img/influxdb_ioBroker_Adapter_SQL_objects_timerange.jpg +0 -0
  21. package/docs/de/img/influxdb_ioBroker_Adapter_SQL_objects_type.jpg +0 -0
  22. package/docs/de/img/influxdb_ioBroker_Adapter_influxDB_Konfig.jpg +0 -0
  23. package/docs/de/img/influxdb_ioBroker_Adapter_influxDB_objects.jpg +0 -0
  24. package/docs/de/img/influxdb_ioBroker_Adapter_rickshaw03.jpg +0 -0
  25. package/docs/de/img/influxdb_ioBroker_adapter_History_devices.jpg +0 -0
  26. package/docs/de/influxdb.md +101 -0
  27. package/io-package.json +220 -364
  28. package/lib/Database.js +6 -5
  29. package/lib/DatabaseInfluxDB1x.js +18 -17
  30. package/lib/DatabaseInfluxDB2x.js +108 -71
  31. package/lib/aggregate.js +141 -37
  32. package/main.js +712 -364
  33. package/package.json +22 -8
  34. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -32
  35. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  36. package/.github/auto-merge.yml +0 -17
  37. package/.github/dependabot.yml +0 -16
  38. package/.github/stale.yml +0 -78
  39. package/.github/workflows/dependabot-automerge.yml +0 -22
  40. package/.github/workflows/test-and-release.yml +0 -221
package/lib/Database.js CHANGED
@@ -10,19 +10,20 @@ class Database {
10
10
  writeSeries(series, callback_error) {}
11
11
  writePoints(seriesId, pointsToSend, callback_error) {}
12
12
  writePoint(seriesName, values, options, callback_error) {}
13
-
13
+
14
14
  query(query, callback) {}
15
15
 
16
16
  calculateShardGroupDuration(retentionTime) { // in seconds
17
17
  // Shard Group Duration according to official Influx recommendations
18
- if (retentionTime == 0 ) //infinite
18
+ if (!retentionTime) {//infinite
19
19
  return 604800; // 7 days
20
- else if (retentionTime < 172800) // < 2 days
20
+ } else if (retentionTime < 172800) {// < 2 days
21
21
  return 3600; // 1 hour
22
- else if ((retentionTime >= 172800) && (retentionTime <= 7862400)) // >= 2 days, <= 6 months (~182 days)
22
+ } else if (retentionTime >= 172800 && retentionTime <= 7862400) {// >= 2 days, <= 6 months (~182 days)
23
23
  return 86400; // 1 day
24
- else // > 6 months
24
+ } else {// > 6 months
25
25
  return 604800; // 7 days
26
+ }
26
27
  }
27
28
  }
28
29
 
@@ -25,6 +25,8 @@ class DatabaseInfluxDB1x extends Database{
25
25
  }
26
26
 
27
27
  connect () {
28
+ this.log.debug(`Connect InfluxDB1: ${this.protocol}://${this.host}:${this.port} [${this.database}]`);
29
+
28
30
  this.connection = influx({
29
31
  host: this.host,
30
32
  port: this.port, // optional, default 8086
@@ -46,7 +48,7 @@ class DatabaseInfluxDB1x extends Database{
46
48
  getRetentionPolicyForDB(dbname, callback) {
47
49
  this.connection.query('SHOW RETENTION POLICIES ON ' + dbname, (err, rows) => {
48
50
  if(err){
49
- this.log.error("Error retrieving retention policy: " + err);
51
+ this.log.error(`Error retrieving retention policy: ${err}`);
50
52
  callback(err, null);
51
53
  } else {
52
54
  const regex = /(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/;
@@ -61,36 +63,35 @@ class DatabaseInfluxDB1x extends Database{
61
63
  retentionName = row.name;
62
64
  }
63
65
  });
64
- callback(null, {"name": retentionName, "time": retentionTime});
66
+ callback(null, {name: retentionName, time: retentionTime});
65
67
  }
66
68
  });
67
69
  }
68
70
 
69
71
  async applyRetentionPolicyToDB(dbname, retention, callback) {
70
72
  this.getRetentionPolicyForDB(dbname, (err, oldRetention) => {
71
- //Check, if there was an error
73
+ // Check, if there was an error
72
74
  if (err) {
73
- callback(err);
74
- return;
75
+ return callback(err);
75
76
  }
76
77
 
77
78
  //Check, if it needs to be changed, otherwise skip
78
- this.log.debug("old retention: " + oldRetention + " new retention: " + retention);
79
- if ((oldRetention.time !== null) && (oldRetention.time === retention)) {
80
- this.log.debug("Retention policy for " + dbname + " remains unchanged.");
81
- callback(false);
82
- return;
79
+ this.log.debug(`old retention: ${JSON.stringify(oldRetention)} new retention: ${retention}`);
80
+
81
+ if (oldRetention.time !== null && oldRetention.time === parseInt(retention, 10)) {
82
+ this.log.debug(`Retention policy for ${dbname} remains unchanged.`);
83
+ return callback(false);
83
84
  }
84
85
 
85
86
  const shardDuration = this.calculateShardGroupDuration(retention);
86
87
 
87
- //Get name of currently active default policy first, to update only it.
88
+ // Get name of currently active default policy first, to update only it.
88
89
 
89
- const command = (oldRetention.time != null) ? "ALTER" : "CREATE";
90
- const retentionName = (oldRetention.name != null) ? oldRetention.name : "global";
90
+ const command = oldRetention.time ? 'ALTER' : 'CREATE';
91
+ const retentionName = oldRetention.name ? oldRetention.name : 'global';
91
92
 
92
- this.log.info("Applying retention policy (" + retentionName + ") for " + dbname + " to " + ((retention === 0) ? "infinity" : retention + " seconds") + ". Shard Duration: " + shardDuration + " seconds");
93
- this.connection.query(command + ' RETENTION POLICY "' + retentionName + '" ON ' + dbname + ' DURATION ' + retention + 's REPLICATION 1 SHARD DURATION ' + shardDuration + 's DEFAULT', callback);
93
+ this.log.info(`Applying retention policy (${retentionName}) for ${dbname} to ${retention === 0 ? 'infinity' : retention + ' seconds'}. Shard Duration: ${shardDuration} seconds`);
94
+ this.connection.query(`${command} RETENTION POLICY "${retentionName}" ON ${dbname} DURATION ${retention}s REPLICATION 1 SHARD DURATION ${shardDuration}s DEFAULT`, callback);
94
95
  });
95
96
  }
96
97
 
@@ -115,7 +116,7 @@ class DatabaseInfluxDB1x extends Database{
115
116
  }
116
117
 
117
118
  query(query, callback) {
118
- this.log.debug("Query to execute: " + query);
119
+ this.log.debug(`Query to execute: ${query}`);
119
120
  this.connection.query(query, callback);
120
121
  }
121
122
 
@@ -127,4 +128,4 @@ class DatabaseInfluxDB1x extends Database{
127
128
 
128
129
  module.exports = {
129
130
  DatabaseInfluxDB1x : DatabaseInfluxDB1x
130
- }
131
+ };
@@ -2,7 +2,7 @@
2
2
 
3
3
  const Database = require('./Database.js');
4
4
  const InfluxClient = require('@influxdata/influxdb-client');
5
- const InfluxClientApis = require('@influxdata/influxdb-client-apis');
5
+ const InfluxClientApis = require('@influxdata/influxdb-client-apis');
6
6
 
7
7
  /* Old node-influx lib had some connection-pool handling that is not present in new influx lib,
8
8
  so to not break old code we use a fictional pool here. */
@@ -11,18 +11,18 @@ class FakeConnectionPool {
11
11
  this.connections = [];
12
12
  }
13
13
 
14
- activatePool() {
15
- this.connections.push("fakehost");
14
+ activatePool () {
15
+ this.connections.push('fakehost');
16
16
  }
17
17
 
18
- getHostsAvailable() {
18
+ getHostsAvailable () {
19
19
  return this.connections;
20
20
  }
21
21
  }
22
22
 
23
23
  //Influx 2.x auth requires token, not user/pw
24
- class DatabaseInfluxDB2x extends Database{
25
- constructor (log, host, port, protocol, token, organization, database, timePrecision, requestTimeout) {
24
+ class DatabaseInfluxDB2x extends Database {
25
+ constructor(log, host, port, protocol, token, organization, database, useTags, timePrecision, requestTimeout) {
26
26
  super();
27
27
 
28
28
  this.log = log;
@@ -35,18 +35,21 @@ class DatabaseInfluxDB2x extends Database{
35
35
  this.database = database;
36
36
  this.timePrecision = timePrecision; // ms
37
37
  this.requestTimeout = requestTimeout; // 30000
38
+ this.useTags = useTags || false;
38
39
 
39
40
  this.request = new FakeConnectionPool();
40
41
 
41
42
  this.connect();
42
43
  }
43
44
 
44
- connect () {
45
- const url = this.protocol + '://' + this.host + ':' + this.port + '/';
45
+ connect() {
46
+ const url = `${this.protocol}://${this.host}:${this.port}/`;
47
+
48
+ this.log.debug(`Connect InfluxDB1: ${url} [${this.database}]`);
46
49
 
47
50
  this.connection = new InfluxClient.InfluxDB({
48
- url: url,
49
- token: this.token,
51
+ url,
52
+ token: this.token,
50
53
  });
51
54
 
52
55
  this.queryApi = this.connection.getQueryApi(this.organization);
@@ -62,19 +65,19 @@ class DatabaseInfluxDB2x extends Database{
62
65
  this.request.activatePool();
63
66
  }
64
67
 
65
- async getDatabaseNames (callback) {
66
- this.log.debug("Organization being checked: " + this.organization);
68
+ async getDatabaseNames(callback) {
69
+ this.log.debug(`Organization being checked: ${this.organization}`);
67
70
 
68
71
  try {
69
- const organizations = await this.orgsApi.getOrgs({org: this.organization});
70
- this.log.debug("Organizations: " + JSON.stringify(organizations));
72
+ const organizations = await this.orgsApi.getOrgs({ org: this.organization });
73
+ this.log.debug(`Organizations: ${JSON.stringify(organizations)}`);
71
74
  if (organizations && organizations.orgs && !organizations.orgs.length) {
72
75
  throw new Error('No organizations exists or the token do not have proper permissions. Please check the token!')
73
76
  }
74
77
  this.organizationId = organizations.orgs[0].id;
75
78
 
76
- const buckets = await this.bucketsApi.getBuckets({orgID: this.organizationId});
77
- this.log.debug("Buckets: " + JSON.stringify(buckets));
79
+ const buckets = await this.bucketsApi.getBuckets({ orgID: this.organizationId });
80
+ this.log.debug(`Buckets: ${JSON.stringify(buckets)}`);
78
81
 
79
82
  const foundDatabases = [];
80
83
 
@@ -90,11 +93,11 @@ class DatabaseInfluxDB2x extends Database{
90
93
  }
91
94
 
92
95
  async getRetentionPolicyForDB(dbname, callback) {
93
- this.log.debug("Getting retention policy for " + dbname);
96
+ this.log.debug(`Getting retention policy for ${dbname}`);
94
97
  try {
95
- const bucketData = await this.bucketsApi.getBucketsID({bucketID: this.bucketIds[dbname]});
96
- this.log.debug("Found retention policy: " + bucketData.retentionRules[0].everySeconds + " seconds ");
97
- callback({"time": bucketData.retentionRules[0].everySeconds});
98
+ const bucketData = await this.bucketsApi.getBucketsID({ bucketID: this.bucketIds[dbname] });
99
+ this.log.debug(`Found retention policy: ${bucketData.retentionRules[0].everySeconds} seconds`);
100
+ callback({time: bucketData.retentionRules[0].everySeconds });
98
101
  } catch (error) {
99
102
  this.log.error(error);
100
103
  callback(null);
@@ -103,7 +106,7 @@ class DatabaseInfluxDB2x extends Database{
103
106
 
104
107
  async applyRetentionPolicyToDB(dbname, retention, callback_error) {
105
108
  const shardGroupDuration = this.calculateShardGroupDuration(retention);
106
- this.log.info("Applying retention policy for " + dbname + " to " + ((retention === 0) ? "infinity" : retention + " seconds") + ". Shard Group Duration (calculated): " + shardGroupDuration + " seconds");
109
+ this.log.info(`Applying retention policy for ${dbname} to ${!retention ? "infinity" : retention + " seconds"}. Shard Group Duration (calculated): ${shardGroupDuration} seconds`);
107
110
  try {
108
111
  await this.bucketsApi.patchBucketsID({
109
112
  bucketID: this.bucketIds[dbname],
@@ -124,11 +127,13 @@ class DatabaseInfluxDB2x extends Database{
124
127
 
125
128
  async createDatabase(dbname, callback_error) {
126
129
  try {
127
- this.log.info("Creating database " + dbname + " for orgId " + this.organizationId);
128
- const newBucket = await this.bucketsApi.postBuckets({ body: {
129
- orgID: this.organizationId,
130
- name: dbname
131
- }});
130
+ this.log.info(`Creating database ${dbname} for orgId ${this.organizationId}`);
131
+ const newBucket = await this.bucketsApi.postBuckets({
132
+ body: {
133
+ orgID: this.organizationId,
134
+ name: dbname
135
+ }
136
+ });
132
137
 
133
138
  this.bucketIds[dbname] = newBucket.id;
134
139
  callback_error(false);
@@ -140,8 +145,8 @@ class DatabaseInfluxDB2x extends Database{
140
145
 
141
146
  async dropDatabase(dbname, callback_error) {
142
147
  try {
143
- this.log.info("Dropping database " + dbname + " for orgId " + this.organizationId);
144
- await this.bucketsApi.deleteBucketsID({ bucketID: this.bucketIds[dbname] });
148
+ this.log.info(`Dropping database ${dbname} for orgId ${this.organizationId}`);
149
+ await this.bucketsApi.deleteBucketsID({ bucketID: this.bucketIds[dbname] });
145
150
 
146
151
  callback_error(false);
147
152
  } catch (error) {
@@ -151,7 +156,7 @@ class DatabaseInfluxDB2x extends Database{
151
156
  }
152
157
 
153
158
  async writeSeries(series, callback_error) {
154
- this.log.debug("Write series: " + JSON.stringify(series));
159
+ this.log.debug(`Write series: ${JSON.stringify(series)}`);
155
160
 
156
161
  const points = [];
157
162
  for (const [pointId, valueSets] of Object.entries(series)) {
@@ -165,7 +170,7 @@ class DatabaseInfluxDB2x extends Database{
165
170
  try {
166
171
  this.writeApi.writePoints(points);
167
172
  await this.writeApi.flush();
168
- this.log.debug("Points written to " + this.database);
173
+ this.log.debug(`Points written to ${this.database}`);
169
174
  callback_error();
170
175
  } catch (error) {
171
176
  callback_error(error);
@@ -173,7 +178,7 @@ class DatabaseInfluxDB2x extends Database{
173
178
  }
174
179
 
175
180
  async writePoints(pointId, pointsToSend, callback_error) {
176
- this.log.debug("Write Points: "+pointId+" pointstoSend:"+JSON.stringify(pointsToSend));
181
+ this.log.debug(`Write Points: ${pointId} pointstoSend:${JSON.stringify(pointsToSend)}`);
177
182
 
178
183
  const points = [];
179
184
  pointsToSend.forEach((values) => {
@@ -185,7 +190,7 @@ class DatabaseInfluxDB2x extends Database{
185
190
  try {
186
191
  this.writeApi.writePoints(points);
187
192
  await this.writeApi.flush();
188
- this.log.debug("Points written to " + this.database);
193
+ this.log.debug(`Points written to ${this.database}`);
189
194
  callback_error();
190
195
  } catch (error) {
191
196
  callback_error(error);
@@ -193,54 +198,64 @@ class DatabaseInfluxDB2x extends Database{
193
198
  }
194
199
 
195
200
  async writePoint(pointId, values, options, callback_error) {
196
- this.log.debug("Write Point: "+pointId+" values:"+ JSON.stringify(values) + " options: " + JSON.stringify(options));
201
+ this.log.debug(`Write Point: ${pointId} values:${JSON.stringify(values)} options: ${JSON.stringify(options)}`);
197
202
 
198
203
  try {
199
204
  this.writeApi.writePoint(this.stateValueToPoint(pointId, values));
200
205
  await this.writeApi.flush();
201
- this.log.debug("Point written to " + this.database);
206
+ this.log.debug(`Point written to ${this.database}`);
202
207
  callback_error();
203
208
  } catch (error) {
204
- this.log.warn("Point could not be written to database: " + this.database);
209
+ this.log.warn(`Point could not be written to database: ${this.database}`);
205
210
  callback_error(error);
206
211
  }
207
212
 
208
213
  }
209
214
 
210
- stateValueToPoint(pointName, stateValue){
211
- const point = new InfluxClient.Point(pointName)
212
- .timestamp(stateValue.time)
213
- .floatField("q", stateValue.q)
214
- .booleanField("ack", stateValue.ack)
215
- .stringField("from", stateValue.from);
215
+ stateValueToPoint(pointName, stateValue) {
216
+ let point = null;
217
+
218
+ if (this.useTags) {
219
+ point = new InfluxClient.Point(pointName)
220
+ .timestamp(stateValue.time)
221
+ .tag('q', String(stateValue.q))
222
+ .tag('ack', String(stateValue.ack))
223
+ .tag('from', stateValue.from);
224
+ } else {
225
+ point = new InfluxClient.Point(pointName)
226
+ .timestamp(stateValue.time)
227
+ .floatField('q', stateValue.q)
228
+ .booleanField('ack', stateValue.ack)
229
+ .stringField('from', stateValue.from);
230
+ }
216
231
 
217
- switch(typeof stateValue.value){
218
- case "boolean":
219
- point.booleanField("value", stateValue.value);
232
+ switch (typeof stateValue.value) {
233
+ case 'boolean':
234
+ point.booleanField('value', stateValue.value);
220
235
  break;
221
- case "number":
222
- point.floatField("value", parseFloat(stateValue.value));
236
+ case 'number':
237
+ point.floatField('value', parseFloat(stateValue.value));
223
238
  break;
224
- case "string":
239
+ case 'string':
225
240
  default:
226
- point.stringField("value", stateValue.value);
241
+ point.stringField('value', stateValue.value);
227
242
  break;
228
243
  }
229
-
230
244
  return point;
231
245
  }
232
246
 
233
247
  query(query, callback) {
234
- this.log.debug("Query to execute: " + query);
248
+ this.log.debug(`Query to execute: ${query}`);
235
249
  let rows = [];
236
250
 
237
251
  this.queryApi.queryRows(query, {
238
- next(row , tableMeta) {
252
+ next (row, tableMeta) {
239
253
  const fields = tableMeta.toObject(row);
240
254
 
241
255
  //Columns "_time" and "_value" are mapped to "time" and "value" for backwards compatibility
242
- if (fields["_time"] !== null)
243
- fields["time"] = fields["_time"];
256
+ if (fields['_time'] !== null)
257
+ fields['time'] = fields['_time'];
258
+
244
259
  //if (fields["_value"] !== null)
245
260
  // fields["value"] = fields["_value"];
246
261
 
@@ -248,27 +263,56 @@ class DatabaseInfluxDB2x extends Database{
248
263
 
249
264
  // console.log(JSON.stringify(o, null, 2))
250
265
  },
251
- error(error) {
252
- //Ignore errors that are related to an empty range. The handling of this currently seems inconsitent for flux.
266
+ error (error) {
267
+ //Ignore errors that are related to an empty range. The handling of this currently seems inconsistent for flux.
253
268
  //See also https://github.com/influxdata/flux/issues/3543
254
- if (error.message.match(".*cannot query an empty range.*"))
269
+ if (error.message.match('.*cannot query an empty range.*'))
255
270
  callback(null, rows);
256
271
  else
257
272
  callback(error, null);
258
273
  },
259
- complete() {
274
+ complete () {
260
275
  callback(null, rows);
261
276
 
262
277
  }
263
278
  });
264
279
  }
265
280
 
266
- async queries(queries, callback) {
281
+ getMetaDataStorageType (callback) {
282
+ const queries = [
283
+ `import "influxdata/influxdb/schema" schema.tagKeys(bucket: "${this.database}")`,
284
+ `import "influxdata/influxdb/schema" schema.fieldKeys(bucket: "${this.database}")`,
285
+ ];
286
+
287
+ this.queries(queries, (error, result) => {
288
+ let storageType = "none";
289
+ if (error) {
290
+ callback(error, null);
291
+ } else {
292
+ this.log.debug(`Result of metadata storage type check: ${JSON.stringify(result)}`);
293
+ for (let i = 0; i <= 1; i++) {
294
+ result[i].forEach(row => {
295
+ switch(row._value) {
296
+ case 'q':
297
+ case 'ack':
298
+ case 'from':
299
+ storageType = i == 0 ? 'tags' : 'fields';
300
+ return;
301
+ }
302
+ });
303
+ }
304
+ callback(null, storageType);
305
+ }
306
+
307
+ });
308
+ }
309
+
310
+ async queries (queries, callback) {
267
311
  const collectedRows = [];
268
312
  let success = false;
269
313
  let errors = [];
270
314
  for (const query of queries) {
271
- await new Promise ((resolve, reject) => {
315
+ await new Promise((resolve, reject) => {
272
316
  this.query(query, (error, rows) => {
273
317
  if (error) {
274
318
  this.log.warn(`Error in query "${query}": ${error}`);
@@ -282,6 +326,7 @@ class DatabaseInfluxDB2x extends Database{
282
326
  });
283
327
  });
284
328
  }
329
+
285
330
  let retError = null;
286
331
  if (errors.length) {
287
332
  retError = new Error(`${errors.length} Error happened while processing ${queries.length} queries`);
@@ -291,20 +336,12 @@ class DatabaseInfluxDB2x extends Database{
291
336
  }
292
337
 
293
338
  ping(interval) {
294
- //can't do much with interval, so ignoring it for compatibility reasons
295
- const promises = [];
296
- promises.push(new Promise ((resolve, reject) => {
297
- this.healthApi.getHealth().then(result => {
298
- resolve(result.status === 'pass' ? {online: true} : {online: false});
299
- })
300
- .catch (error => {
301
- reject(error);
302
- });
303
- }));
304
- return Promise.all(promises);
339
+ // can't do much with interval, so ignoring it for compatibility reasons
340
+ return this.healthApi.getHealth()
341
+ .then(result => result.status === 'pass' ? [{ online: true }] : [{ online: false }]);
305
342
  }
306
343
  }
307
344
 
308
345
  module.exports = {
309
- DatabaseInfluxDB2x : DatabaseInfluxDB2x
346
+ DatabaseInfluxDB2x: DatabaseInfluxDB2x
310
347
  }