-
Notifications
You must be signed in to change notification settings - Fork 1
/
gyeeta_comm.js
2135 lines (1680 loc) · 56.2 KB
/
gyeeta_comm.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';
const net = require('net');
const assert = require('assert').strict;
const chalk = require('chalk');
const {safetypeof} = require("./gyutil.js");
const moment = require('moment');
const {evaluateFilter} = require("./evaluate.js");
require('console-stamp')(console, {
format: ':date(yyyy-mm-dd HH:MM:ss.l)::label:'
});
const MAX_COMM_DATA_SZ = 16 * 1024 * 1024;
const NS_HDR_MAGIC = 0x05999905;
const NM_HDR_MAGIC = 0x05AAAA05;
const NS_REGISTER_REQ = 6;
const NM_CONNECT_CMD = 7;
const NS_REGISTER_RESP = 12;
const NM_CONNECT_RESP = 13;
const COMM_EVENT_NOTIFY = 14;
const COMM_QUERY_CMD = 15;
const COMM_QUERY_RESP = 16;
const NS_ALERT_REGISTER = 17;
const NOTIFY_PING_CONN = 0xA01;
const NOTIFY_JSON_EVENT = 0xA02;
const JsonMsgTypes = {
QUERY_WEB_JSON : 1,
CRUD_GENERIC_JSON : 2,
CRUD_ALERT_JSON : 3,
};
const RESP_WEB_JSON = 1000;
const RESP_JSON_WITH_HEADER = 1;
const NODE_VERSION = 0x000200;
const NODE_VERSION_STR = '0.2.0';
const MIN_SHYAMA_VERSION = 0x000200;
const MIN_MADHAVA_VERSION = 0x000200;
const COMM_VERSION = 1;
const CLI_TYPE_REQ_RESP = 0;
const NodeMsgTypes = {
NODE_MSG_QUERY : 1,
NODE_MSG_ADD : 2,
NODE_MSG_UPDATE : 3,
NODE_MSG_DELETE : 4,
NODE_MSG_PING : 5,
};
const NodeQueryTypes = {
NN_MIN_TYPE : 1000,
NS_MADHAVA_LIST : 1001,
NM_HOST_STATE : 1002,
NM_CPU_MEM : 1003,
NM_LISTENER_STATE : 1004,
NM_TOP_HOST_PROCS : 1005,
NM_TOP_LISTENERS : 1006,
NM_LISTENER_INFO : 1007,
NM_ACTIVE_CONN : 1008,
NM_LISTENER_SUMM : 1009,
NM_LISTENPROC_MAP : 1010,
NM_CLIENT_CONN : 1011,
NM_NOTIFY_MSG : 1012,
NM_HOST_INFO : 1013,
NM_PROC_INFO : 1014,
NM_PROC_STATE : 1015,
NM_TOP_AGGR_PROCS : 1016,
NM_CLUSTER_STATE : 1017,
NS_SVC_MESH_CLUST : 1018,
NS_SVC_IP_CLUST : 1019,
NS_ALERTS : 1020,
NS_ALERTDEF : 1021,
NS_INHIBITS : 1022,
NS_SILENCES : 1023,
NS_ACTIONS : 1024,
NM_EXTSVCSTATE : 1025,
NM_EXTACTIVECONN : 1026,
NM_EXTCLIENTCONN : 1027,
NM_EXTPROCSTATE : 1028,
NS_SHYAMASTATUS : 1029,
NM_MADHAVASTATUS : 1030,
NM_PARTHALIST : 1031,
NM_MULTI_QUERY : 5000,
};
const ErrorTypes = {
ERR_SUCCESS : 0,
ERR_INVALID_REQUEST : 400,
ERR_CONFLICTS : 409,
ERR_DATA_NOT_FOUND : 410,
ERR_SERV_ERROR : 500,
ERR_TIMED_OUT : 504,
ERR_BLOCKING_ERROR : 503,
ERR_MAX_SZ_BREACHED : 507,
ERR_SYSERROR : 510,
};
let gNodeHost = '';
let gNodePort = 0;
function get_align_len(nsize, nalign = 8)
{
return ((nsize - 1) & ~(nalign - 1)) + nalign;
}
function get_curr_sec_big(secsToAdd = 0)
{
return BigInt((Date.now() / 1000 | 0) + secsToAdd);
}
class GyCommError extends Error
{
constructor(message)
{
super(message);
this.name = this.constructor.name;
}
};
class CommHeader
{
static structlen = 16;
constructor(data_type, payload_len, ismad)
{
const hdr = Buffer.allocUnsafe(CommHeader.structlen);
let padlen = 0, offlen = 0, padbuf = "";
let total_sz = CommHeader.structlen + payload_len;
padlen = get_align_len(total_sz) - total_sz;
total_sz += padlen;
offlen = hdr.writeUInt32LE(ismad ? NM_HDR_MAGIC : NS_HDR_MAGIC, 0);
offlen = hdr.writeUInt32LE(total_sz, offlen);
offlen = hdr.writeUInt32LE(data_type, offlen);
offlen = hdr.writeUInt32LE(padlen, offlen);
if (padlen > 0) {
padbuf = Buffer.allocUnsafe(padlen);
for (let i = 0; i < padlen; ++i) {
padbuf[i] = 0;
}
}
this.struct_ = hdr;
this.padding_sz_ = padlen;
this.data_type_ = data_type;
this.total_sz_ = total_sz;
this.padbuf_ = padbuf;
CommHeader.validate(this);
}
static parse_hdr(hdr, conn)
{
assert.equal(hdr.length, CommHeader.structlen);
const tmagic = conn.is_madhava_ ? NM_HDR_MAGIC : NS_HDR_MAGIC;
let obj = {};
obj.magic_ = hdr.readUInt32LE(0);
if (obj.magic_ != tmagic) {
throw new GyCommError(`ERROR : Invalid Magic Type seen for Communication Header ${obj.magic_.toString(16)}`);
}
obj.total_sz_ = hdr.readUInt32LE(4);
obj.data_type_ = hdr.readUInt32LE(8);
obj.padding_sz_ = hdr.readUInt32LE(12);
CommHeader.validate(obj);
return obj;
}
static validate(obj)
{
if (obj.total_sz_ > MAX_COMM_DATA_SZ || obj.total_sz_ <= CommHeader.structlen) {
throw new GyCommError(`ERROR : Invalid Total Size seen for Communication Header ${obj.total_sz_}`);
}
switch (obj.data_type_) {
case COMM_QUERY_RESP :
case COMM_QUERY_CMD :
case COMM_EVENT_NOTIFY :
case NM_CONNECT_CMD :
case NM_CONNECT_RESP :
case NS_REGISTER_REQ :
case NS_REGISTER_RESP :
case NS_ALERT_REGISTER :
break;
default :
throw new GyCommError(`ERROR : Invalid Data Type seen for Communication Header ${Number(obj.data_type_).toString(16)}`);
}
if (obj.padding_sz_ >= 8) {
throw new GyCommError(`ERROR : Invalid Padding Size seen for Communication Header ${obj.padding_sz_}`);
}
}
};
class NSRegisterReq
{
static structlen = 416;
constructor()
{
const hdr = Buffer.allocUnsafe(NSRegisterReq.structlen);
let offlen = 0;
hdr.fill(0);
offlen = hdr.writeBigUInt64LE(get_curr_sec_big(), 0);
offlen = hdr.writeUInt32LE(COMM_VERSION, offlen);
offlen = hdr.writeUInt32LE(NODE_VERSION, offlen);
offlen = hdr.writeUInt32LE(MIN_SHYAMA_VERSION, offlen);
offlen = hdr.writeUInt32LE(CLI_TYPE_REQ_RESP, offlen);
offlen = hdr.writeUInt32LE(gNodePort, offlen);
hdr.write(gNodeHost, offlen);
this.struct_ = hdr;
}
};
class NMConnectCmd
{
static structlen = 416;
constructor()
{
const hdr = Buffer.allocUnsafe(NMConnectCmd.structlen);
let offlen = 0;
hdr.fill(0);
offlen = hdr.writeBigUInt64LE(get_curr_sec_big(), 0);
offlen = hdr.writeUInt32LE(COMM_VERSION, offlen);
offlen = hdr.writeUInt32LE(NODE_VERSION, offlen);
offlen = hdr.writeUInt32LE(MIN_MADHAVA_VERSION, offlen);
offlen = hdr.writeUInt32LE(CLI_TYPE_REQ_RESP, offlen);
offlen = hdr.writeUInt32LE(gNodePort, offlen);
hdr.write(gNodeHost, offlen);
this.struct_ = hdr;
}
};
class RegisterResponse
{
static structlen = 424;
static parse_response(resp, server_string)
{
if (resp.length != RegisterResponse.structlen) {
throw new GyCommError(`ERROR : Invalid Register Response Size ${resp.length} seen for ${server_string}`);
}
let obj = {};
obj.error_code_ = resp.readUInt32LE(0);
obj.server_version_ = resp.readUInt32LE(4);
obj.server_id_ = resp.subarray(8, 40).toString();
if (obj.error_code_ != 0) {
throw new GyCommError(`ERROR : Registration to ${server_string} failed with Error Code ${obj.error_code_} : Error is ${resp.subarray(40, resp.indexOf(0, 40)).toString()}`);
}
return obj;
}
};
class QueryCmd
{
static structlen = 24;
constructor(seqid, timeout_secs = 100, jsontype = JsonMsgTypes.QUERY_WEB_JSON)
{
const hdr = Buffer.allocUnsafe(QueryCmd.structlen);
let offlen = 0;
switch (jsontype) {
case JsonMsgTypes.QUERY_WEB_JSON :
case JsonMsgTypes.CRUD_GENERIC_JSON :
case JsonMsgTypes.CRUD_ALERT_JSON :
break;
default :
jsontype = JsonMsgTypes.QUERY_WEB_JSON;
break;
}
offlen = hdr.writeBigUInt64LE(BigInt(seqid), 0);
offlen = hdr.writeBigUInt64LE(get_curr_sec_big(timeout_secs), offlen);
offlen = hdr.writeUInt32LE(jsontype, offlen);
offlen = hdr.writeUInt32LE(RESP_WEB_JSON, offlen);
this.struct_ = hdr;
}
static parse_req(req, server_string)
{
if (req.length < QueryCmd.structlen) {
throw new GyCommError(`ERROR : Invalid Query Cmd Size ${req.length} seen for ${server_string}`);
}
let obj = {};
obj.seqid_ = Number(req.readBigUInt64LE(0));
obj.timeoutmsec_ = Number(req.readBigUInt64LE(8)) * 1000;
obj.query_type_ = req.readUInt32LE(16);
obj.respformat_ = req.readUInt32LE(20);
// console.debug(`Received Query Request from ${server_string} : ${JSON.stringify(obj)}`);
return obj;
}
};
class QueryResponse
{
static structlen = 32;
constructor(seqid, errcode, resplen /* subsequent payload len */, is_resp_complete = true)
{
const hdr = Buffer.allocUnsafe(QueryResponse.structlen);
let offlen = 0;
offlen = hdr.writeBigUInt64LE(BigInt(seqid), 0);
offlen = hdr.writeUInt32LE(RESP_WEB_JSON, offlen);
offlen = hdr.writeUInt32LE(errcode, offlen);
offlen = hdr.writeUInt32LE(RESP_JSON_WITH_HEADER, offlen);
offlen = hdr.writeUInt32LE(resplen, offlen);
offlen = hdr.writeUInt32LE(0, offlen);
offlen = hdr.writeUInt32LE(is_resp_complete ? 1 : 0, offlen);
this.struct_ = hdr;
}
static parse_response(resp, server_string)
{
if (resp.length < QueryResponse.structlen) {
throw new GyCommError(`ERROR : Invalid Query Response Size ${resp.length} seen for ${server_string}`);
}
let obj = {};
obj.seqid_ = Number(resp.readBigUInt64LE(0));
obj.resp_type_ = resp.readUInt32LE(8);
obj.respcode_ = resp.readUInt32LE(12);
obj.respformat_ = resp.readUInt32LE(16);
obj.resp_len_ = resp.readUInt32LE(20);
obj.respflags_ = resp.readUInt32LE(24);
obj.is_resp_complete_ = resp.readUInt32LE(28);
return obj;
}
};
class EventNotify
{
static structlen = 8;
constructor(notify_type, nevents = 1)
{
const hdr = Buffer.allocUnsafe(EventNotify.structlen);
let offlen = 0;
offlen = hdr.writeUInt32LE(notify_type, 0);
offlen = hdr.writeUInt32LE(nevents, offlen);
this.struct_ = hdr;
}
static parse_event(evt, server_string)
{
if (evt.length < EventNotify.structlen) {
throw new GyCommError(`ERROR : Invalid Event Header Size ${evt.length} seen for ${server_string}`);
}
let obj = {};
obj.notify_type_ = evt.readUInt32LE(0);
obj.nevents_ = evt.readUInt32LE(4);
// console.debug(`Received Event Notify from ${server_string} : ${JSON.stringify(obj)}`);
return obj;
}
};
const GyConnStates =
{
Disconnected : 0,
Connected : 1,
Registered : 2,
Exiting : 3,
};
class ReqEventCallbacks
{
static MAX_CALLBACKS = 1024;
constructor()
{
this.cbmap_ = new Map();
}
set_callback(key, cb)
{
if (typeof key === 'string' && typeof cb === 'function' && this.cbmap_.size < ReqEventCallbacks.MAX_CALLBACKS) {
this.cbmap_.set(key, cb);
return true;
}
return false;
}
get_callback(key)
{
if (typeof key === 'string') {
return this.cbmap_.get(key);
}
return null;
}
delete_key(key)
{
this.cbmap_.delete(key);
}
num_callbacks()
{
return this.cbmap_.size;
}
};
const gcallbacklist = new ReqEventCallbacks();
function setReqEventCallback(key, cb)
{
return gcallbacklist.set_callback(key, cb);
}
setReqEventCallback('currtime', () => {
const m = moment();
return {
time_t : m.unix(),
time : m.format()
};
});
setReqEventCallback('parsefilter', (qry) => {
let data = qry.data;
if (safetypeof(data) !== 'string') {
return '';
}
if (qry.format && qry.format === 'object') {
return evaluateFilter(data);
}
else {
// Default is to encode the evaluateFilter output as a string. Note this is diff from a NodeMsgTypes.NODE_MSG_QUERY format
return JSON.stringify(evaluateFilter(data));
}
});
class RespPromise
{
constructor(conn, seqid, timeout_secs)
{
// Extend Promise to prevent Garbage Collection if Map entry deleted and Promise handler not executed yet
this.promise_ = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.then = this.promise_.then.bind(this.promise_);
this.catch = this.promise_.catch.bind(this.promise_);
this[Symbol.toStringTag] = 'Promise';
this.conn_ = conn;
this.seqid_ = seqid;
this.created_tmsec_ = Date.now();
this.timeout_secs_ = timeout_secs;
this.total_bytes_rcvd_ = 0;
this.resp_buf_arr_ = [];
this.last_resp_tmsec_ = 0;
this.is_complete_ = false;
}
push_response(resp, is_complete, respcode)
{
this.resp_buf_arr_.push(resp);
this.total_bytes_rcvd_ += resp.length;
this.last_resp_tmsec_ = Date.now();
/*console.debug(`Received Response chunk from ${this.conn_.conn_string_} seqid ${this.seqid_} of length ${resp.length} : Total Length ${this.total_bytes_rcvd_}\n`);*/
if (is_complete) {
this.is_complete_ = true;
this.resolve({respcode : respcode, data : this.resp_buf_arr_});
console.debug(`Response received from ${this.conn_.conn_string_} seqid ${this.seqid_} : Respcode ${respcode} : Response Time is ${this.last_resp_tmsec_ - this.created_tmsec_} msec `
+ `and length ${this.total_bytes_rcvd_} chars`);
}
}
signal_reject(reason = 'Errored Out', respcode = ErrorTypes.ERR_SERV_ERROR)
{
this.is_complete_ = true;
this.reject({respcode : respcode, data : [].push(reason)});
}
handle_timeout(currmsec = Date.now(), leewaymultiple = 0.0)
{
if (this.created_tmsec_ + (this.timeout_secs_ + leewaymultiple * this.timeout_secs_) * 1000 < currmsec) {
console.error(chalk.red(`Response Timed Out for query to ${this.conn_.conn_string_} seqid ${this.seqid_} : Waited ${currmsec - this.created_tmsec_} msec`));
this.signal_reject('Response Timed Out', ErrorTypes.ERR_TIMED_OUT);
return true;
}
return false;
}
};
class GyConn
{
static MAX_REQ_MULTIPLEX = 1024;
static MAX_REQ_SEQID = Number.MAX_SAFE_INTEGER - 1000;
static MAX_PENDING_WRITE_BYTES = 10 * 1024 * 1024;
constructor(server_host, server_port, is_madhava, conn_index, poolobj, to_reconnect = true, is_action_conn = false)
{
this.sock_ = null;
this.sockstate_ = GyConnStates.Disconnected;
this.server_host_ = server_host;
this.server_port_ = server_port;
this.is_madhava_ = is_madhava;
this.conn_index_ = conn_index;
this.poolobj_ = poolobj;
this.connect_timerid_ = null;
this.resp_map_ = new Map();
this.to_reconnect_ = to_reconnect;
this.is_action_conn_ = is_action_conn;
if (is_action_conn === true && is_madhava) {
throw new GyCommError(`Internal Error : Connection for Alert Action ${server_host} port ${server_port} specified but Conn Type set as Madhava`);
}
this.conn_string_ = (is_madhava ? 'Madhava' : 'Shyama');
if (is_action_conn === true) {
this.conn_string_ += ' Alertmgr';
}
this.conn_string_ += ` Host ${server_host} Port ${server_port} Conn #${conn_index}`;
this.req_seq_id_ = 0;
this.nmap_missed_ = 0;
this.lastsendmsec_ = 0;
this.lasttimeoutchk_ = 0;
this.nsends_ = 0;
this.nbytes_rcvd_ = 0;
this.hdr_ = {
data_type_ : 0,
total_sz_ : 0,
padding_sz_ : 0,
};
this.resp_data_ = null;
}
create_conn() {
if (this.sockstate_ === GyConnStates.Registered) {
return;
}
console.log(`Initiating Connection for ${this.conn_string_}`);
if (this.connect_timerid_ !== null) {
clearTimeout(this.connect_timerid_);
this.connect_timerid_ = null;
}
this.sock_ = net.createConnection({ port: this.server_port_, host: this.server_host_, timeout: 3000 }, () =>
{
console.log(`Connected to ${this.conn_string_} : Now starting Registration...`);
this.sockstate_ = GyConnStates.Connected;
this.connect_timerid_ = null;
this.sock_.this_ = this;
this.sock_.removeAllListeners('timeout');
try {
if (this.is_madhava_ === true) {
this.register_madhava();
}
else {
this.register_shyama();
}
}
catch (e) {
console.error(`Caught exception while registering to server for ${this.conn_string_} : ${e}\n${e?.stack}\n`);
this.destroy_conn();
}
});
this.sock_.once('timeout', () => {
console.error(`Connect Timed Out while connecting to ${this.conn_string_}. Will retry later...\n`);
this.sock_.destroy();
this.connect_timerid_ = setTimeout(() => {
this.connect_timerid_ = null;
this.create_conn();
}, 30 * 1000);
})
this.sock_.on('readable', () => {
do {
let chunkhdr, chunkdata, chunkpad, commhdr;
let nbytes = 0;
if (this.hdr_.total_sz_ === 0) {
// First read the header
chunkhdr = this.sock_.read(CommHeader.structlen);
if ((null === chunkhdr) || (chunkhdr.length < CommHeader.structlen)) {
// Non null indicates end of stream let end stream handler handle
return;
}
try {
let commhdr = CommHeader.parse_hdr(chunkhdr, this);
this.hdr_.total_sz_ = commhdr.total_sz_;
this.hdr_.data_type_ = commhdr.data_type_;
this.hdr_.padding_sz_ = commhdr.padding_sz_;
}
catch (e) {
console.error(`Exception caught while parsing Header for ${this.conn_string_} : ${e}\n${e?.stack}\n`);
this.destroy_conn();
}
}
const resplen = this.hdr_.total_sz_ - CommHeader.structlen;
chunkdata = this.sock_.read(resplen);
if ((null === chunkdata) || (chunkdata.length < resplen)) {
// Non null indicates end of stream let end stream handler handle
return;
}
try {
if (this.sockstate_ >= GyConnStates.Registered) {
if (this.hdr_.data_type_ === COMM_QUERY_RESP) {
this.handle_query_response(chunkdata);
}
else if (this.hdr_.data_type_ === COMM_EVENT_NOTIFY) {
this.handle_notification_event(chunkdata);
}
else if (this.hdr_.data_type_ === COMM_QUERY_CMD) {
this.handle_incoming_req(chunkdata);
}
else {
// Ignore
}
}
else {
let robj = RegisterResponse.parse_response(chunkdata, this.conn_string_);
this.sockstate_ = GyConnStates.Registered;
this.poolobj_.set_conn_valid(this.conn_index_, true, robj.server_id_, robj.server_version_);
console.log(`Registered Successfully with remote ${this.conn_string_}...`);
}
this.clear_data();
}
catch (e) {
console.error(`Exception caught while handling data from ${this.conn_string_} : ${e}\n${e?.stack}\n`);
this.destroy_conn();
return;
}
} while (true);
});
this.sock_.on('end', () => {
if (this.sockstate_ !== GyConnStates.Exiting) {
console.error(`Connection disconnected from server for ${this.conn_string_}.`);
this.destroy_conn();
}
});
this.sock_.on('error', () => {
if (this.sockstate_ !== GyConnStates.Exiting) {
if (this.sockstate_ !== GyConnStates.Disconnected) {
console.error(`Error Event Occured for Connection ${this.conn_string_}... Disconnecting`);
}
else {
console.info(`Failed to Connect to ${this.conn_string_}...`);
}
this.destroy_conn();
}
});
}
destroy_conn(destroy_completely = false)
{
if (this.sockstate_ === GyConnStates.Exiting) {
this.sock_.removeAllListeners();
if (destroy_completely === true) {
if (this.connect_timerid_ !== null) {
clearTimeout(this.connect_timerid_);
this.connect_timerid_ = null;
}
}
return;
}
this.sockstate_ = GyConnStates.Exiting;
this.sock_.removeAllListeners();
this.poolobj_.set_conn_valid(this.conn_index_, false, 0, 0);
try {
this.sock_.destroy();
console.debug(`Destroying Connection and clearing Connection Response Data Map for ${this.conn_string_}`);
this.signal_all_reject('Response Rejected as connection is closing');
// Schedule the map cleanup to enable promise callbacks
setImmediate((resp_map) => { resp_map.clear(); }, this.resp_map_);
if (this.connect_timerid_ !== null) {
clearTimeout(this.connect_timerid_);
this.connect_timerid_ = null;
}
}
catch (e) {
console.error(`Exception caught while destroying connection for ${this.conn_string_} : ${e}\n${e?.stack}\n`);
}
this.clear_data();
if (this.to_reconnect_ === true && destroy_completely === false) {
this.connect_timerid_ = setTimeout(() => {
console.log(`Initiating Connection Reconnect for ${this.conn_string_}`);
this.sockstate_ = GyConnStates.Disconnected;
this.connect_timerid_ = null;
this.create_conn();
}, 30 * 1000);
}
else if (destroy_completely) {
this.poolobj_ = undefined;
}
}
clear_data()
{
this.hdr_.total_sz_ = 0;
this.hdr_.data_type_ = 0;
this.hdr_.padding_sz_ = 0;
this.resp_data_ = null;
}
is_registered()
{
return (this.sockstate_ === GyConnStates.Registered);
}
is_write_allowed(max_pending_resp = GyConn.MAX_REQ_MULTIPLEX, max_pending_write_bytes = GyConn.MAX_PENDING_WRITE_BYTES)
{
return (this.sockstate_ === GyConnStates.Registered && this.resp_map_.size < max_pending_resp && this.sock_.writableLength < max_pending_write_bytes);
}
num_pending_responses()
{
return this.resp_map_.size;
}
handle_query_response(resp)
{
let rhdr = QueryResponse.parse_response(resp, this.conn_string_);
if (rhdr.seqid_ === 0) {
// Response to be ignored
return;
}
let mobj = this.resp_map_.get(rhdr.seqid_);
if (mobj === undefined) {
console.debug(`[ERROR]: Received Response for a query with non existent sequence ${rhdr.seqid_}\n`);
this.nmap_missed_++;
return;
}
let respdata = resp.subarray(QueryResponse.structlen, resp.length - this.hdr_.padding_sz_).toString('utf8');
if (rhdr.is_resp_complete_) {
this.resp_map_.delete(rhdr.seqid_);
}
mobj.push_response(respdata, rhdr.is_resp_complete_, rhdr.respcode_);
}
handle_incoming_req(req)
{
const rhdr = QueryCmd.parse_req(req, this.conn_string_);
const seqid = rhdr.seqid_;
let qryresp, errcode = ErrorTypes.ERR_SUCCESS;
try {
if (rhdr.query_type_ !== JsonMsgTypes.QUERY_WEB_JSON) {
errcode = ErrorTypes.ERR_INVALID_REQUEST;
qryresp = JSON.stringify({error : errcode, errmsg : `Incoming Request not of Web JSON Type`});
send_query_response(seqid, errcode, qryresp, true);
return;
}
/*
* We need the request to be an array of objects :
*
* Currently we support the following request types :
*
* 1. "currtime" : Output is of format [{id : "c1", time_t : 1628244881, data : "2021-08-06T15:46:34+05:30"}]
* 2. "parsefilter" : Output is of format [{id : "f1", data : '{ "data": "cpumem.oom_kill > 0", "hash": "b58d62683453060c" }' }]
*
* For Errors, the output is of format : {"error" : ErrorTypes.ERR_INVALID_REQUEST, "errmsg" : "Invalid Arguments"}
*
* e.g.
[
{type : "currtime", id : "c1" },
{type : "parsefilter", id : "f1", format : [can be "string"/"object"], data : "( ({ percentile(0.95, resp5s) > 100 }) or ({ percentile(0.95, qps5s) > 50 }) )" }
]
*
* The output JSON Array is first run through a JSON.stringify() and then sent as response
*/
let query = req.subarray(QueryCmd.structlen, req.length - this.hdr_.padding_sz_).toString('utf8');
if (query.length === 0) {
errcode = ErrorTypes.ERR_INVALID_REQUEST;
qryresp = JSON.stringify({error : errcode, errmsg : `Incoming Request has 0 length request`});
send_query_response(seqid, errcode, qryresp, true);
return;
}
let pqryarr = JSON.parse(query);
if (safetypeof(pqryarr) !== 'array') {
errcode = ErrorTypes.ERR_INVALID_REQUEST;
qryresp = JSON.stringify({error : errcode, errmsg : `Incoming Request not of an Array Type`});
send_query_response(seqid, errcode, qryresp, true);
return;
}
qryresp = [];
for (let i = 0; i < pqryarr.length; ++i) {
const qry = pqryarr[i];
if (safetypeof(qry) !== 'object') {
continue;
}
if (qry.type === undefined || qry.id === undefined) {
continue;
}
const cb = gcallbacklist.get_callback(qry.type);
if (typeof cb === 'function') {
qryresp.push({ id : qry.id, data : cb(qry) });
}
}
send_query_response(seqid, errcode, JSON.stringify({ data : qryresp }), true);
}
catch (e) {
errcode = ErrorTypes.ERR_SERV_ERROR;
qryresp = JSON.stringify({error : errcode, errmsg : `Exception caught while handling request : ${e}`});
send_query_response(seqid, errcode, qryresp, true);
console.debug(`[ERROR]: Exception caught while handling incoming request : ${e}\n`);
}
}
handle_notification_event(evt)
{
const rhdr = EventNotify.parse_event(evt, this.conn_string_);
if ((rhdr.notify_type_ !== NOTIFY_JSON_EVENT) || (rhdr.nevents_ !== 1)) {
// Not Handled : No Response to be sent
return;
}
try {
/*
* We need the event payload to be an object :
* e.g. { etype : "action", ...} // For Alert Action
*/
let notify = evt.subarray(EventNotify.structlen, evt.length - this.hdr_.padding_sz_).toString('utf8');
let eobj;
if (notify.length === 0) {
return;
}
try {
eobj = JSON.parse(notify);
}
catch (e) {
console.debug(`[ERROR]: Invalid JSON seen while handling incoming event notification : ${e} : Data : ${notify}\n`);
return;
}
if (safetypeof(eobj) !== 'object') {
return;
}
if (typeof eobj.etype !== 'string') {
return;
}
const cb = gcallbacklist.get_callback(eobj.etype);
if (typeof cb === 'function') {
cb(eobj);
}
}
catch (e) {
console.debug(`[ERROR]: Exception caught while handling incoming event notification : ${e}\n`);
}
}
signal_all_reject(reason)
{
for (let prom of this.resp_map_.values()) {
if (!prom.is_complete_) {
prom.signal_reject(reason);
}
}
}
// Internal API call
get_resp_promise(timeout_sec)
{
if (this.resp_map_.size > GyConn.MAX_REQ_MULTIPLEX) {
throw new GyCommError(`ERROR : Too Many Multiplexed Responses pending for ${this.conn_string_} : ${this.resp_map_.size}`);
}
this.req_seq_id_++;
if (this.req_seq_id_ > GyConn.MAX_REQ_SEQID) {
this.req_seq_id_ = 1;
}
const prom = new RespPromise(this, this.req_seq_id_, timeout_sec);