-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhwmonparser.v2.js
More file actions
1425 lines (1267 loc) · 47.7 KB
/
Copy pathhwmonparser.v2.js
File metadata and controls
1425 lines (1267 loc) · 47.7 KB
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
var child = require('child_process'),
fs = require('fs'),
http = require('http'),
events = require('events'),
eventEmitter = new events.EventEmitter(),
DB = require('node-cassandra-cql').Client,
dbhosts = ['localhost'],//Database host
db = new DB({hosts:dbhosts,keyspace:'iomapper'});
global.traceInterval = 15; //In seconds;
global.configInterval = 60; //In seconds;
global.intervals = new Array();
global.mapRoot = 'viewport';
global.defaultClusterId = 'id_cluster_default';
global.hostConfigs = {};
global.hostAttrs = {};
global.agents = [
'raptor' //raptor
,
//'172.16.1.123'
//,
'charger' //charger
,
'challenger'
,
'dart'
,
'lightning'
,
'thunderbird'
,
'corvette'
]
//var config = {};
//var trace = {};
//var ids = {};
//sample = {};
//eventEmitter.on('config',function(cfg){storeObject(cfg)});
//eventEmitter.on('trace',function(trc){storeObject(trc)});
eventEmitter.on('exitParser',function(){process.exit()})//Must initialize event loop
eventEmitter.on('config',function(cfg,host){storeObject(cfg,host)});
eventEmitter.on('trace',function(trc,host){storeObject(trc,host)});
//setInterval(getData,configInterval,configOpts);
//setInterval(getData,traceInterval,traceOpts)
function getData(opts){
//var o = opts.host;
//debugger;
//var z = 'z';
var req = http.request(opts,callback);
req.__opts__ = {};
req.__opts__.host = opts.host;//The callback above is an event listener, doesn't have access to any scope variables. Add request-related info to associate response with request
req.__opts__.path = opts.path
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
console.log('IP: ',opts.host)
console.log('URL: ',req.url);
//debugger;
});
req.end();
function callback(response) {
var str = '';
//debugger;
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
//debugger;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
try{
var sample=JSON.parse(str);
//console.log("Parsed");
//console.log(Object.keys(sample))
if(sample.__config__){
//debugger;
config = JSON.parse(str);
var cfg = str;
var host = this.req.__opts__.host;
eventEmitter.emit('config',cfg,host);
};
if(sample.processes){
//debugger;
trace = JSON.parse(str);
var trc = str;
var host = this.req.__opts__.host;
eventEmitter.emit('trace',trc,host);
};
//var clusters;
//var subnets = new Array();
//storeObject(sample);
//debugger;
//process.kill(process.pid, 'SIGINT');
}
catch(err){
//debugger;
console.log("Error parsing JSON: "+err);
return;
}
//sample = JSON.parse(str);
//console.log(sample)
});
response.on('error', function(err){console.log("ERROR: ",err)})
}
}
function sampleMachine(ip,options){
//var configOpts = {host:'172.16.1.233',port:8125,path:'/config',method:'GET'};//HWMON Agent host
//var traceOpts = {host:'172.16.1.233',port:8125,path:'/trace',method:'GET'};//HWMON Agent host
var configOpts = {host:ip,port:8125,path:'/config',method:'GET'};//HWMON Agent host
var traceOpts = {host:ip,port:8125,path:'/trace',method:'GET'};//HWMON Agent host
//var config = 'asdf';
//var trace = 'fdsa';
getData(configOpts);
getData(traceOpts);
//debugger;
}
function run(){
for (var agent in agents){
sampleMachine(agents[agent]);
}
}
run();
intervals.push(setInterval(run,(traceInterval*1000)));
process.on('SIGINT',function(){
db.shutdown(function(){console.log("Shutting down database connection");
console.log("about to exit");
for (var i=0;i<intervals.length;i++){
clearInterval(intervals[i]);
}
process.exit();
})
//writeOut(rawData);
//hwmon.kill('SIGINT');
})
function writeOut(data){
//var traceOut = JSON.stringify(sockets);
var filename = '/root/file01.txt'
fs.writeFile(filename,data,'utf8',function(err){if(err){console.log('ERROR')}else console.log('Done writing trace file '+ filename)});
}
function storeObject(obj,agent){
//debugger;
var originalString = obj;
obj = JSON.parse(obj);
var traceCounter = 0;//Counts number of items to insert;
var insertCounter = 0;//Counts number of successful inserts;
var insertDone = false;//Set to true when json fully processed and we're only waiting on DB to finish
var ids = {};
//Handle system scan
//debugger;
if(obj.__config__){
//config = JSON.stringify(obj);
//debugger;
if (!hostConfigs[agent]) {
hostConfigs[agent] = {};
hostConfigs[agent] = JSON.parse(originalString);
}
else{
hostConfigs[agent] = JSON.parse(originalString);
}
var config = hostConfigs[agent];
var host = config.id;
if (!hostAttrs[config.id]) {
hostAttrs[config.id] = {};
}
hostAttrs[config.id].config = JSON.parse(originalString);
hostAttrs[config.id].subnets = new Array();
//var clusters = {'a':'b'};
var insertIpQuery = "INSERT INTO ips (ip,host,html_id,device_name) values (?,?,?,?)";
//Insert IP addresses to match sockets against;
for(var nic in obj.nics){
if(obj.nics[nic].__config__ && obj.nics[nic].__config__.ips){
var ips = obj.nics[nic].__config__.ips;
for (var a in ips){
if(ips[a].family == 'IPv4'){
var ip = ips[a].address;
var html_id = obj.nics[nic].id;
var device_name = nic;
var props = [ip,host,html_id,device_name];
insert(insertIpQuery,props)
}
}
}
if(obj.nics[nic].__config__ && obj.nics[nic].__config__.ip && obj.nics[nic].__config__.mask){
var ipcalc = new IPv4_Address(obj.nics[nic].__config__.ip,obj.nics[nic].__config__.mask);
var subnet = ipcalc.netaddressDotQuad;
hostAttrs[config.id].subnets.push(subnet);
}
}
//return;
/*
* Identify the cluster and the client/server container:
*
* Figure out if the host has a parent - lookup the most recent entry in hosts table. Maybe not the most recent... just overwrite them as new relationships are made
* If yes, figure out parent chain - from container to cluster
* Insert into TIME MAP database using the current timestamp. Insert all parents up to and including cluster
* Insert rest of config using simple loop. Or maybe insert the whole JSON for the host as one line to save time
*
* If NOT: the host doesn't have a parent. Need to determine the cluster - how?
* Step 0: Identify IPs (done above) and subnets of the host
* Step 1 - worst: lookup subnets each cluster is responsible for. If found - use that cluster
* What if several subnets are found belonging to different clusters?
* Step 2 - better: lookup "unknown peers" IPs created when sockets are recorded, and remote is not found. If found, Use cluster of known peer
* This is bad idea. Sockets could be very remote... strike step 2
* Step 3 - best: lookup "unknown peers" WWNs created when disk (FC/IB) I/O is recored. If found, use cluster of known peer
* Only works for storage devices
* Step 4: If not found - use default cluster
*
*
*/
function retrieveClusters(currentId){
function data(currentId){//Define closure function to pass current variables to callback. Don't ask how
//debugger;
return currentId;
}
var params = [];
for (var a = 0; a<hostAttrs[currentId].subnets.length; a++){params.push('?')};
var params = params.join();
var subnetClusterQuery = 'select subnet,cluster_id,parent from subnets where subnet in (' + params + ')';
db.execute(subnetClusterQuery,hostAttrs[currentId].subnets,function(err,result){
var id = data(currentId);
//debugger;
//currentData.originalString = JSON.parse(currentData.originalString);
var cluster = '';
var parent;
//debugger;
if(err){console.log('Could not select clusters; Error: ',err);debugger}
else{
//console.log(clusters);
var clusters = result.rows;
//debugger;
if (clusters.length == 0) {
//cluster = 'defaut';
//insertConfig()
}
else{
for (var z = 0; z < clusters.length; z++){
if (hostAttrs[id].subnets.indexOf(clusters[z]['subnet']) == -1) {
var error = new Error('DB result is not in list of subnets...');
//debugger;
console.log(error);
//console.log(currentData);
console.log(result);
}
else if (clusters[z]['cluster_id'] == null) {
//cluster = 'id_default_cluster';
}
else{
cluster = clusters[z]['cluster_id'];
parent = clusters[z]['parent'];
}
}
}
}
if (cluster == '') {
cluster = defaultClusterId;//'id_cluster_default';
parent = mapRoot;//'viewport'
}
hostAttrs[id].cluster = {'id':cluster,'parent':parent};
retrieveContainers(id);
//debugger;
})
}
function retrieveContainers(currentId){
function data(currentId){//Define closure function to pass current variables to callback. Don't ask how
//debugger;
return currentId;
}
var clusterContainersQuery = "select template,parent,html_id from containers where template in ('clientContainer','serverContainer') and parent=?";
db.execute(clusterContainersQuery,[hostAttrs[currentId].cluster.id],function(err,result){
var id = data(currentId);
//debugger;
if(err){console.log('Could not select containers; Error: ',err);debugger}
else{
//console.log(clusters);
var containers = result.rows;
//debugger;
if (containers.length == 0) {
if(!hostAttrs[id].containers){hostAttrs[id].containers = {};};
if (!hostAttrs[id].containers.clientContainer) {hostAttrs[id].containers.clientContainer={};}
if (!hostAttrs[id].containers.serverContainer) {hostAttrs[id].containers.serverContainer={};}
hostAttrs[id].containers.clientContainer.parent = hostAttrs[id].cluster.id;
hostAttrs[id].containers.clientContainer.id = 'id_clientContainer_' + hostAttrs[id].cluster.id;
hostAttrs[id].containers.serverContainer.parent = hostAttrs[id].cluster.id;
hostAttrs[id].containers.serverContainer.id = 'id_serverContainer_' + hostAttrs[id].cluster.id;
var containerInsertQuery = 'INSERT INTO CONTAINERS (template,parent,html_id) values(?,?,?)';
var containerProps = ['clientContainer',hostAttrs[id].containers.clientContainer.parent,hostAttrs[id].containers.clientContainer.id]
insert(containerInsertQuery,containerProps);
var containerProps = ['serverContainer',hostAttrs[id].containers.serverContainer.parent,hostAttrs[id].containers.serverContainer.id]
insert(containerInsertQuery,containerProps);
}
else{
for (var z = 0; z < containers.length; z++){
if (hostAttrs[id].cluster.id != containers[z]['parent']) {
var error = new Error('DB result is not the right cluster...');
//debugger;
console.log(error);
//console.log(currentData);
console.log(result);
}
else if (containers[z]['html_id'] == null) {//No html_id
//cluster = 'default';
}
else{
if(!hostAttrs[id].containers){hostAttrs[id].containers = {};};
if (!hostAttrs[id].containers[containers[z]['template']]) {hostAttrs[id].containers[containers[z]['template']]={};}
hostAttrs[id].containers[containers[z]['template']]['id'] = containers[z]['html_id'];
hostAttrs[id].containers[containers[z]['template']]['parent'] = containers[z]['parent'];
}
}
}
}
//debugger;
insertConfig(id);
})
}
function retrieveHosts(currentId){
function data(currentId){//Define closure function to pass current variables to callback. Don't ask how
//debugger;
return currentId;
}
var hostQuery = 'select host,parent from hosts where host=?';
db.execute(hostQuery,[currentId],function(err,result){
var id = data(currentId);
//debugger;
//currentData.originalString = JSON.parse(currentData.originalString);
var parent = '';
//debugger;
if(err){console.log('Could not select hosts; Error: ',err);debugger}
else{
//console.log(clusters);
var parents = result.rows;
//debugger;
if (parents.length == 0) {
//cluster = 'defaut';
//insertConfig()
}
else{
for (var z = 0; z < parents.length; z++){
if (id != parents[z]['host']) {
var error = new Error('DB result is not the right host...');
//debugger;
console.log(error);
console.log(result);
}
else if (parents[z]['parent'] == null) {
}
else{
parent = parents[z]['parent'];
}
}
}
}
if (parent == '') {
//debugger;
retrieveClusters(id);
}
else{
hostAttrs[id].parent = parent;
//Insert config here;
}
//debugger;
})
}
//retrieveClusters(config.id);
retrieveHosts(config.id);
//######################################################################
//return;
function insertConfig(id){
//var time = new Date().getTime();
var parent;
var html_id;
var template;
var json;
//var query = "INSERT INTO MAPPER (parent,time,html_id,template) values (?,?,?,?)";
var query = "INSERT INTO MAPPER (parent,html_id,template) values (?,?,?)";
//var props = [parent,time,html_id];
//var props = [parent,html_id];
//Insert cluster
parent = hostAttrs[id].cluster.parent;
html_id = hostAttrs[id].cluster.id;
template = 'cluster';
//props = [parent,time,html_id,template];
var props = [parent,html_id,template];
db.execute(query,props,function(err){if(err){console.log("ERROR: ",err)}});
//Insert container
parent = html_id;
switch (hostAttrs[id].config.template) {
case 'client':
html_id = hostAttrs[id].containers.clientContainer.id;
template = 'clientContainer';
break;
case 'server':
html_id = hostAttrs[id].containers.serverContainer.id;
template = 'serverContainer';
break;
}
//props = [parent,time,html_id,template];
props = [parent,html_id,template];
db.execute(query,props,function(err){if(err){console.log("ERROR: ",err)}});
//Insert host:
parent = html_id;
html_id = id;
template = hostAttrs[id].config.template;
json = JSON.stringify(hostAttrs[id].config)
//query = "INSERT INTO MAPPER (parent,time,html_id,template,json) values (?,?,?,?,?)";
query = "INSERT INTO MAPPER (parent,html_id,template,json) values (?,?,?,?)";
//props = [parent,time,html_id,template,json];
props = [parent,html_id,template,json];
db.execute(query,props,function(err){if(err){console.log("ERROR: ",err)}});
//debugger;
};
//debugger;
}
//Handle sample metrics
else if(obj.processes){
//Make sure CONFIG is there
if (!hostConfigs[agent]) {
console.log("No config present, can't process trace");
return;
}
var config = hostConfigs[agent];
//if(!config || !config.__config__ || !config.id){
//
//}
var date = new Date();
//Calculate unique "Time Period" key. This will be the primary key upon insert.
//Every sample which falls into the same period will have an identical key
//Find the nearest "tick" and set the key to it
var timeKey = new Date(date);
timeKey.setMilliseconds(0);
var s = timeKey.getSeconds();
if (s<traceInterval) {s = 0}
else{s = s-(s%traceInterval)};
timeKey.setSeconds(s);
//console.log('Time: ',date)
//console.log('Time Key: ',timeKey)
var realTimestamp = date.getTime();
var timestamp = timeKey.getTime();
console.log('Time: ',timeKey)
//debugger;
//IF I want to convert from Unix epoch:
//var utcSeconds = 1234567890;
//var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
//d.setUTCSeconds(utcSeconds);
//How to select timestamp with milliseconds:
//select type,blobAsBigint(timestampAsBlob(ts)) AS val from iomapper.tempio limit 20;
/*
* How to get a TIMESTAMP field from Cassandra and convert it to milliseconds string in Javascript:
* select ts from table;
* var a = ts string (Sun Dec 22 2013 18:02:32 GMT-0800 (PST));
* a automatically becomes a Date Object
* a.getTime() - gives you the exact string you have in DB
*
*/
//Types:
//disk
//proccpu
//procmem
//procdisk
//net
var type,
host = config.id,//THE HTML ID of the host from config
ts = timestamp,
device_id = '',
metric_name,
uuid,
metric_value = '';
var laddr = '',
lport = '',
raddr = '',
rport = '',
pid = '',
html_id,
origin,
parentB,
bwa,bwb,stream_id,
attrs = {};
ids.raids = new Object();
ids.vols = new Object();
var procPipes = [];
//tag1 = '',
//tag2 = '',
//tag3 = '',
//tag4 = '',
//tag5 = '',
//tag6 = '',
//tag7 = '',
//tag8 = '',
//var tempIoQuery = "INSERT INTO tempio (type,ts,host,device_id,metric_name,uuid,device_name,metric_value) values (?,?,?,?,?,?,?,?)";
//var tempIoQuery = "INSERT INTO tempio (type,ts,host,device_id,uuid,metric_value,json) values (?,?,?,?,?,?,?)";
var tempIoQuery = "INSERT INTO tempio (type,ts,host,device_id,uuid,metric_value) values (?,?,?,?,?,?)";
var pipesQuery = "INSERT INTO pipes (type,ts,html_id,origin,parentB,bwa,bwb,stream_id) values (?,?,?,?,?,?,?,?)";
var socketsQuery = "INSERT INTO sockets (laddr,lport,raddr,rport,html_id,read,write) values (?,?,?,?,?,?,?)";
var liveSocketsQuery = "SELECT laddr,lport,raddr,rport,html_id,read,write FROM sockets WHERE laddr=? AND lport=? AND raddr=? AND rport=?"
var liveIpQuery = "SELECT host,html_id,device_name FROM ips WHERE ip=?"
var query = tempIoQuery;
//var props = [ts,host,device,m_value,name,uuid,tag1,tag2,tag3,tag4,tag5,tag6,tag7,tag8,ts];
if(obj.PhysIO){
for (var a in obj.PhysIO){
type = 'volpipe';
device_name = a;
var dev = a;//Find the actual device ID from config; dev is used in matchDiskId function();
if(!ids.raids[dev]){//If ID hasn't been found yet
walk(config,matchDiskId);//Find ID - only look in physical devices (skip dm-0 kind of devices)
if(!ids.raids[dev] || !ids.raids[dev].origin || !ids.raids[dev].parentB){continue}//If ID still not found - skip
}
origin = ids.raids[dev].origin;
parentB = ids.raids[dev].parentB;
html_id = htmlId(type,origin,parentB,'readBytesSec');
bwa = obj.PhysIO[a]['readBytesSec'];bwb = bwa;
stream_id = '0';
//debugger;
if(bwa != 0){
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
//debugger;
insert(pipesQuery,props);
}
html_id = htmlId(type,origin,parentB,'writeBytesSec');
bwa = obj.PhysIO[a]['writeBytesSec'];bwb = bwa;
if(bwa != 0){
//debugger;
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
insert(pipesQuery,props);
}
}
}
if(obj.network){
for (var a in obj.network){
type = 'socket';
//device = obj.network[a].MAC;
//name = "bytesReceivedPerSec";
var dev = obj.network[a].local;
if(!ids[dev]){//If ID hasn't been found yet
walk(config.nics,matchNicId);//Find ID
//debugger;
if(!ids[dev]){continue}//If ID still not found - skip
else{device_id = ids[dev].id}
}
device_id = ids[dev].id
metric_name = "netSocket";
//var socketId = ipToNum(obj.network[a].local).toString()+'_'+obj.network[a].localport.toString();//Maybe later when this becomes a problem
var socketId = obj.network[a].local+'_'+obj.network[a].localport.toString();
uuid = htmlId(type,host,metric_name,socketId);
obj.network[a].uuid = uuid;
device_name = ids[dev].device_name;
//debugger;
//if(!ids[a]){continue}
//else{device_id = ids[a].id};
//walk(config,matchNicId);
//console.log("NAME: ",name)
//debugger;
//Figure out percentage value for the socket traffic
var speed = config.nics[device_name].__config__.speed;
metric_value = obj.network[a].bytesReceivedPerSec+obj.network[a].bytesSentPerSec;
//In bits per second:
metric_value = metric_value*8;
//In percent:
metric_value = metric_value/(speed/100)
//if(metric_value != 0){
//var props = [type,ts,host,device_id,metric_name,uuid,device_name,metric_value];
var props = [type,ts,host,device_id,uuid,metric_value];
//traceCounter++;
insert(tempIoQuery,props);
//}
laddr = obj.network[a].local;
lport = obj.network[a].localport.toString();
raddr = obj.network[a].remote;
rport = obj.network[a].remoteport.toString();
var read = obj.network[a].bytesReceivedPerSec;
var write = obj.network[a].bytesSentPerSec;
var props = [laddr,lport,raddr,rport,uuid,read,write];
insert(socketsQuery,props);
//metric_name = "bytesSentPerSec";
//metric_value = obj.network[a].bytesSentPerSec;
//if(metric_value != 0){
// var props = [type,ts,host,device_id,metric_name,uuid,device_name,metric_value];
// //traceCounter++;
// insert(query,props);
//}
origin = uuid;
parentB = htmlId('proccpu',host,'processCpuUtil',obj.network[a].PID);
type = 'nicpipe';
html_id = htmlId(type,origin,parentB,'read');
bwa = obj.network[a].bytesReceivedPerSec;bwb = bwa;
stream_id = '0';
if(bwa != 0){
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
insert(pipesQuery,props);
}
html_id = htmlId(type,origin,parentB,'write');
bwa = obj.network[a].bytesSentPerSec;bwb = bwa;
if(bwa != 0){
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
insert(pipesQuery,props);
}
//Create NETPIPE;
//debugger;
createNetPipe(obj.network[a])
}
}
if(obj.processes){
for (var a in obj.processes){
//device = 'cpu'+obj.processes[a].processor.toString();
type = 'proccpu'
var dev = obj.processes[a].processor;
if(!ids.cpus){ids.cpus = new Object();}
if(!ids.cpus[dev]){//If ID hasn't been found yet
walk(config.cpus,matchCpuId);//Find ID
//debugger;
if(!ids.cpus[dev]){debugger;continue}//If ID still not found - skip
else{device_id = ids.cpus[dev].id;
device_name = ids.cpus[dev].device_name;
}
}
device_id = ids.cpus[dev].id;
device_name = ids.cpus[dev].device_name;
metric_name = 'processCpuUtil';
//uuid = obj.processes[a].PID.toString();
var pid = obj.processes[a].PID.toString();
uuid = htmlId(type,host,metric_name,pid);
origin = uuid;
metric_value = obj.processes[a].procCpuUtil;
//if (!metric_value) {
// debugger;
//}
if (metric_value == null) {
debugger;
}
bwa = metric_value;
//var props = [type,ts,host,device_id,metric_name,uuid,device_name,metric_value];
var props = [type,ts,host,device_id,uuid,metric_value];
//traceCounter++;
if (metric_value == 0) {
//Coalesce zero-value metrics
if (!zero) {
var zero = new Object();
}
if (!zero[type]) {
zero[type] = new Object();
}
if (!zero[type][device_id]) {
zero[type][device_id] = new Array();
}
zero[type][device_id].push(uuid);
//Create new ORIGIN for connecting pipe;
origin = htmlId(type,host,device_id,'zero');
}
else{
insert(tempIoQuery,props);
}
type = 'procmem'
metric_name = 'processMemUtil';
//metric_value = obj.processes[a].memoryKB; //Replacing with percentage
metric_value = obj.processes[a].memUtilPct;
if(!ids.ram){//If ID hasn't been found yet
walk(config.ram,matchRamId);//Find ID
//debugger;
if(!ids.ram){continue}//If ID still not found - skip
else{device_id = ids.ram.id;
device_name = ids.ram.device_name;
}
}
device_id = ids.ram.id;
device_name = ids.ram.device_name;
uuid = htmlId(type,host,metric_name,pid);
parentB = uuid;
bwb = metric_value;
//var props = [type,ts,host,device_id,metric_name,uuid,device_name,metric_value];
var props = [type,ts,host,device_id,uuid,metric_value];
if (metric_value == 0) {
//Coalesce zero-value metrics
if (!zero) {
var zero = new Object();
}
if (!zero[type]) {
zero[type] = new Object();
}
if (!zero[type][device_id]) {
zero[type][device_id] = new Array();
}
zero[type][device_id].push(uuid);
//Change Parent B designation for connecting pipe;
parentB = htmlId(type,host,device_id,'zero');
}
else{
insert(tempIoQuery,props);
}
//Create pipe between process and mem
type = 'procpipe';
html_id = htmlId(type,origin,parentB,'pipe');
stream_id = '0';
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
if (procPipes.indexOf(html_id) == -1) {
insert(pipesQuery,props);
}
//else{console.log('Pipe ',html_id,' exists, skipping insert')}
//Add Pipe name to an array to prevent duplicate creations
procPipes.push(html_id);
if(obj.processes[a].diskio){
type = 'mempipe'
origin = parentB;//From the MEM sample
for (var b in obj.processes[a].diskio){
var dev = b.replace('/dev/','');
if(!ids.vols[dev]){//If ID hasn't been found yet
walk(config.vols,matchVolId);//Find ID
if(!ids.vols[dev]){continue}//If ID still not found - skip
else{parentB = ids.vols[dev].id}
}
parentB = ids.vols[dev].id;
//device_name = dev; //ids[dev].device_name;
//metric_name = 'processDiskUtil';
html_id = htmlId(type,origin,parentB,'readBytesSec');
bwa = obj.processes[a].diskio[b]['readBytesSec'];bwb = bwa;
stream_id = '0';
//debugger;
if(bwa != 0){
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
//debugger;
insert(pipesQuery,props);
}
html_id = htmlId(type,origin,parentB,'writeBytesSec');
bwa = obj.processes[a].diskio[b]['writeBytesSec'];bwb = bwa;
if(bwa != 0){
//debugger;
var props = [type,ts,html_id,origin,parentB,bwa,bwb,stream_id];
insert(pipesQuery,props);
}
}
}
}
if (zero) {
//debugger;
metric_value = 0;
for (var type in zero) {
for(var device_id in zero[type]){
//for(var u = 0; u < zero[type][device_id].length; u++){}
var json = JSON.stringify(zero[type][device_id]);
var tempIoQuery = "INSERT INTO tempio (type,ts,host,device_id,uuid,metric_value,json) values (?,?,?,?,?,?,?)";
uuid = htmlId(type,host,device_id,'zero');
var props = [type,ts,host,device_id,uuid,metric_value,json];
//debugger;
insert(tempIoQuery,props);
}
}
}
}
//console.log("Traces to Insert: ",traceCounter);
insertDone = true;
eventEmitter.once('trace_insert_complete',function(){console.log("Traces Inserted: ",insertCounter)})
}
else{return}
//debugger;
function walk(obj,action){
for(var leaf in obj){
if(obj.hasOwnProperty(leaf)){
var value = obj[leaf];
if(typeof value === 'object'){//do stuff
action(value,leaf,obj);
walk(value,action);
}
}
}
}
function matchVolId(value,leaf,obj){
//if(leaf == dev){
//console.log(leaf);console.log(obj);
if(value.id){
var id = value.id;
if (value.__config__ && value.__config__.kdevice && value.__config__.kdevice == dev){
if(!ids.vols[dev]){
ids.vols[dev] = new Object();
}
ids.vols[dev].id = id;
}
}
};
function matchDiskId(value,leaf,obj){
//console.log(leaf);console.log(obj);
if(value.id){
var id = value.id;
if(leaf == dev){
if(!ids.raids[dev]){
ids.raids[dev] = new Object();
}
ids.raids[dev].id = id;
ids.raids[dev].parentB = id;
}
if (value.__config__ && value.__config__.dst && value.__config__.dst[dev] && value.__config__.dst[dev].kname == dev){
if(!ids.raids[dev]){
ids.raids[dev] = new Object();
}
ids.raids[dev].origin = id;
}
}
//else if(value.kdevice && value.kdevice == dev){
// //console.log(leaf);console.log(obj);
// var id = obj.id;
// if(!ids[dev]){ids[dev] = new Object(); ids[dev].id = id;}
//}
};
function matchNicId(value,leaf,obj){
//if(leaf == dev){
//console.log(leaf);console.log(obj);
if(value.id){
var id = value.id;
if (value.__config__ && value.__config__.ips && value.__config__.ips instanceof Array){
for (var a = 0; a < value.__config__.ips.length; a++){
if(value.__config__.ips[a].address == dev){
if(!ids[dev]){ids[dev] = new Object(); ids[dev].id = id;ids[dev].device_name = leaf}
}
}
}
//if(!ids[dev]){ids[dev] = new Object(); ids[dev].id = id;}
}
};
function matchCpuId(value,leaf,obj){
//if(leaf == dev){
//console.log(leaf);console.log(obj);
if(value.id){
//console.log("ID: ",value.id)
var id = value.id;
//console.log("Value: ",value)
if (value.__config__ && value.__config__.processor == dev){
//for (var a = 0; a < value.__config__.ips.length; a++){
//console.log("Processor ",value.__config__.processor)
//if(value.__config__.processor == dev){
//console.log("dev ",dev)
if(!ids.cpus[dev]){ids.cpus[dev] = new Object(); ids.cpus[dev].id = id;ids.cpus[dev].device_name = leaf}
//}
//}
}
//if(!ids[dev]){ids[dev] = new Object(); ids[dev].id = id;}
}
};
function matchRamId(value,leaf,obj){
//if(leaf == dev){
//console.log(leaf);console.log(obj);
if(value.id){
var id = value.id;
if (value.template && value.template == 'ram'){
//for (var a = 0; a < value.__config__.ips.length; a++){
//if(value.__config__.processor == dev){
if(!ids.ram){ids.ram = new Object(); ids.ram.id = id;ids.ram.device_name = leaf}
//}
//}
}
//if(!ids[dev]){ids[dev] = new Object(); ids[dev].id = id;}
}
};
function createNetPipe(socket){
var laddr = socket.local,
lport = socket.localport.toString(),
raddr = socket.remote,
rport = socket.remoteport.toString(),
read = socket.bytesReceivedPerSec,
write = socket.bytesSentPerSec,
type = 'netpipe';
//Figure out if this machine is server or client
var srv = false;
if(trace.netstat){
if(trace.netstat['0.0.0.0']){
if(trace.netstat['0.0.0.0'][lport]){srv = true}
}
else if(trace.netstat[laddr]){
if(trace.netstat[laddr][lport]){srv = true}
}
}
//Search existing sockets for the opposing match
//If found:
//If SERVER - create two pipes with the opposite being ORIGIN
//BWA is remote, BWB is local
//If CLIENT - create two pipes with THIS being origin
//BWA is local, BWB is remote
//If socket not found:
//Search the IPs for a remote match
//If found:
//Create socket with remote/local flipped, read and write BWs are taken from local trace
//Assign proper HTML ID to it
//If SERVER - create two pipes with the opposite being ORIGIN
//BWA is remote, BWB is local
//If CLIENT - create two pipes with THIS being origin
//BWA is local, BWB is remote
//If IP not found:
//Do nothing at this point.