/
sthDatabase.js
1990 lines (1899 loc) · 65.5 KB
/
sthDatabase.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U
*
* This file is part of the Short Time Historic (STH) component
*
* STH is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* STH is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with STH.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with: [german.torodelvalle@telefonica.com]
*/
'use strict';
Object.assign = Object.assign || require('object-assign');
var ROOT_PATH = require('app-root-path').toString();
var sthLogger = require('logops');
var sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration.js');
var sthUtils = require(ROOT_PATH + '/lib/utils/sthUtils.js');
var sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming');
var mongoClient = require('mongodb').MongoClient;
var boom = require('boom');
var jsoncsv = require('json-csv');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var async = require('async');
var _ = require('lodash');
var db, connectionURL;
/**
* Returns the options to use for the CSV file generation
* @param attrName The attribute name
* @return {{fields: *[], fieldSeparator: string}} The options to use
*/
function getJSONCSVOptions(attrName) {
var jsonCSVOptions = {
fields: [
{
name: 'attrName',
label: 'attrName'
},
{
name: 'attrType',
label: 'attrType'
},
{
name: 'attrValue',
label: 'attrValue'
},
{
name: 'recvTime',
label: 'recvTime'
}
],
fieldSeparator: ','
};
jsonCSVOptions.fields[0].filter = function () {
return attrName;
};
return jsonCSVOptions;
}
/**
* Connects to a (MongoDB) database endpoint asynchronously
* @param {object} params It is an object including the following properties:
* - {string} authentication The authentication schema to use for the connection
* - {string} dbURI The database URI
* - {string} replicaSet The replica set name, if any
* - {string} database The name of the database to connect to
* - {Number} poolSize The size of the pool of connections to the database
* @param {Function} callback A callback to inform about the result of the operation
*/
function connect(params, callback) {
connectionURL = 'mongodb://' + params.authentication + '@' + params.dbURI + '/' + params.database +
(params.replicaSet ? '?replicaSet=' + params.replicaSet : '');
sthLogger.info(
sthConfig.LOGGING_CONTEXT.DB_CONN_OPEN,
'Establishing connection to the database at %s',
connectionURL
);
mongoClient.connect(connectionURL,
{
server: {
poolSize: params.poolSize
}
},
function (err, theDB) {
if (!err) {
sthLogger.info(
sthConfig.LOGGING_CONTEXT.DB_CONN_OPEN,
'Connection successfully established to the database at %s',
connectionURL
);
}
db = theDB;
return process.nextTick(callback.bind(null, err, theDB));
}
);
}
/**
* Closes a connection to the database asynchronously
* @param {Function} callback Callback function to notify the result
* of the operation
*/
function closeConnection(callback) {
sthLogger.info(
sthConfig.LOGGING_CONTEXT.DB_CONN_CLOSE,
'Closing the connection to the database...'
);
if (db) {
db.close(function (err) {
if (err) {
sthLogger.error(
sthConfig.LOGGING_CONTEXT.DB_CONN_CLOSE,
'Error when closing the connection to the database: ' + err);
} else {
sthLogger.info(
sthConfig.LOGGING_CONTEXT.DB_CONN_CLOSE,
'Connection to MongoDb succesfully closed');
db = null;
}
return process.nextTick(callback.bind(null, err));
});
} else {
sthLogger.info(
sthConfig.LOGGING_CONTEXT.DB_CONN_CLOSE,
'No connection to the database available');
return process.nextTick(callback);
}
}
/**
* Sets the unique index for the raw data collections
* @param {object} collection The raw data collection
*/
function setRawDataUniqueIndex(collection) {
var uniqueCompoundIndex;
switch(sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
uniqueCompoundIndex = {
'recvTime': 1,
'entityId': 1,
'entityType': 1,
'attrName': 1,
'attrType': 1,
'attrValue': 1
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
uniqueCompoundIndex = {
'recvTime': 1,
'attrName': 1,
'attrType': 1,
'attrValue': 1
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
uniqueCompoundIndex = {
'recvTime': 1,
'attrType': 1,
'attrValue': 1
};
break;
}
collection.ensureIndex(
uniqueCompoundIndex,
{ unique: true },
function (err) {
if (err) {
sthLogger.error(
sthConfig.LOGGING_CONTEXT.DB_LOG,
'Error when creating the unique compound index for collection \'' +
collection.s.name + '\': ' + err
);
}
}
);
}
/**
* Returns true is the collection name corresponds to an aggregated data collection. False otherwise.
* @param collectionName The collection name
* @return {boolean} True is the collection name corresponds to an aggregated data collection. False otherwise.
*/
function isAggregated(collectionName) {
if (collectionName.lastIndexOf('.aggr') === -1 ||
collectionName.lastIndexOf('.aggr') !== collectionName.length - '.aggr'.length) {
return false;
} else {
return true;
}
}
/**
* Sets the time to live policy on a collection
* @param {object} collection The collection
*/
function setTTLPolicy(collection) {
// Set the TTL policy if required
if (sthConfig.TRUNCATION_EXPIRE_AFTER_SECONDS > 0) {
if (!isAggregated(collection)) {
if (sthConfig.TRUNCATION_SIZE === 0) {
collection.ensureIndex(
{
'recvTime': 1
},
{
expireAfterSeconds: sthConfig.TRUNCATION_EXPIRE_AFTER_SECONDS
}, function (err) {
if (err) {
sthLogger.error(
sthConfig.LOGGING_CONTEXT.DB_LOG,
'Error when creating the index for TTL for collection \'' +
collection.s.name + '\': ' + err
);
}
}
);
}
} else {
collection.ensureIndex(
{
'_id.origin': 1
},
{
expireAfterSeconds: sthConfig.TRUNCATION_EXPIRE_AFTER_SECONDS
}, function (err) {
if (err) {
sthLogger.error(
sthConfig.LOGGING_CONTEXT.DB_LOG,
'Error when creating the index for TTL for collection \'' +
collection.s.name + '\': ' + err
);
}
}
);
}
}
}
/**
* Returns asynchronously a reference to a collection of the database
* @param {object} params Params object including the following properties:
* - service: The service
* - servicePath: The service path
* - entityId: The entity id
* - entityType: The entity type
* - attrName: The attribute name
* @param {object} options Options object including the following properties:
* - isAggregated: Flag indicating if the aggregated collection is desired
* - shouldCreate: Flag indicating if the collection should be created if it does not
* exist
* - shouldTruncate: Flag indicating if the collection should be trucate in time or size
* @param {Function} callback The callback
*/
function getCollection(params, options, callback) {
var isAggregated = options.isAggregated,
shouldCreate = options.shouldCreate,
shouldTruncate = options.shouldTruncate;
var databaseName = sthDatabaseNaming.getDatabaseName(params.service);
var collectionName;
if (params.collection) {
collectionName = params.collection;
} else {
collectionName = isAggregated ?
sthDatabaseNaming.getAggregatedCollectionName(
{
service: params.service,
servicePath: params.servicePath,
entityId: params.entityId,
entityType: params.entityType,
attrName: params.attrName
}
) :
sthDatabaseNaming.getRawCollectionName(
{
service: params.service,
servicePath: params.servicePath,
entityId: params.entityId,
entityType: params.entityType,
attrName: params.attrName
}
);
}
if (!collectionName) {
var error = boom.badRequest('The collection name could not be generated');
return process.nextTick(callback.bind(null, error));
}
// Switch to the right database
var connection = db.db(databaseName);
function createCollectionCB(err, collection) {
if (err) {
if (err.message === 'collection already exists') {
// We have observed that although leaving the strict option to the default value, sometimes
// we get a 'collection already exists' error when executing connection.db#createCollection()
connection.collection(collectionName, {strict: true},
function (err, collection) {
return callback(err, collection);
}
);
} else {
return callback(err, collection);
}
} else if (collection && !isAggregated) {
setRawDataUniqueIndex(collection);
if (shouldTruncate) {
setTTLPolicy(collection);
}
return callback(err, collection);
} else {
return callback(err, collection);
}
}
connection.collection(collectionName, {strict: true},
function (err, collection) {
if (err &&
(err.message === 'Collection ' + collectionName + ' does not exist. Currently in strict mode.') &&
shouldCreate) {
if (shouldTruncate && !isAggregated) {
// Set the size removal policy if required
if (sthConfig.TRUNCATION_SIZE > 0) {
var collectionCreationOptions = {
capped: true,
size: sthConfig.TRUNCATION_SIZE,
max: sthConfig.TRUNCATION_MAX || null
};
return connection.createCollection(collectionName,
collectionCreationOptions,
createCollectionCB
);
}
}
connection.createCollection(collectionName,
createCollectionCB
);
} else {
return callback(err, collection);
}
}
);
}
/**
* Saves the contents of a readable stream into a file in the local file system
* @param {string} attrName The name of the attribute the stream contents refers to
* @param {object} stream The stream
* @param {string} fileName The file name where the stream contents should be stored
* @param {function} callback THe callback
*/
function save2File(attrName, stream, fileName, callback) {
var tempDir = ROOT_PATH + path.sep + sthConfig.TEMPORAL_DIR;
if (!fs.existsSync(tempDir) ||
(fs.existsSync(tempDir) && !fs.statSync(tempDir).isDirectory())) {
mkdirp.sync(tempDir);
}
var outputFile = fs.createWriteStream(tempDir + path.sep + fileName, {encoding: 'utf8'});
stream.pipe(jsoncsv.csv(getJSONCSVOptions(attrName))).pipe(outputFile).on('finish', callback);
}
/**
* Generates a CSV file from a stream containing raw data associated to certain attribute
* @param {string} attrName The attribute name
* @param {object} stream The stream
* @param {function} callback The callback
*/
function generateCSV(attrName, stream, callback) {
var fileName = attrName + '-' + Date.now() + '.csv';
save2File(attrName, stream, fileName,
callback.bind(null, null,
ROOT_PATH + path.sep + sthConfig.TEMPORAL_DIR + path.sep + fileName));
}
/**
* Returns the required raw data from the database asynchronously
* @param {object} data The data for which return the raw data. It is an object including the following properties:
* - {object} collection: The collection from where the data should be extracted
* - {string} entityId: The entity id related to the event
* - {string} entityType: The type of entity related to the event
* - {string} attrName: The attribute id related to the event
* - {number} lastN: Only return the last n matching entries
* - {number} hLimit: Maximum number of results to retrieve when paginating
* - {number} hOffset: Offset to apply when paginating
* - {date} from: The date from which retrieve the aggregated data
* - {date} to: The date to which retrieve the aggregated data
* - {string} filetype: The file type to return the data in
* @param {Function} callback Callback to inform about any possible error or results
*/
function getRawData(data, callback) {
var collection = data.collection,
entityId = data.entityId,
entityType = data.entityType,
attrName = data.attrName,
lastN = data.lastN,
hLimit = data.hLimit,
hOffset = data.hOffset,
from = data.from,
to = data.to,
filetype = data.filetype;
var findCondition;
switch (sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
findCondition = {
'entityId': entityId,
'entityType': entityType,
'attrName': attrName
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
findCondition = {
'attrName': attrName
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
findCondition = {};
break;
}
var recvTimeFilter;
if (from && to) {
recvTimeFilter = {
$lte: to,
$gte: from
};
} else if (from) {
recvTimeFilter = {
$gte: from
};
} else if (to) {
recvTimeFilter = {
$lte: to
};
}
if (recvTimeFilter) {
findCondition.recvTime = recvTimeFilter;
}
var cursor;
var totalCount=0;
if (lastN || lastN === 0) {
cursor = collection.find(
findCondition,
{
_id: 0,
attrType: 1,
attrValue: 1,
recvTime: 1
}
).sort({'recvTime': -1});
cursor.count(function(err, count) {
totalCount=count;
});
cursor = cursor.limit(lastN);
if (filetype === 'csv') {
generateCSV(attrName, cursor.stream(), callback);
} else {
cursor.toArray(function (err, results) {
if (!err) {
results.reverse();
}
return process.nextTick(callback.bind(null, err, results, totalCount));
});
}
} else if (hOffset || hLimit) {
cursor = collection.find(
findCondition,
{
_id: 0,
attrType: 1,
attrValue: 1,
recvTime: 1
}
).sort({'recvTime': 1});
cursor.count(function(err, count) {
totalCount=count;
});
cursor = cursor.skip(hOffset || 0).limit(hLimit || 0);
if (filetype === 'cvs') {
generateCSV(attrName, cursor.stream(), callback);
} else {
cursor.toArray(function (err, results) {
return process.nextTick(callback.bind(null, err, results, totalCount));
});
}
} else {
cursor = collection.find(
findCondition,
{
_id: 0,
attrType: 1,
attrValue: 1,
recvTime: 1
}
);
cursor.count(function(err, count) {
totalCount=count;
});
if (filetype === 'csv') {
generateCSV(attrName, cursor.stream(), callback);
} else {
cursor.toArray(function (err, results) {
return process.nextTick(callback.bind(null, err, results, totalCount));
});
}
}
}
/**
* Filters out a concrete point from the beginning of the results array
* @param points The points array
* @param i The point index to filter out
* @param aggregatedFunction The aggregated function
* @param shouldFilter A flag indicating if results have been filtered out
*/
function filterPointFromBeginning(points, i, aggregatedFunction, shouldFilter) {
if (shouldFilter) {
points.splice(i, 1);
i--;
} else {
points[i].samples = 0;
if (aggregatedFunction === 'occur') {
points[i].occur = {};
} else if (aggregatedFunction === 'min') {
points[i].min = Number.POSITIVE_INFINITY;
} else if (aggregatedFunction === 'max') {
points[i].max = Number.NEGATIVE_INFINITY;
} else {
points[i][aggregatedFunction] = 0;
}
}
return i;
}
/**
* Filters out points from the beginning of the results array
* @param results The results array from which the points should be removed
* @param minOffset The minimum offset which should be included in the results
* @param aggregatedFunction The aggregation function
* @param shouldFilter A flag indicating if the results should be filtered
*/
function filterResultsFromBeginning(results, minOffset, aggregatedFunction, shouldFilter) {
var points = results[0].points;
for (var i = 0; i < points.length; i++) {
if (points[i]) {
if (points[i].offset < minOffset) {
if (points[i].samples) {
i = filterPointFromBeginning(points, i, aggregatedFunction, shouldFilter);
}
} else {
break;
}
}
}
if (!points.length) {
results.splice(0, 1);
}
}
/**
* Filters out a concrete point from the end of the results array
* @param points The points array
* @param i The point index to filter out
* @param aggregatedFunction The aggregated function
* @param shouldFilter A flag indicating if results have been filtered out
*/
function filterPointFromEnd(points, i, aggregatedFunction, shouldFilter) {
if (shouldFilter) {
points.splice(i, 1);
} else {
points[i].samples = 0;
if (aggregatedFunction === 'occur') {
points[i].occur = {};
} else if (aggregatedFunction === 'min') {
points[i].min = Number.POSITIVE_INFINITY;
} else if (aggregatedFunction === 'max') {
points[i].max = Number.NEGATIVE_INFINITY;
} else {
points[i][aggregatedFunction] = 0;
}
}
}
/**
* Filters out points from the end of the results array
* @param results The results array from which the points should be removed
* @param maxOffset The maximum offset which should be included in the results
* @param aggregatedFunction The aggregation function
* @param shouldFilter A flag indicating if the results should be filtered
*/
function filterResultsFromEnd(results, maxOffset, aggregatedFunction, shouldFilter) {
var points = results[results.length - 1].points;
for (var i = points.length - 1; i >= 0; i--) {
if (points[i]) {
if (points[i].offset > maxOffset) {
if (points[i].samples) {
filterPointFromEnd(points, i, aggregatedFunction, shouldFilter);
}
} else {
break;
}
}
}
if (!points.length) {
results.splice(results.length - 1, 1);
}
}
/**
* Filters out the results based on the resolution and the optional from and to dates. For certain resolution, the
* from and to dates are considered and applied until the unit of time indicated by the resolution.
* @param results The array of results
* @param options Additional data to be considered in the filtering. It is an object including the following properties:
* - resolution: The resolution
* - from: The starting date
* - to: The ending date
* - aggregatedFunction: The aggregation function
* - shouldFilter: Flag indicating if null results should be filtered
*/
function filterResults(results, options) {
var resolution = options.resolution,
from = options.from,
to = options.to,
aggregatedFunction = options.aggregatedFunction,
shouldFilter = options.shouldFilter;
if (!results.length) {
return;
}
if (from &&
results[0]._id.origin.getTime() === sthUtils.getOrigin(from, resolution).getTime()) {
var minOffset;
switch (resolution) {
case sthConfig.RESOLUTION.SECOND:
minOffset = from.getUTCSeconds();
break;
case sthConfig.RESOLUTION.MINUTE:
minOffset = from.getUTCMinutes();
break;
case sthConfig.RESOLUTION.HOUR:
minOffset = from.getUTCHours();
break;
case sthConfig.RESOLUTION.DAY:
minOffset = from.getUTCDate();
break;
case sthConfig.RESOLUTION.MONTH:
minOffset = from.getUTCMonth();
break;
}
filterResultsFromBeginning(results, minOffset, aggregatedFunction, shouldFilter);
}
if (results.length && to &&
results[results.length - 1]._id.origin.getTime() === sthUtils.getOrigin(to, resolution).getTime()) {
var maxOffset;
switch (resolution) {
case sthConfig.RESOLUTION.SECOND:
maxOffset = to.getUTCSeconds();
break;
case sthConfig.RESOLUTION.MINUTE:
maxOffset = to.getUTCMinutes();
break;
case sthConfig.RESOLUTION.HOUR:
maxOffset = to.getUTCHours();
break;
case sthConfig.RESOLUTION.DAY:
maxOffset = to.getUTCDate();
break;
case sthConfig.RESOLUTION.MONTH:
maxOffset = to.getUTCMonth();
break;
}
filterResultsFromEnd(results, maxOffset, aggregatedFunction, shouldFilter);
}
}
/**
* Returns the required aggregated data from the database asynchronously
* @param {object} data The data to get the aggregated data. It is an object including the following properties:
* - {object} collection: The collection from where the data should be extracted
* - {string} entityId: The entity id related to the event
* - {string} entityType: The type of entity related to the event
* - {string} attrName: The attribute id related to the event
* - {string} aggregatedFunction: The aggregated function or method to retrieve
* - {string} resolution: The resolution of the data to use
* - {date} from: The date from which retrieve the aggregated data
* - {date} to: The date to which retrieve the aggregated data
* - {boolean} shouldFilter: If true, the null results are filter out
* @param {Function} callback Callback to inform about any possible error or results
*/
function getAggregatedData(data, callback) {
var collection = data.collection,
entityId = data.entityId,
entityType = data.entityType,
attrName = data.attrName,
aggregatedFunction = data.aggregatedFunction,
resolution = data.resolution,
from = data.from,
to = data.to,
shouldFilter = data.shouldFilter;
var fieldFilter = {
'points.offset': 1,
'points.samples': 1
};
fieldFilter['points.' + aggregatedFunction] = 1;
var originFilter;
if (from && to) {
originFilter = {
$lte: sthUtils.getOrigin(to, resolution),
$gte: sthUtils.getOrigin(from, resolution)
};
} else if (from) {
originFilter = {
$gte: sthUtils.getOrigin(from, resolution)
};
} else if (to) {
originFilter = {
$lte: sthUtils.getOrigin(to, resolution)
};
}
if (shouldFilter) {
var pushAccumulator = {
offset: '$points.offset',
samples: '$points.samples'
};
pushAccumulator[aggregatedFunction] = '$points.' + aggregatedFunction;
var matchCondition;
switch (sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
matchCondition = {
'_id.entityId': entityId,
'_id.entityType': entityType,
'_id.attrName': attrName,
'_id.resolution': resolution
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
matchCondition = {
'_id.attrName': attrName,
'_id.resolution': resolution
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
matchCondition = {
'_id.resolution': resolution
};
break;
}
if (originFilter) {
matchCondition['_id.origin'] = originFilter;
}
var groupId;
switch (sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
groupId = {
entityId: '$_id.entityId',
entityType: '$_id.entityType',
attrName: '$_id.attrName',
origin: '$_id.origin',
resolution: '$_id.resolution'
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
groupId = {
attrName: '$_id.attrName',
origin: '$_id.origin',
resolution: '$_id.resolution'
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
groupId = {
origin: '$_id.origin',
resolution: '$_id.resolution'
};
break;
}
collection.aggregate([
{
$match: matchCondition
},
{
$project: fieldFilter
},
{
$unwind: '$points'
},
{
$match: {
'points.samples': {
$gt: 0
}
}
},
{
$group: {
_id: groupId,
points: {
$push: pushAccumulator
}
}
},
{
$sort: {
'_id.origin': 1
}
}
], function (err, resultsArr) {
filterResults(
resultsArr,
{
resolution: resolution,
from: from,
to: to,
aggregatedFunction: aggregatedFunction,
shouldFilter: shouldFilter
}
);
process.nextTick(callback.bind(null, err, resultsArr));
});
} else {
// Get the aggregated data from the database
// Return the data in ascending order based on the origin
var findCondition;
switch (sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
findCondition = {
'_id.entityId': entityId,
'_id.entityType': entityType,
'_id.attrName': attrName,
'_id.resolution': resolution
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
findCondition = {
'_id.attrName': attrName,
'_id.resolution': resolution
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
findCondition = {
'_id.resolution': resolution
};
break;
}
if (originFilter) {
findCondition['_id.origin'] = originFilter;
}
collection.find(
findCondition,
fieldFilter
).sort({'_id.origin': 1}).toArray(
function (err, resultsArr) {
filterResults(
resultsArr,
{
resolution: resolution,
from: from,
to: to,
aggregatedFunction: aggregatedFunction,
shouldFilter: shouldFilter
}
);
process.nextTick(callback.bind(null, err, resultsArr));
}
);
}
}
/**
* Returns the condition to be used in the MongoDB update operation for aggregated data
* @param {object} data The data from which the update condition should be generated. It is an object including the
* following properties:
* - {string} entityId: The entity id
* - {string} entityType: The entity type
* - {string} attrName: The attribute name
* - {string} resolution The resolution
* - {date} recvTime The date (or recvTime) of the notification (attribute value change)
* @returns {Object} The update condition
*/
function getAggregateUpdateCondition(data) {
var entityId = data.entityId,
entityType = data.entityType,
attrName = data.attrName,
resolution = data.resolution,
timestamp = data.timestamp;
var offset = sthUtils.getOffset(resolution, timestamp);
var aggregateUpdateCondition;
switch (sthConfig.DATA_MODEL) {
case sthConfig.DATA_MODELS.COLLECTION_PER_SERVICE_PATH:
aggregateUpdateCondition = {
'_id.entityId': entityId,
'_id.entityType': entityType,
'_id.attrName': attrName,
'_id.origin': sthUtils.getOrigin(timestamp, resolution),
'_id.resolution': resolution,
'points.offset': offset
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ENTITY:
aggregateUpdateCondition = {
'_id.attrName': attrName,
'_id.origin': sthUtils.getOrigin(timestamp, resolution),
'_id.resolution': resolution,
'points.offset': offset
};
break;
case sthConfig.DATA_MODELS.COLLECTION_PER_ATTRIBUTE:
aggregateUpdateCondition = {
'_id.origin': sthUtils.getOrigin(timestamp, resolution),
'_id.resolution': resolution,
'points.offset': offset
};
break;
}
return aggregateUpdateCondition;
}
/**
* Returns the data to prepopulate the aggregated data collection with
* @param {string} attrType The attribute type
* @param {string} attrValue The attribute value
* @param {string} resolution The resolution
*/
function getAggregatePrepopulatedData(attrType, attrValue, resolution) {
var points = [],
totalValues,
offsetOrigin = 0;
switch (resolution) {
case sthConfig.RESOLUTION.SECOND:
totalValues = 60;
break;
case sthConfig.RESOLUTION.MINUTE:
totalValues = 60;
break;
case sthConfig.RESOLUTION.HOUR:
totalValues = 24;
break;
case sthConfig.RESOLUTION.DAY:
offsetOrigin = 1;
totalValues = 32;
break;
case sthConfig.RESOLUTION.MONTH:
offsetOrigin = 1;
totalValues = 13;
break;
}
if (sthUtils.getAggregationType(attrValue) === sthConfig.AGGREGATIONS.NUMERIC) {
for (var i = offsetOrigin; i < totalValues; i++) {
points.push({
offset: i,
samples: 0,
sum: 0,
sum2: 0,
min: Number.POSITIVE_INFINITY,
max: Number.NEGATIVE_INFINITY
});
}
} else {
for (var j = offsetOrigin; j < totalValues; j++) {
var entry = {
offset: j,
samples: 0,
occur: {}
};
points.push(entry);
}
}