-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexploration.js
1534 lines (1430 loc) · 63.2 KB
/
exploration.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
"use strict";
var express = require("express");
var router = express.Router();
var ErrorSerializer = require("../serializers/error");
function gaussian_pdf(x, mean, sigma) {
var gaussianConstant = 1 / Math.sqrt(2 * Math.PI), x = (x - mean) / sigma;
return gaussianConstant * Math.exp(-.5 * x * x) / sigma;
}
/**
* @api {get} /exploration/summary?flow_id=:flow_id&start=:start&end:end Explore summary
* @apiName Explore summary
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID to explore
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/summary/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var flow_id = req.query.flow_id;
var retention = req.query.retention;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
var datatypeType = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.type : null;
var datatypeClassification = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.classification : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
let where = "";
let start = typeof req.query.start!=="undefined"?req.query.start:"";
let end = typeof req.query.end!=="undefined"?req.query.end:"";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (where === "") {
where = "AND time > now()-52w";// TODO : performance issue ; make the max to 1Y
}
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
let query = `SELECT FIRST(${dt}) as first, LAST(${dt}) as last, COUNT(${dt}) as count, MEAN(${dt}) as mean, stddev(${dt}) as std_dev, SPREAD(${dt}) as spread, MIN(${dt}) as minimum, MAX(${dt}) as maximum, MODE(${dt}) as mode, MEDIAN(${dt}) as median, PERCENTILE(${dt},25) as "quantile1", PERCENTILE(${dt},50) as "quantile2", PERCENTILE(${dt},75) as "quantile3" FROM ${rp}.data WHERE flow_id='${flow_id}' ${where}`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((data) => {
if (data.length > 0) {
data.map(function(d) {
d.links = {
"summary": sprintf("%s/v%s/exploration/summary?flow_id=%s&start=%s&end=%s", baseUrl_https, version, flow_id, start, end),
"normality": sprintf("%s/v%s/exploration/normality?flow_id=%s&start=%s&end=%s", baseUrl_https, version, flow_id, start, end),
"head": sprintf("%s/v%s/exploration/head?flow_id=%s&start=%s&end=%s", baseUrl_https, version, flow_id, start, end),
"tail": sprintf("%s/v%s/exploration/tail?flow_id=%s&start=%s&end=%s", baseUrl_https, version, flow_id, start, end),
"distribution": {
"kernelDensityEstimation": sprintf("%s/v%s/exploration/kernelDensityEstimation?flow_id=%s&start=%s&end=%s", baseUrl_https, version, flow_id, start, end),
},
};
d.time = undefined;
d.start_date = moment(start).format("DD-MM-YYYY HH:mm:ss");
d.end_date = moment(end).format("DD-MM-YYYY HH:mm:ss");
d.data_type = {
"name": datatypeName,
"type": datatypeType,
"classification": datatypeClassification,
};
});
res.status(200).send(data[0]);
} else {
res.status(404).send(new ErrorSerializer({ err: "No data found", "id": 4058, "code": 404, "message": "Not found" }).serialize());
}
}).catch((err) => {
res.status(500).send(new ErrorSerializer({ err: err, "id": 4060, "code": 500, "message": "Internal Error" }).serialize());
});
} else {
res.status(412).send(new ErrorSerializer({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" }).serialize());
}
}
});
/**
* @api {get} /exploration/normality?flow_id=:flow_id&start=:start&end:end Explore for normality
* @apiName Explore for normality
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID to explore
* @apiQuery {Float} [x] raw score x
* @apiQuery {Float} expectedValue Expected value of the population mean
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiSuccess {Float} skewness Skewness
* @apiSuccess {Float} z_score zScore
* @apiSuccess {String} t_test tTest of the x value
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/normality/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var flow_id = req.query.flow_id;
var retention = req.query.retention;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
let where = "";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (where === "") {
where = "AND time > now()-52w";// TODO : performance issue ; make the max to 1Y
}
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
let query = `SELECT ${dt} as value FROM ${rp}.data WHERE flow_id='${flow_id}' ${where}`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((data) => {
if (data.length > 3) {
let normalityData;
let arrayOfValues = data.map(function(row) { return row.value; });
normalityData = {
"skewness": statistics.sampleSkewness(arrayOfValues),
"z_score": typeof req.query.x !== "undefined" ? (statistics.zScore(req.query.x, statistics.mean(arrayOfValues), statistics.standardDeviation(arrayOfValues))) : undefined,
"t_test": ((typeof req.query.x) !== "undefined" && (typeof req.query.expectedValue) !== "undefined") ? (statistics.tTest(arrayOfValues, req.query.expectedValue).toFixed(2)) : undefined,
"endpoint_status": "Be cautious, this endpoint is beta !",
};
res.status(200).send(normalityData);
} else {
t6console.debug(sprintf("Query: %s", query));
t6console.debug("sampleSkewness requires at least three data points", data);
res.status(404).send({ err: "No data found", "id": 4058, "code": 404, "message": "Not found or not enougth data" });
}
}).catch((err) => {
res.status(500).send({ err: err, "id": 4060, "code": 500, "message": "Internal Error" });
});
} else {
res.status(412).send({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" });
}
}
});
/**
* @api {get} /exploration/head?flow_id=:flow_id&n=:n Explore the first n rows
* @apiName Explore the first n rows
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID to explore
* @apiQuery {Integer} n Number of Datapoints
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
/**
* @api {get} /exploration/tail?flow_id=:flow_id&n=:n Explore the last n rows
* @apiName Explore the last n rows
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID to explore
* @apiQuery {Integer} n Number of Datapoints
* @apiQuery {String} retention Retention policy
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/:sorting(head|tail)/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var sorting = req.params.sorting === "head" ? "ASC" : (req.params.sorting === "tail" ? "DESC" : "ASC");
var flow_id = req.query.flow_id;
var retention = req.query.retention;
var limit = parseInt(req.query.n, 10) < 50 ? parseInt(req.query.n, 10) : 10;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
let query = `SELECT * FROM ${rp}.data WHERE flow_id='${flow_id}' ORDER BY time ${sorting} LIMIT ${limit} OFFSET 0`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((data) => {
if (data.length > 0) {
data.map(function(d) {
d.id = sprintf("%s/%s", flow_id, moment(d.time).format("x") * 1000);
d.timestamp = Date.parse(d.time);
d.time = d.time.toNanoISOString();
});
t6console.log(data[0]);
res.status(200).send(data);
} else {
res.status(404).send({ err: "No data found", "id": 4058, "code": 404, "message": "Not found" });
}
}).catch((err) => {
res.status(500).send({ err: err, "id": 4060, "code": 500, "message": "Internal Error" });
});
} else {
res.status(412).send({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" });
}
}
});
/**
* @api {get} /exploration/kernelDensityEstimation?flow_id=:flow_id&start=:start&end=:end Explore Distribution KDE
* @apiName Explore Distribution KDE
* @apiDescription Explore Distribution Kernel Density Estimation
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID you want to get data from
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {Number{1-5000}} [limit] Set the number of expected resources.
* @apiQuery {String="min","max","first","last","sum","count"} [select] Modifier function to modify the results
* @apiQuery {String="10ns, 100µ, 3600ms, 3600s, 1m, 3h, 4d, 2w, 365d"} [group] Group By Clause
* @apiQuery {String} [xAxis] Label value in X axis
* @apiQuery {String} [yAxis] Label value in Y axis
* @apiQuery {Integer} [width] output width of SVG chart
* @apiQuery {Integer} [height] output height of SVG chart
* @apiQuery {Integer} [ticks=10] Ticks
* @apiSuccess {Svg} Svg image file
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/kernelDensityEstimation/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var d3nBar = require("d3node-barchart"); // TODO : it should be an histogram !
var flow_id = req.query.flow_id;
var retention = req.query.retention;
var group = req.query.group;
var xAxis = typeof req.query.xAxis !== "undefined" ? req.query.xAxis : "";
var yAxis = typeof req.query.yAxis !== "undefined" ? req.query.yAxis : "";
var width = parseInt(req.query.width, 10);
var height = parseInt(req.query.height, 10);
var ticks = typeof req.query.ticks !== "undefined" ? req.query.ticks : 10;
var query;
var start;
var end;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
let where = "";
let group_by = "";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (typeof group!=="undefined") {
group_by = `GROUP BY time(${group})`;
}
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
query = `SELECT MEAN(${dt}) as mean FROM ${rp}.data WHERE flow_id='${flow_id}' ${where} ${group_by}`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((data) => {
if (data.length > 3) {
var graphData = [];
let svg;
// TODO : it should be an histogram !
data.map(function(row) {
if (typeof row.time !== "undefined") {
graphData.push(row.mean);
}
});
let dataDensity = new Array();
let densityFunc = statistics.kernelDensityEstimation(graphData);
let step = Math.round(statistics.max(graphData) - statistics.min(graphData), 0) / ticks;
for (let n = statistics.min(graphData); n < statistics.max(graphData); n += step) {
dataDensity.push({ key: Math.round(n * 100 / 100), value: densityFunc(n) });
}
svg = d3nBar({
data: dataDensity,
selector: "",
container: "",
labels: { xAxis: xAxis, yAxis: yAxis },
width: width,
height: height,
});
res.setHeader("content-type", "image/svg+xml");
res.status(200).send(svg.svgString());
} else {
t6console.debug(sprintf("Query: %s", query));
t6console.debug("sampleVariance requires at least three data points", data);
res.status(412).send({ err: "No data found", "id": 4058, "code": 412, "message": "Not found or not enougth data" });
}
}).catch((err) => {
t6console.error("kernelDensityEstimation", err);
res.status(500).send({ err: err, "id": 4060, "code": 500, "message": "Internal Error" });
});
} else {
res.status(412).send({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" });
}
}
});
/**
* @api {get} /exploration/loess?flow_id=:flow_id&start=:start&end=:end Explore LOESS
* @apiName Explore LOESS
* @apiDescription Explore LOcally Estimated Scatterplot Smoothing
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID you want to get data from
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {Number{1-5000}} [limit] Set the number of expected resources.
* @apiQuery {String="min","max","first","last","sum","count"} [select] Modifier function to modify the results
* @apiQuery {String="10ns, 100µ, 3600ms, 3600s, 1m, 3h, 4d, 2w, 365d"} [group] Group By Clause
* @apiQuery {String} [xAxis] Label value in X axis
* @apiQuery {String} [yAxis] Label value in Y axis
* @apiQuery {String} [span="0.75"] 0 to inf, default 0.75
* @apiQuery {String=0,1} [band=0] 0 to 1, default 0
* @apiQuery {String="constant","linear","quadratic"} [degree="quadratic"] Lower degree fitting function computes faster.
* @apiQuery {Integer} [width] output width of SVG chart
* @apiQuery {Integer} [height] output height of SVG chart
* @apiSuccess {Svg} Svg image file
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/loess/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var flow_id = req.query.flow_id;
var retention = req.query.retention;
var group = req.query.group;
var xAxisLabel = typeof req.query.xAxis!=="undefined" ? req.query.xAxis : "";
var yAxisLabel = typeof req.query.yAxis!=="undefined" ? req.query.yAxis : "";
var degree = typeof req.query.degree!=="undefined" ? req.query.degree : "";
var span = typeof req.query.span!=="undefined" ? parseFloat(req.query.span) : "";
var band = typeof req.query.band!=="undefined" ? parseFloat(req.query.band) : "";
var width = parseInt(req.query.width, 10);
var height = parseInt(req.query.height, 10);
var query;
var start;
var end;
var limit = parseInt(req.query.limit, 10) < 100001 ? parseInt(req.query.limit, 10) : 10;
if(degree !== "constant" && degree !== "linear" && degree !== "quadratic") {
degree = "quadratic";
}
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
let where = "";
let group_by = "";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (typeof group!=="undefined") {
group_by = `GROUP BY time(${group})`;
}
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
query = `SELECT ${dt} as value FROM ${rp}.data WHERE flow_id='${flow_id}' ${where} ${group_by} LIMIT ${limit} OFFSET 1`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((queryData) => {
if (queryData.length > 10) {
let graphScatterData = [];
let graphLoessData = { x: [], y: [] };
let graphLoess = [];
let svg;
let n = 0;
queryData.map(function(row) {
if (typeof row.time !== "undefined" && row.value !== null) {
graphScatterData.push({ key: parseInt(moment(row.time).format("x"), 10), value: row.value });
graphLoessData.x.push(parseInt(moment(row.time).format("x"), 10));
graphLoessData.y.push(row.value);
}
});
var D3Node = require("d3-node");
const d3n = new D3Node({
selector: "",
svgStyles: "",
styles: "",
container: "",
});
const d3 = d3n.d3;
let _margin = { top: 10, right: 60, bottom: 30, left: 60 };
let _lineWidth = 2;
let _tickSize = 5;
let _tickPadding = 5;
let _lineColor = "#765548";
let _lineColors = ["#795548"];
let _isCurve = true;
svg = d3n.createSVG(width, height)
.append("g")
.attr("transform", `translate(${_margin.left}, ${_margin.top})`);
width = width - _margin.left - _margin.right;
height = height - _margin.top - _margin.bottom;
let g = svg.append("g");
let { allKeys } = graphScatterData;
/* LOESS */
let options /*optional*/ = {
span: span, // 0 to inf, default 0.75
band: band, // 0 to 1, default 0
degree: degree, // degree: [0, 1, 2] || ["constant", "linear", "quadratic"] // default 2
normalize: true, // default true if degree > 1, false otherwise
robust: false, // default false
iterations: 1 //default 4 if robust = true, 1 otherwise
};
let model = new Loess.default(graphLoessData, options);
//let newData = model.grid([graphLoessData.x.length]);
let fit = model.predict(); //newData
var m = 0;
fit.fitted.map((y, idx) => {
graphLoess.push({ key: idx, value: y, halfwidth: fit.halfwidth[idx] });
});
let xScaleScatter = d3.scaleTime()
.domain(allKeys ? d3.extent(allKeys) : d3.extent(graphScatterData, (d) => d.key))
.rangeRound([0, width]);
let yScaleScatter = d3.scaleLinear()
.domain(allKeys ? [d3.min(graphScatterData, (d) => d3.min(d, (v) => v.value)), d3.max(graphScatterData, (d) => d3.max(d, (v) => v.value))] : d3.extent(graphScatterData, (d) => d.value))
.rangeRound([height, 0]);
let xAxis = d3.axisBottom(xScaleScatter)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
let yAxis = d3.axisLeft(yScaleScatter)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
let xScale = d3.scaleTime()
.domain(allKeys ? d3.extent(allKeys) : d3.extent(graphLoess, (d) => d.key))
.rangeRound([0, width]);
var yScaleR = d3.scaleLinear()
//.domain(allKeys ? [d3.min(graphLoess, d => d3.min(d, v => v.value)), d3.max(graphLoess, d => d3.max(d, v => v.value))] : d3.extent(graphLoess, d => d.value))
.domain(allKeys ? [d3.min(graphScatterData, (d) => d3.min(d, (v) => v.value)), d3.max(graphScatterData, (d) => d3.max(d, (v) => v.value))] : d3.extent(graphScatterData, (d) => d.value))
.rangeRound([height, 0]);
/*
xAxis = d3.axisBottom(xScale)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
*/
var yAxisR = d3.axisRight(yScaleR)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
let lineChart = d3.line()
.x((d) => xScale(d.key))
.y((d) => yScaleR(d.value));
const area = d3.area()
.x((d) => xScale(d.key))
.y0((d) => yScaleR(d.value - d.halfwidth))
.y1((d) => yScaleR(d.value + d.halfwidth));
if (_isCurve) { lineChart.curve(d3.curveBasis); }
g.append("g")
.append("path")
.attr("fill", "steelblue")
.style("opacity", .3)
.attr("d", area(graphLoess));
g.append("g")
.attr("fill", "none")
.attr("stroke-width", _lineWidth)
.selectAll("path")
.data(allKeys ? data : [graphLoess])
.enter().append("path")
.attr("stroke", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor)
.attr("d", lineChart);
g.append("g")
.selectAll("dot")
.data(allKeys ? data : graphScatterData)
.enter().append("circle")
.attr("cx", function(d) { return xScaleScatter(d.key); })
.attr("cy", function(d) { return yScaleScatter(d.value); })
.attr("r", _tickSize)
.attr("class", "dot")
.attr("stroke", "black")
.attr("fill", "none");
g.append("g")
.attr("transform", `translate(0, ${height})`)
.text(typeof xAxisLabel!=="undefined"?xAxisLabel:"")
.call(xAxis);
g.append("g")
.text(typeof xAxisLabel!=="undefined"?yAxisLabel:"")
.call(yAxis);
g.append("g")
.attr("transform", `translate(${width}, 0)`)
.call(yAxisR);
// END LOESS
res.setHeader("content-type", "image/svg+xml");
res.status(200).send(d3n.svgString());
} else {
t6console.debug("Loess requires at least 10 data points", queryData, queryData.length);
res.status(404).send({ err: "No data found", "id": 4058, "code": 404, "message": "Not found or not enougth data" });
}
}).catch((err) => {
t6console.error("Loess", err);
res.status(500).send({ err: err, "id": 4060, "code": 500, "message": "Internal Error" });
});
} else {
res.status(412).send({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" });
}
}
});
/**
* @api {get} /exploration/frequencyDistribution?flow_id=:flow_id&start=:start&end=:end Explore Frequency Distribution
* @apiName Explore Frequency Distribution
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID you want to get data from
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {Number{1-5000}} [limit] Set the number of expected resources.
* @apiQuery {String="min","max","first","last","sum","count"} [select] Modifier function to modify the results
* @apiQuery {String="10ns, 100µ, 3600ms, 3600s, 1m, 3h, 4d, 2w, 365d"} [group] Group By Clause
* @apiQuery {String} [xAxis] Label value in X axis
* @apiQuery {String} [yAxis] Label value in Y axis
* @apiQuery {Integer} [width] output width of SVG chart
* @apiQuery {Integer} [height] output height of SVG chart
* @apiSuccess {Svg} Svg image file
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 412
* @apiUse 429
*/
router.get("/frequencyDistribution/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var flow_id = req.query.flow_id;
var retention = req.query.retention;
var group = req.query.group;
var width = parseInt(req.query.width, 10);
var height = parseInt(req.query.height, 10);
var query;
var start;
var end;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
let where = "";
let group_by = "";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (typeof group!=="undefined") {
group_by = `GROUP BY time(${group})`;
}
var flowDT = flows.chain().find({ id: flow_id, }).limit(1);
var joinDT = flowDT.eqJoin(datatypes.chain(), "data_type", "id");
var datatypeName = typeof (joinDT.data())[0] !== "undefined" ? (joinDT.data())[0].right.name : null;
let dt = getFieldsFromDatatype(datatypeName, false, false);
if( datatypeName === "integer" || datatypeName === "float" ) {
let rp = typeof retention!=="undefined"?retention:"autogen";
let flow = (flowDT.data())[0].left;
if( typeof retention==="undefined" || (influxSettings.retentionPolicies.data).indexOf(retention)===-1 ) {
if ( typeof flow!=="undefined" && flow.retention ) {
if ( (influxSettings.retentionPolicies.data).indexOf(flow.retention)>-1 ) {
rp = flow.retention;
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (flow.retention is invalid)", flow.retention, rp);
}
} else {
rp = influxSettings.retentionPolicies.data[0];
t6console.debug("Defaulting Retention from setting (retention parameter is invalid)", retention, rp);
}
}
query = `SELECT MEAN(${dt}) as mean, PERCENTILE(${dt},25) as "q1", PERCENTILE(${dt},50) as "q2", PERCENTILE(${dt},75) as "q3" FROM ${rp}.data WHERE flow_id='${flow_id}' ${where} ${group_by}`;
t6console.debug(sprintf("Query: %s", query));
dbInfluxDB.query(query).then((data) => {
if (data.length > 0) {
var graphData = [];
let svg;
data.map(function(row) {
if (typeof row.time !== "undefined") {
graphData.push({ key: moment(row.time._nanoISO), value: row.mean }); // TODO : security
}
});
var D3Node = require("d3-node");
const d3n = new D3Node({
selector: "",
svgStyles: "",
container: "",
});
const d3 = d3n.d3;
let _margin = { top: 20, right: 10, bottom: 60, left: 50 };
let _lineWidth = 1.5;
let _isCurve = true;
let _tickSize = 5;
let _tickPadding = 5;
let _lineColor = "steelblue";
let _lineColors = ["steelblue"];
let sidePlotWidth = 300;
svg = d3n.createSVG(width, height)
.append("g")
.attr("transform", `translate(${_margin.left}, ${_margin.top})`);
width = width - _margin.left - _margin.right;
height = height - _margin.top - _margin.bottom;
const g = svg.append("g");
const { allKeys } = graphData;
const xScale = d3.scaleTime()
.domain(allKeys ? d3.extent(allKeys) : d3.extent(graphData, (d) => d.key))
.range([0, width - sidePlotWidth]);
const yScale = d3.scaleLinear()
.domain(allKeys ? [d3.min(graphData, (d) => d3.min(d, (v) => v.value)), d3.max(graphData, (d) => d3.max(d, (v) => v.value))] : d3.extent(graphData, (d) => d.value))
.rangeRound([height, 0]);
const xAxis = d3.axisBottom(xScale)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
const yAxis = d3.axisLeft(yScale)
.tickSize(_tickSize)
.tickPadding(_tickPadding);
const lineChart = d3.line()
.x((d) => xScale(d.key))
.y((d) => yScale(d.value));
if (_isCurve) { lineChart.curve(d3.curveBasis); }
g.append("g")
.attr("transform", `translate(0, ${height})`)
.call(xAxis)
.selectAll("text")
.attr("transform", "translate(-10, 0)rotate(-45)")
.style("text-anchor", "end");
g.append("g").call(yAxis);
let m = 10; // margin 10
let barHeight = (height / 4) - 2 * m;
let w, p;
let totalValues = graphData.length;
let min = d3.min(graphData.map(function(d) { return (d.value); }));
let q1 = d3.quantile(graphData.map(function(d) { return (d.value); }), .25);
let q2 = d3.quantile(graphData.map(function(d) { return (d.value); }), .5);
let q3 = d3.quantile(graphData.map(function(d) { return (d.value); }), .75);
let max = d3.max(graphData.map(function(d) { return (d.value); }));
g.append("rect").attr("x", width - 290).attr("y", m).attr("width", sidePlotWidth).attr("height", height).attr("fill", "none").style("fill", "none").style("stroke", "black").style("stroke-width", 2);
let xText = width - 290 + 2*m;
let yText = (barHeight/2 + 2*m + 11/2);
let xRect = width - 290 + m;
let yRect = 2*m;
w = (graphData.filter(function(d) { return (d.value > q3 && d.value < max); }).length) * (sidePlotWidth-2*m) / totalValues;
p = 100*((graphData.filter(function(d) { return (d.value > q3 && d.value < max); }).length) / totalValues).toFixed(1);
g.append("rect").attr("x", xRect).attr("y", yRect).attr("width", w).attr("height", barHeight).attr("fill", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor);
g.append("text")
.attr("x", xText)
.attr("y", yText)
.attr("font-size", "11px")
.text(`${q3.toFixed(4)} < value < ${max.toFixed(4)} : ${p}%`);
yText += barHeight+2*m;
yRect += barHeight+2*m;
w = (graphData.filter(function(d) { return (d.value > q3 && d.value < q2); }).length) * (sidePlotWidth-2*m) / totalValues;
p = 100*((graphData.filter(function(d) { return (d.value > q3 && d.value < q2); }).length) / totalValues).toFixed(1);
g.append("rect").attr("x", xRect).attr("y", yRect).attr("width", w).attr("height", barHeight).attr("fill", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor);
g.append("text")
.attr("x", xText)
.attr("y", yText)
.attr("font-size", "11px")
.text(`${q3.toFixed(4)} < value < ${q2.toFixed(4)} : ${p}%`);
yText += barHeight+2*m;
yRect += barHeight+2*m;
w = (graphData.filter(function(d) { return (d.value > q2 && d.value < q1); }).length) * (sidePlotWidth-2*m) / totalValues;
p = 100*((graphData.filter(function(d) { return (d.value > q2 && d.value < q1); }).length) / totalValues).toFixed(1);
g.append("rect").attr("x", xRect).attr("y", yRect).attr("width", w).attr("height", barHeight).attr("fill", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor);
g.append("text")
.attr("x", xText)
.attr("y", yText)
.attr("font-size", "11px")
.text(`${q2.toFixed(4)} < value < ${q1.toFixed(4)} : ${p}%`);
yText += barHeight+2*m;
yRect += barHeight+2*m;
w = (graphData.filter(function(d) { return (d.value > min && d.value < q1); }).length) * (sidePlotWidth-2*m) / totalValues;
p = 100*((graphData.filter(function(d) { return (d.value > min && d.value < q1); }).length) / totalValues).toFixed(1);
g.append("rect").attr("x", xRect).attr("y", yRect).attr("width", w).attr("height", barHeight).attr("fill", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor);
g.append("text")
.attr("x", xText)
.attr("y", yText)
.attr("font-size", "11px")
.text(`${min.toFixed(4)} < value < ${q1.toFixed(4)} : ${p}%`);
g.append("g")
.attr("fill", "none")
.attr("stroke-width", _lineWidth)
.selectAll("path")
.data(allKeys ? data : [graphData])
.enter().append("path")
.attr("stroke", (d, i) => i < _lineColors.length ? _lineColors[i] : _lineColor)
.attr("d", lineChart);
res.setHeader("content-type", "image/svg+xml");
res.status(200).send(d3n.svgString());
} else {
t6console.debug("", data, data.data);
res.status(404).send({ err: "No data found", "id": 4058, "code": 404, "message": "Not found or not enougth data" });
}
}).catch((err) => {
t6console.error("Loess", err, queryData, queryData.length);
res.status(500).send({ err: err, "id": 4060, "code": 500, "message": "Internal Error" });
});
} else {
t6console.error("flowDT", flowDT.data());
res.status(412).send({ err: `Datatype ${dt} is not compatible`, "id": 4059, "code": 412, "message": "Precondition Failed" });
}
}
});
/**
* @api {get} /exploration/export?flow_id=:flow_id&start=:start&end=:end Export rough data as json array
* @apiName Export rough data as json array
* @apiGroup 10. Exploratory Data Analysis EDA
* @apiVersion 2.0.1
*
* @apiUse Auth
*
* @apiQuery {uuid-v4} flow_id Flow ID you want to get data from
* @apiQuery {String} [start] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {String} [end] Timestamp or formatted date YYYY-MM-DD HH:MM:SS
* @apiQuery {Number{1-5000}} [limit] Set the number of expected resources.
* @apiQuery {String="min","max","first","last","sum","count"} [select] Modifier function to modify the results
* @apiQuery {String="10ns, 100µ, 3600ms, 3600s, 1m, 3h, 4d, 2w, 365d"} [group] Group By Clause
* @apiSuccess {Svg} Svg image file
* @apiUse 200
* @apiUse 401
* @apiUse 404
* @apiUse 405
* @apiUse 429
*/
router.get("/export/?", expressJwt({ secret: jwtsettings.secret, algorithms: jwtsettings.algorithms }), function(req, res) {
var flow_id = req.query.flow_id;
var retention = req.query.retention;
var group = req.query.group;
var query;
var start;
var end;
if (!flow_id) {
res.status(405).send(new ErrorSerializer({ "id": 4056, "code": 405, "message": "Method Not Allowed" }).serialize());
} else {
let where = "";
let group_by = "";
if (typeof req.query.start !== "undefined") {
if (!isNaN(req.query.start) && parseInt(req.query.start, 10)) {
if (req.query.start.toString().length === 10) { start = req.query.start * 1e9; }
else if (req.query.start.toString().length === 13) { start = req.query.start * 1e6; }
else if (req.query.start.toString().length === 16) { start = req.query.start * 1e3; }
where += sprintf(" AND time>=%s", parseInt(start, 10));
} else {
where += sprintf(" AND time>='%s'", req.query.start.toString());
}
}
if (typeof req.query.end !== "undefined") {
if (!isNaN(req.query.end) && parseInt(req.query.end, 10)) {
if (req.query.end.toString().length === 10) { end = req.query.end * 1e9; }
else if (req.query.end.toString().length === 13) { end = req.query.end * 1e6; }
else if (req.query.end.toString().length === 16) { end = req.query.end * 1e3; }
where += sprintf(" AND time<=%s", parseInt(end, 10));
} else {
where += sprintf(" AND time<='%s'", req.query.end.toString());
}
}
if (typeof group!=="undefined") {
group_by = `GROUP BY time(${group})`;