-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.js
559 lines (473 loc) · 19.1 KB
/
main.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
const zestClient = require('./lib/zest.js')
const arbiterClient = require('./lib/arbiter-client.js')
const config = require('./lib/config.js')
const url = require('url')
const EventEmitter = require('events')
const fs = require('fs')
const rp = require('request-promise-native')
// StoreClient returns a new client to read and write data to stores
// storeEndpoint is provided in the DATABOX_ZMQ_ENDPOINT environment variable
// and arbiterEndpoint is provided by the DATABOX_ARBITER_ENDPOINT environment variable
// to databox apps and drivers.
exports.NewStoreClient = function (storeEndpoint, arbiterEndpoint, enableLogging) {
let zestEndpoint = storeEndpoint
let zestDealerEndpoint = storeEndpoint.replace(':5555', ':5556')
let zestCli = zestClient(zestEndpoint, zestDealerEndpoint, config.CORE_STORE_KEY, enableLogging)
let arbiterCli = arbiterClient(arbiterEndpoint, enableLogging)
let client = {
config: config,
zestEndpoint: zestEndpoint,
zestDealerEndpoint: zestDealerEndpoint,
zestCli: zestCli,
arbiterCli: arbiterCli,
RegisterDatasource: async function (DataSourceMetadata) {
return _registerDatasource(arbiterCli, zestCli, DataSourceMetadata)
},
GetDatasourceCatalogue: async function () {
return _read(arbiterCli, zestCli, '/cat', '/cat', 'JSON')
},
//KeyValueClient used to read and write of data key value to the store
KV: {
Read: async function (dataSourceID, key, contentFormat = 'JSON') {
let path = `/kv/${dataSourceID}/${key}`
return _read(arbiterCli, zestCli, path, path, contentFormat)
},
Write: async function (dataSourceID, key, payload, contentFormat = 'JSON') {
let path = `/kv/${dataSourceID}/${key}`
return _write(arbiterCli, zestCli, path, path, payload, contentFormat)
},
ListKeys: async function (dataSourceID) {
let path = `/kv/${dataSourceID}/keys`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Observe: async function (dataSourceID, timeOut = 0, contentFormat = 'JSON') {
let path = `/kv/${dataSourceID}/*`
return _observe(arbiterCli, zestCli, path, timeOut, contentFormat)
},
ObserveKey: async function (dataSourceID, key, timeOut = 0, contentFormat = 'JSON') {
let path = `/kv/${dataSourceID}/${key}`
return _observe(arbiterCli, zestCli, path, timeOut, contentFormat)
},
StopObserving: async function (dataSourceID, key) {
if (typeof key == 'undefined') {
key = '*'
}
let path = `/kv/${dataSourceID}/${key}`
await zestCli.StopObserving(path)
}
},
TSBlob: {
Write: async function (dataSourceID, payload) {
let path = `/ts/blob/${dataSourceID}`
return _write(arbiterCli, zestCli, path, path, payload, 'JSON')
},
WriteAt: async function (dataSourceID, timestamp, payload) {
let path = `/ts/blob/${dataSourceID}/at/${timestamp}`
let tokenPath = `/ts/blob/${dataSourceID}/at/*`
return _write(arbiterCli, zestCli, path, tokenPath, payload, 'JSON')
},
Latest: async function (dataSourceID) {
let path = `/ts/blob/${dataSourceID}/latest`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Earliest: async function (dataSourceID) {
let path = `/ts/blob/${dataSourceID}/earliest`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
LastN: async function (dataSourceID, n) {
let path = `/ts/blob/${dataSourceID}/last/${n}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
FirstN: async function (dataSourceID, n) {
let path = `/ts/blob/${dataSourceID}/first/${n}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Since: async function (dataSourceID, sinceTimeStamp) {
let path = `/ts/blob/${dataSourceID}/since/${sinceTimeStamp}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Range: async function (dataSourceID, formTimeStamp, toTimeStamp) {
let path = `/ts/blob/${dataSourceID}/range/${formTimeStamp}/${toTimeStamp}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Length: async function (dataSourceID) {
let path = `/ts/blob/${dataSourceID}/length`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Observe: async function (dataSourceID, timeOut = 0) {
let path = `/ts/blob/${dataSourceID}`
return _observe(arbiterCli, zestCli, path, timeOut, 'JSON')
},
StopObserving: async function (dataSourceID) {
let path = `/ts/blob/${dataSourceID}`
await zestCli.StopObserving(path)
}
},
TS: {
Write: async function (dataSourceID, payload) {
let path = '/ts/' + dataSourceID
return _write(arbiterCli, zestCli, path, path, payload, 'JSON')
},
WriteAt: async function (dataSourceID, timestamp, payload) {
let path = `/ts/${dataSourceID}/at/` + timestamp
let tokenPath = `/ts/${dataSourceID}/at/*`
return _write(arbiterCli, zestCli, path, tokenPath, payload, 'JSON')
},
Latest: async function (dataSourceID) {
let path = `/ts/${dataSourceID}/latest`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Earliest: async function (dataSourceID) {
let path = `/ts/${dataSourceID}/earliest`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
LastN: async function (dataSourceID, n, aggregation = '', filterTagName = '', filterType = '', filterValue = '') {
let path = `/ts/${dataSourceID}/last/${n}${calculatePath(aggregation, filterTagName, filterType, filterValue)}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
FirstN: async function (dataSourceID, n, aggregation = '', filterTagName = '', filterType = '', filterValue = '') {
let path = `/ts/${dataSourceID}/first/${n}${calculatePath(aggregation, filterTagName, filterType, filterValue)}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Since: async function (dataSourceID, sinceTimeStamp, aggregation = '', filterTagName = '', filterType = '', filterValue = '') {
let path = `/ts/${dataSourceID}/since/${sinceTimeStamp}${calculatePath(aggregation, filterTagName, filterType, filterValue)}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Range: async function (dataSourceID, formTimeStamp, toTimeStamp, aggregation = '', filterTagName = '', filterType = '', filterValue = '') {
let path = `/ts/${dataSourceID}/range/${formTimeStamp}/${toTimeStamp}${calculatePath(aggregation, filterTagName, filterType, filterValue)}`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Length: async function (dataSourceID) {
let path = `/ts/${dataSourceID}/length`
return _read(arbiterCli, zestCli, path, path, 'JSON')
},
Observe: async function (dataSourceID, timeOut = 0) {
let path = `/ts/${dataSourceID}`
return _observe(arbiterCli, zestCli, path, timeOut, 'JSON')
},
StopObserving: async function (dataSourceID) {
let path = `/ts/${dataSourceID}`
await zestCli.StopObserving(path)
}
}
}
return client
}
let NewDataSourceMetadata = function () {
return {
Description: ' ',
ContentType: ' ',
Vendor: ' ',
DataSourceType: ' ',
DataSourceID: ' ',
StoreType: ' ',
IsActuator: false,
Unit: ' ',
Location: ' ',
}
}
exports.NewDataSourceMetadata = NewDataSourceMetadata
let DataSourceMetadataToHypercat = function (endpoint, metadata) {
ValidateDataSourceMetadata(metadata)
var cat = {
'item-metadata': [{
'rel': 'urn:X-hypercat:rels:hasDescription:en',
'val': metadata.Description
}, {
'rel': 'urn:X-hypercat:rels:isContentType',
'val': metadata.ContentType
}, {
'rel': 'urn:X-databox:rels:hasVendor',
'val': metadata.Vendor
}, {
'rel': 'urn:X-databox:rels:hasType',
'val': metadata.DataSourceType
}, {
'rel': 'urn:X-databox:rels:hasDatasourceid',
'val': metadata.DataSourceID
}, {
'rel': 'urn:X-databox:rels:hasStoreType',
'val': metadata.StoreType
}],
href: endpoint + metadata.DataSourceID
}
if (metadata.IsActuator)
cat['item-metadata'].push({
'rel': 'urn:X-databox:rels:isActuator',
'val': metadata.IsActuator
})
if (metadata.Unit)
cat['item-metadata'].push({
'rel': 'urn:X-databox:rels:hasUnit',
'val': metadata.Unit
})
if (metadata.Location)
cat['item-metadata'].push({
'rel': 'urn:X-databox:rels:hasLocation',
'val': metadata.Location
})
return cat
}
exports.DataSourceMetadataToHypercat = DataSourceMetadataToHypercat
let HypercatToDataSourceMetadata = function (hyperCat) {
let dm = NewDataSourceMetadata()
if (typeof (hyperCat) === 'string') {
hyperCat = JSON.parse(hyperCat)
}
hyperCat['item-metadata'].forEach(element => {
if (element['rel'] == 'urn:X-hypercat:rels:hasDescription:en')
dm.Description = element['val']
if (element['rel'] == 'urn:X-hypercat:rels:isContentType')
dm.ContentType = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasVendor')
dm.Vendor = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasType')
dm.DataSourceType = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasDatasourceid')
dm.DataSourceID = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasStoreType')
dm.StoreType = element['val']
if (element['rel'] == 'urn:X-databox:rels:isActuator')
dm.IsActuator = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasLocation')
dm.Location = element['val']
if (element['rel'] == 'urn:X-databox:rels:hasUnit')
dm.Unit = element['val']
})
return dm
}
exports.HypercatToDataSourceMetadata = HypercatToDataSourceMetadata
exports.GetStoreURLFromHypercat = function (hyperCat) {
if (typeof(hyperCat) === 'string') {
hyperCat = JSON.parse(hyperCat);
}
let u = url.parse(hyperCat.href)
return u.protocol + '//' + u.host
}
exports.GetHttpsCredentials = function () {
let credentials = {};
try {
//HTTPS certs created by the container mangers for this components HTTPS server.
credentials = {
key: fs.readFileSync('/run/secrets/DATABOX.pem'),
cert: fs.readFileSync('/run/secrets/DATABOX.pem')
};
} catch (e) {
console.warn('Warning: No HTTPS certificate not provided HTTPS certificates missing. Error', e);
credentials = {};
}
return credentials
}
let _write = async function (arbiterClient, zestClient, path, tokenPath, payload, contentFormat) {
validateContentFormat(contentFormat)
if (payload !== null && typeof payload === 'object' && contentFormat == 'JSON') {
//convert to JSON string if we have an object
try {
payload = JSON.stringify(payload)
} catch (error) {
throw `Write Error: invalid json payload, ${error}`
}
}
try {
let endPoint = url.parse(zestClient.zestEndpoint)
let token = await arbiterClient.requestToken(endPoint.hostname, tokenPath, 'POST')
let response = await zestClient.Post(token, path, payload, contentFormat)
//TODO this is here to maintain backwards compatibility after moving to zest should be removed in future
if (response == '') {
response = 'created'
}
return response
} catch (error) {
throw (`Write Error: for path ${path}, ${error}`)
}
}
let _read = async function (arbiterClient, zestClient, path, tokenPath, contentFormat) {
validateContentFormat(contentFormat)
try {
let endPoint = url.parse(zestClient.zestEndpoint)
let token = await arbiterClient.requestToken(endPoint.hostname, tokenPath, 'GET')
let response = await zestClient.Get(token, path, contentFormat)
if (response !== null && contentFormat == 'JSON') {
//convert to JSON if we have an object
response = JSON.parse(response)
}
return response
} catch (error) {
throw (`Read Error: for path ${path}, ${error}`)
}
}
let validateContentFormat = function (format) {
switch (format.toUpperCase()) {
case 'TEXT':
return true
case 'BINARY':
return true
case 'JSON':
return true
}
throw ('Error: Unsupported content format')
}
let _observe = async function (arbiterClient, zestClient, path, timeOut = 60, contentFormat = 'JSON') {
contentFormat = contentFormat.toLocaleUpperCase()
validateContentFormat(contentFormat)
try {
let endPoint = url.parse(zestClient.zestEndpoint)
let token = await arbiterClient.requestToken(endPoint.hostname, path, 'GET')
let observeEmitter = await zestClient.Observe(token, path, contentFormat, timeOut)
let _emitter = new EventEmitter()
observeEmitter.on('data', (data) => {
let obj = processObserveString(data)
if (obj === null) {
_emitter.emit('error', 'Malformed data received:: ' + data)
} else {
if (contentFormat === 'JSON') {
obj.data = JSON.parse(obj.data)
}
_emitter.emit('data', obj)
}
})
observeEmitter.on('error', (err) => {
_emitter.emit('error', err)
})
return _emitter
} catch (error) {
throw (`Observe Error: for path ${path}, ${error}`)
}
}
processObserveString = function (observeString) {
try {
let parts = observeString.split(' ')
let _ts = parseInt(parts[0])
let parts2 = parts[1].split(' ')
let _dataSourceID = parts2[2]
let _key = ''
if (parts2.Length > 3) {
_key = string(parts2[3])
}
parts.splice(0, 3)
let _data = parts.join(' ')
let JsonObserveResponse = {}
if (_key !== '') {
JsonObserveResponse = {
'datasourceid': _dataSourceID,
'key': _key,
'data': _data,
}
} else {
JsonObserveResponse = {
'timestamp': _ts,
'datasourceid': _dataSourceID,
'data': _data,
}
}
return JsonObserveResponse
} catch (e) {
return null
}
}
let _registerDatasource = async function (arbiterClient, zestClient, DataSourceMetadata) {
ValidateDataSourceMetadata(DataSourceMetadata)
try {
let hyperCatObj = await DataSourceMetadataToHypercat(zestClient.zestEndpoint + '/' + DataSourceMetadata.StoreType + '/', DataSourceMetadata)
let hyperCatString = JSON.stringify(hyperCatObj)
return _write(arbiterClient, zestClient, '/cat', '/cat', hyperCatString, 'JSON')
} catch (error) {
throw (`RegisterDatasource Error:: ${error}`)
}
}
let checkStoreType = function (storeType) {
switch (storeType) {
case 'kv':
return true
case 'ts':
return true
case 'ts/blob':
return true
}
throw ('Error:: DataSourceMetadata invalid StoreType can be kv,ts or ts/blob')
}
let ValidateDataSourceMetadata = function (DataSourceMetadata) {
if (!DataSourceMetadata
|| typeof (DataSourceMetadata) !== 'object'
|| !DataSourceMetadata.Description
|| !DataSourceMetadata.ContentType
|| !DataSourceMetadata.Vendor
|| !DataSourceMetadata.DataSourceType
|| !DataSourceMetadata.DataSourceID
|| !DataSourceMetadata.StoreType
) {
throw ('Error:: Not a valid DataSourceMetadata object missing required property')
}
checkStoreType(DataSourceMetadata.StoreType)
return true
}
let calculatePath = function (aggregation, tagName, filterType, value) {
let aggregationPath = ''
if (aggregation !== '') {
aggregationPath = '/' + aggregation
}
if (tagName === '' || filterType === '' || value === '') {
return aggregationPath
}
return '/filter/' + tagName + '/' + filterType + '/' + value + aggregationPath
}
// ExportClient returns a new export-service client.
// arbiterEndpoint is provided by the DATABOX_ARBITER_ENDPOINT environment
// variable to databox apps and drivers.
exports.NewExportClient = function (arbiterEndpoint, enableLogging) {
let arbiterCli = arbiterClient(arbiterEndpoint, enableLogging)
let client = {
config: config,
arbiterCli: arbiterCli,
enableLogging: enableLogging,
Longpoll: async function (destination, payload, id) {
let path = '/lp/export'
return _export( arbiterCli, path, destination, payload, id, enableLogging )
}
}
return client
}
const exportServiceURL = "https://export-service:8080"
let _export = async function ( arbiterClient, path, destination, payload, id, enableLogging ) {
if(payload !== null && typeof payload === 'object') {
try {
payload = JSON.stringify(payload);
} catch (error) {
throw `Export Error: invalid payload, ${error}`
}
}
try {
let endPoint = url.parse( exportServiceURL )
let token = await arbiterClient.requestToken(endPoint.hostname, path, 'POST',
// caveat (export-service specific)
{ "destination": destination }
)
if (enableLogging) {
console.log(`Export token for host ${endPoint.hostname} path ${path} POST destination ${destination}: ${token}`)
}
if (typeof (id) !== 'string') {
id = ''
}
if (enableLogging) {
console.log(`Export id ${id}`)
}
let options = {
method: 'POST',
json: {
id: id,
uri: destination,
data: payload
},
url: exportServiceURL + path,
agent: config.httpsAgent,
headers: {
'X-Api-Key': token,
'Content-Type' : "application/json"
}
}
let body = await rp( options )
return body
} catch (error ) {
throw (`Export Error: for path ${path} destination ${destination}, ${error}`)
}
}