@nsshunt/stsappframework 3.0.104 → 3.0.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/influxdb/influxDBManager.js +16 -17
  2. package/dist/influxdb/influxDBManager.js.map +1 -1
  3. package/dist/influxdb/influxDBManagerAgent.js +9 -13
  4. package/dist/influxdb/influxDBManagerAgent.js.map +1 -1
  5. package/dist/influxdb/influxDBManagerBase.js +2 -6
  6. package/dist/influxdb/influxDBManagerBase.js.map +1 -1
  7. package/dist/influxdb/influxDBManagerService.js +10 -14
  8. package/dist/influxdb/influxDBManagerService.js.map +1 -1
  9. package/dist/instrumentationsubscriber.js +11 -15
  10. package/dist/instrumentationsubscriber.js.map +1 -1
  11. package/dist/kafka/IMKafkaManager.js +2 -6
  12. package/dist/kafka/IMKafkaManager.js.map +1 -1
  13. package/dist/kafkatesting/produce.js +1 -5
  14. package/dist/kafkatesting/produce.js.map +1 -1
  15. package/dist/processbase.js +7 -8
  16. package/dist/processbase.js.map +1 -1
  17. package/dist/server.js +1 -1
  18. package/dist/server.js.map +1 -1
  19. package/dist/tcpclient/app2.js +2 -2
  20. package/dist/tcpserver/appmaster.js +39 -16
  21. package/dist/tcpserver/appmaster.js.map +1 -1
  22. package/package.json +7 -7
  23. package/src/influxdb/influxDBManager.ts +16 -18
  24. package/src/influxdb/influxDBManagerAgent.ts +9 -11
  25. package/src/influxdb/influxDBManagerBase.ts +2 -4
  26. package/src/influxdb/influxDBManagerService.ts +10 -12
  27. package/src/instrumentationsubscriber.ts +11 -14
  28. package/src/kafka/IMKafkaManager.ts +2 -4
  29. package/src/kafkatesting/produce.ts +1 -3
  30. package/src/processbase.ts +7 -9
  31. package/src/server.ts +1 -1
  32. package/src/tcpclient/app2.ts +2 -2
  33. package/src/tcpserver/appmaster.ts +39 -17
  34. package/types/influxdb/influxDBManager.d.ts.map +1 -1
  35. package/types/influxdb/influxDBManagerAgent.d.ts.map +1 -1
  36. package/types/influxdb/influxDBManagerBase.d.ts.map +1 -1
  37. package/types/influxdb/influxDBManagerService.d.ts.map +1 -1
  38. package/types/instrumentationsubscriber.d.ts.map +1 -1
  39. package/types/kafka/IMKafkaManager.d.ts.map +1 -1
  40. package/types/processbase.d.ts +2 -2
  41. package/types/processbase.d.ts.map +1 -1
  42. package/types/tcpserver/appmaster.d.ts.map +1 -1
  43. package/src_working/authDefs.ts +0 -37
  44. package/src_working/authutilsnode.ts +0 -373
  45. package/src_working/commonTypes.ts +0 -239
  46. package/src_working/index.ts +0 -22
  47. package/src_working/influxdb/influxDBManager.ts +0 -970
  48. package/src_working/influxdb/influxDBManagerAgent.ts +0 -314
  49. package/src_working/influxdb/influxDBManagerBase.ts +0 -109
  50. package/src_working/influxdb/influxDBManagerService.ts +0 -373
  51. package/src_working/instrumentationsubscriber.ts +0 -283
  52. package/src_working/kafka/IMKafkaManager.ts +0 -152
  53. package/src_working/kafka/kafkaconsumer.ts +0 -82
  54. package/src_working/kafka/kafkamanager.ts +0 -186
  55. package/src_working/kafka/kafkaproducer.ts +0 -58
  56. package/src_working/kafkatesting/config.ts +0 -10
  57. package/src_working/kafkatesting/consume.ts +0 -116
  58. package/src_working/kafkatesting/produce.ts +0 -153
  59. package/src_working/masterprocessbase.ts +0 -598
  60. package/src_working/middleware/serverNetworkMiddleware.ts +0 -240
  61. package/src_working/network.ts +0 -36
  62. package/src_working/processbase.ts +0 -411
  63. package/src_working/processoptions.ts +0 -164
  64. package/src_working/publishertransports/publishTransportDirect.ts +0 -45
  65. package/src_working/publishertransports/publishTransportUtils.ts +0 -53
  66. package/src_working/server.ts +0 -141
  67. package/src_working/serverprocessbase.ts +0 -393
  68. package/src_working/singleprocessbase.ts +0 -121
  69. package/src_working/socketIoServerHelper.ts +0 -177
  70. package/src_working/stscontrollerbase.ts +0 -15
  71. package/src_working/stslatencycontroller.ts +0 -27
  72. package/src_working/stslatencyroute.ts +0 -16
  73. package/src_working/stsrouterbase.ts +0 -22
  74. package/src_working/tcpclient/app.ts +0 -19
  75. package/src_working/tcpclient/app2.ts +0 -56
  76. package/src_working/tcpserver/app.ts +0 -11
  77. package/src_working/tcpserver/appConfig.ts +0 -65
  78. package/src_working/tcpserver/appmaster.ts +0 -544
  79. package/src_working/validation/errors.ts +0 -6
  80. package/src_working/webworkertesting/app.ts +0 -49
  81. package/src_working/webworkertesting/worker.ts +0 -24
  82. package/src_working/workerprocessbase.test.ts +0 -47
  83. package/src_working/workerprocessbase.ts +0 -185
  84. package/src_working2/authDefs.ts +0 -37
  85. package/src_working2/authutilsnode.ts +0 -375
  86. package/src_working2/commonTypes.ts +0 -239
  87. package/src_working2/index.ts +0 -22
  88. package/src_working2/influxdb/influxDBManager.ts +0 -972
  89. package/src_working2/influxdb/influxDBManagerAgent.ts +0 -316
  90. package/src_working2/influxdb/influxDBManagerBase.ts +0 -111
  91. package/src_working2/influxdb/influxDBManagerService.ts +0 -375
  92. package/src_working2/instrumentationsubscriber.ts +0 -286
  93. package/src_working2/kafka/IMKafkaManager.ts +0 -154
  94. package/src_working2/kafka/kafkaconsumer.ts +0 -82
  95. package/src_working2/kafka/kafkamanager.ts +0 -186
  96. package/src_working2/kafka/kafkaproducer.ts +0 -58
  97. package/src_working2/kafkatesting/config.ts +0 -10
  98. package/src_working2/kafkatesting/consume.ts +0 -116
  99. package/src_working2/kafkatesting/produce.ts +0 -155
  100. package/src_working2/masterprocessbase.ts +0 -590
  101. package/src_working2/middleware/serverNetworkMiddleware.ts +0 -240
  102. package/src_working2/network.ts +0 -36
  103. package/src_working2/processbase.ts +0 -415
  104. package/src_working2/processoptions.ts +0 -164
  105. package/src_working2/publishertransports/publishTransportDirect.ts +0 -45
  106. package/src_working2/publishertransports/publishTransportUtils.ts +0 -53
  107. package/src_working2/server.ts +0 -141
  108. package/src_working2/serverprocessbase.ts +0 -393
  109. package/src_working2/singleprocessbase.ts +0 -123
  110. package/src_working2/socketIoServerHelper.ts +0 -177
  111. package/src_working2/stscontrollerbase.ts +0 -15
  112. package/src_working2/stslatencycontroller.ts +0 -27
  113. package/src_working2/stslatencyroute.ts +0 -16
  114. package/src_working2/stsrouterbase.ts +0 -22
  115. package/src_working2/tcpclient/app.ts +0 -19
  116. package/src_working2/tcpclient/app2.ts +0 -56
  117. package/src_working2/tcpserver/app.ts +0 -11
  118. package/src_working2/tcpserver/appConfig.ts +0 -65
  119. package/src_working2/tcpserver/appmaster.ts +0 -522
  120. package/src_working2/validation/errors.ts +0 -6
  121. package/src_working2/webworkertesting/app.ts +0 -49
  122. package/src_working2/webworkertesting/worker.ts +0 -24
  123. package/src_working2/workerprocessbase.test.ts +0 -47
  124. package/src_working2/workerprocessbase.ts +0 -187
@@ -1,375 +0,0 @@
1
- /* eslint @typescript-eslint/no-explicit-any: 0, @typescript-eslint/no-unused-vars: 0 */ // --> OFF
2
- // https://www.influxdata.com/blog/tldr-influxdb-tech-tips-multiple-aggregations-yield-flux/
3
- // https://www.influxdata.com/blog/top-5-hurdles-for-intermediate-flux-users-and-resources-for-optimizing-flux/
4
-
5
- /*
6
- option task = {
7
- name: "task-sts-service-stats",
8
- every: 1s,
9
- }
10
-
11
- data =
12
- from(bucket: "TestBucket01")
13
- |> range(start: -5s)
14
- |> last()
15
- |> filter(fn: (r) => r["_measurement"] == "service" and r["_field"] != "memory")
16
-
17
- r1 =
18
- data
19
- |> filter(
20
- fn: (r) =>
21
- r["_field"] == "requestCount" or r["_field"] == "errorCount" or r["_field"]
22
- ==
23
- "retryCount" or r["_field"] == "authenticationCount" or r["_field"]
24
- ==
25
- "activeRequestCount" or r["_field"] == "connectionCount" or r["_field"]
26
- ==
27
- "connectionPoolCount" or r["_field"] == "connectionIdleCount" or r["_field"]
28
- ==
29
- "connectionWaitingCount" or r["_field"] == "coreCount" or r["_field"] == "cpu"
30
- or
31
- r["_field"] == "systemcpu" or r["_field"] == "velocity" or r["_field"]
32
- ==
33
- "timer" or r["_field"] == "rx" or r["_field"] == "tx",
34
- )
35
-
36
- r2 =
37
- data
38
- |> filter(
39
- fn: (r) =>
40
- float(v: r["_value"]) > 0.0 and (r["_field"] == "duration" or r["_field"]
41
- ==
42
- "latency"),
43
- )
44
-
45
- serviceInstanceProcessSum =
46
- r1
47
- |> group(columns: ["serviceId", "serviceInstanceId", "serviceInstanceProcessId", "_field"])
48
- |> sum()
49
- |> toFloat()
50
-
51
- serviceInstanceProcessMean =
52
- r2
53
- |> group(columns: ["serviceId", "serviceInstanceId", "serviceInstanceProcessId", "_field"])
54
- |> mean()
55
- |> toFloat()
56
-
57
- union(tables: [serviceInstanceProcessSum, serviceInstanceProcessMean])
58
- |> map(fn: (r) => ({r with _time: now(), _measurement: "sts-stats-by-serviceinstanceprocess"}))
59
- |> to(org: "my-org", bucket: "TestBucket01")
60
-
61
- serviceInstanceSum =
62
- r1
63
- |> group(columns: ["serviceId", "serviceInstanceId", "_field"])
64
- |> sum()
65
- |> toFloat()
66
-
67
- serviceInstanceMean =
68
- r2
69
- |> group(columns: ["serviceId", "serviceInstanceId", "_field"])
70
- |> mean()
71
- |> toFloat()
72
-
73
- union(tables: [serviceInstanceSum, serviceInstanceMean])
74
- |> map(fn: (r) => ({r with _time: now(), _measurement: "sts-stats-by-serviceinstance"}))
75
- |> to(org: "my-org", bucket: "TestBucket01")
76
-
77
- serviceSum =
78
- r1
79
- |> group(columns: ["serviceId", "_field"])
80
- |> sum()
81
- |> toFloat()
82
-
83
- serviceMean =
84
- r2
85
- |> group(columns: ["serviceId", "_field"])
86
- |> mean()
87
- |> toFloat()
88
-
89
- union(tables: [serviceSum, serviceMean])
90
- |> map(fn: (r) => ({r with _time: now(), _measurement: "sts-stats-by-service"}))
91
- |> to(org: "my-org", bucket: "TestBucket01")
92
-
93
- globalServiceSum =
94
- r1
95
- |> group(columns: ["_field"])
96
- |> sum()
97
- |> toFloat()
98
-
99
- globalServiceMean =
100
- r2
101
- |> group(columns: ["_field"])
102
- |> mean()
103
- |> toFloat()
104
-
105
- union(tables: [globalServiceSum, globalServiceMean])
106
- |> map(fn: (r) => ({r with _time: now(), _measurement: "sts-stats-globalservice"}))
107
- |> to(org: "my-org", bucket: "TestBucket01")
108
-
109
- */
110
-
111
- import { Point, WriteApi, QueryApi } from '@influxdata/influxdb-client'
112
-
113
- import { Gauge, InstrumentVelocity } from '@nsshunt/stsinstrumentation'
114
-
115
- import { InfluxDBManagerBase } from './influxDBManagerBase'
116
-
117
- import { IInfluxDBManagerOptions, InstrumentPayload } from './../commonTypes'
118
- import { ISubscriptionPayload, ISubscriptionKey } from '@nsshunt/stssocketio-client'
119
-
120
- import chalk from 'chalk';
121
-
122
- const _logPrefix = 'InfluxDBManagerService:'
123
-
124
- /*
125
- const SERVICE_STATS_BY_SERVICE_INSTANCE_PROCESS = "sts-stats-sum-byserviceInstanceprocessid";
126
- const SERVICE_STATS_BY_SERVICE_INSTANCE = "sts-stats-sum-byserviceinstance";
127
- const SERVICE_STATS_BY_SERVICE = "sts-stats-sum-byservice";
128
- const SERVICE_STATS_GLOBAL = "sts-stats-sum";
129
- */
130
-
131
- const SERVICE_STATS_BY_SERVICE_INSTANCE_PROCESS = "sts-stats-by-serviceinstanceprocess";
132
- const SERVICE_STATS_BY_SERVICE_INSTANCE = "sts-stats-by-serviceinstance";
133
- const SERVICE_STATS_BY_SERVICE = "sts-stats-by-service";
134
- const SERVICE_STATS_GLOBAL = "sts-stats-globalservice";
135
-
136
- export class InfluxDBManagerService extends InfluxDBManagerBase
137
- {
138
- constructor(options: IInfluxDBManagerOptions, queryApi: QueryApi) {
139
- super(options, queryApi);
140
- }
141
-
142
- override get modelType(): string {
143
- return 'service'
144
- }
145
-
146
- // Queries --------------------------------------------------------------------------------------------------------
147
-
148
- /*
149
- data = from(bucket: "my-bucket")
150
- |> range(start: -task.every)
151
- |> filter(fn: (r) => r._measurement == "my_measurement")
152
-
153
- data
154
- |> mean()
155
- |> set(key: "agg_type",value: "mean_temp")
156
- |> to(bucket: "downsampled", org: "my-org", tagColumns: ["agg_type"])
157
-
158
- data
159
- |> count()
160
- |> set(key: "agg_type",value: "count_temp")
161
- |> to(bucket: "downsampled", org: "my-org", tagColumns: ["agg_type"])
162
- */
163
-
164
- #GetSTSCountGenericService = async (measurement: string, filterClause: string, showOutput: boolean = false): Promise<any> => {
165
- try {
166
- const query = `r1 = from(bucket: "${this.options.bucket}")
167
- |> range(start: -5s)
168
- |> last()
169
- |> filter(fn: (r) => r["_measurement"] == "${measurement}" ${filterClause})
170
-
171
- r2 = from(bucket: "${this.options.bucket}")
172
- |> range(start: -5s)
173
- |> last()
174
- |> filter(fn: (r) => r["_measurement"] == "service" ${filterClause} and r["_field"] == "memory")
175
-
176
- union(tables: [r1, r2])`;
177
-
178
- if (showOutput) {
179
- console.log(query);
180
- }
181
-
182
- return this.queryApi.collectRows(query)
183
- } catch (error) {
184
- console.error(chalk.red(`${_logPrefix}#GetSTSCountGeneric: Error: [${error}]`));
185
- }
186
- }
187
-
188
- // Histo metrics
189
- #GetSTSHistoGenericService = async (measurement: string, filterClause: string): Promise<any> => {
190
- try {
191
- const query = `import "math"
192
- from(bucket: "${this.options.bucket}")
193
- |> range(start: -10m)
194
- |> filter(fn: (r) => r["_measurement"] == "${measurement}" and (r["_field"] =="latency" or
195
- r["_field"] =="duration") ${filterClause})
196
- |> histogram(bins: [0.0, 10.0, 20.0, 50.0, 100.0, 1000.0, 50000.0, math.mInf(sign: 1) ])
197
- |> difference()`;
198
- return this.queryApi.collectRows(query)
199
- } catch (error) {
200
- console.error(chalk.red(`${_logPrefix}#GetSTSHistoGeneric: Error: [${error}]`));
201
- }
202
- }
203
-
204
- // Quantile metrics
205
- #GetSTSQuantileGenericService = async (measurement: string, filterClause: string): Promise<any> => {
206
- try {
207
- const query = `data = from(bucket: "${this.options.bucket}")
208
- |> range(start: -10m)
209
- |> filter(fn: (r) => r["_measurement"] == "${measurement}" and (r["_field"] == "latency" or
210
- r["_field"] == "duration" or
211
- r["_field"] == "cpu" or
212
- r["_field"] == "systemcpu") ${filterClause})
213
- |> aggregateWindow(every: 5s, fn: max, createEmpty: false)
214
-
215
- dostsquantileex = (q) =>
216
- data
217
- |> quantile(q: q, method: "estimate_tdigest", compression: 1000.0)
218
- |> set(key: "quantile", value: string(v:q))
219
- |> group(columns: ["quantile"])
220
-
221
- union(tables: [
222
- dostsquantileex(q: 0.5),
223
- dostsquantileex(q: 0.8),
224
- dostsquantileex(q: 0.9),
225
- dostsquantileex(q: 0.95),
226
- dostsquantileex(q: 0.99)
227
- ])`;
228
-
229
- return this.queryApi.collectRows(query)
230
- } catch (error) {
231
- console.error(chalk.red(`${_logPrefix}#GetSTSQuantileGeneric: Error: [${error}]`));
232
- }
233
- }
234
-
235
- // Metric queries -------------------------------------------------------------------------------------------------
236
- // Root level metrics
237
- async GetInfluxDBResultsRootService(subscriptionKey: ISubscriptionKey): Promise<ISubscriptionPayload> {
238
- let retVal = null;
239
- try {
240
- retVal = await this.ProcessInfluxDBResults([
241
- this.#GetSTSCountGenericService(SERVICE_STATS_GLOBAL, ''),
242
- this.#GetSTSQuantileGenericService(SERVICE_STATS_GLOBAL, ''),
243
- this.#GetSTSHistoGenericService(SERVICE_STATS_GLOBAL, '')],
244
- [ ])
245
- } catch (error) {
246
- console.error(chalk.red(`${_logPrefix}GetInfluxDBResultsRoot: Error: [${error}]`));
247
- }
248
- return {
249
- subscriptionKey,
250
- data: retVal
251
- };
252
- }
253
-
254
- // Service level metrics
255
- async GetInfluxDBResultsService(subscriptionKey: ISubscriptionKey): Promise<ISubscriptionPayload> {
256
- let retVal = null;
257
- try {
258
- retVal = await this.ProcessInfluxDBResults([
259
- this.#GetSTSCountGenericService(SERVICE_STATS_BY_SERVICE, ''),
260
- this.#GetSTSQuantileGenericService(SERVICE_STATS_BY_SERVICE, ''),
261
- this.#GetSTSHistoGenericService(SERVICE_STATS_BY_SERVICE, '')],
262
- ['serviceId'])
263
- } catch (error) {
264
- console.error(chalk.red(`${_logPrefix}GetInfluxDBResultsService: Error: [${error}]`));
265
- }
266
- return {
267
- subscriptionKey,
268
- data: retVal
269
- };
270
-
271
- }
272
-
273
- // Service instance metrics for a particular service type
274
- async GetInfluxDBResultsServiceInstances(subscriptionKey: ISubscriptionKey): Promise<ISubscriptionPayload> {
275
- let retVal = null;
276
- try {
277
- const serviceId = subscriptionKey.key as string;
278
- retVal = await this.ProcessInfluxDBResults([
279
- this.#GetSTSCountGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE, `and r["serviceId"] == "${serviceId}"`),
280
- this.#GetSTSQuantileGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE, `and r["serviceId"] == "${serviceId}"`),
281
- this.#GetSTSHistoGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE, `and r["serviceId"] == "${serviceId}"`)],
282
- ['serviceId', 'serviceInstanceId'])
283
- } catch (error) {
284
- console.error(chalk.red(`${_logPrefix}GetInfluxDBResultsServiceInstances: Error: [${error}]`));
285
- }
286
- return {
287
- subscriptionKey,
288
- data: retVal
289
- };
290
- }
291
-
292
- // Service instance thread metrics for a particular service instance
293
- async GetInfluxDBResultsServiceInstance(subscriptionKey: ISubscriptionKey): Promise<ISubscriptionPayload> {
294
- let retVal = null;
295
- try {
296
- const serviceInstanceId = subscriptionKey.key as string;
297
- retVal = await this.ProcessInfluxDBResults([
298
- this.#GetSTSCountGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE_PROCESS, `and r["serviceInstanceId"] == "${serviceInstanceId}"`),
299
- this.#GetSTSQuantileGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE_PROCESS, `and r["serviceInstanceId"] == "${serviceInstanceId}"`),
300
- this.#GetSTSHistoGenericService(SERVICE_STATS_BY_SERVICE_INSTANCE_PROCESS, `and r["serviceInstanceId"] == "${serviceInstanceId}"`)],
301
- ['serviceId', 'serviceInstanceId', 'serviceInstanceProcessId'])
302
- } catch (error) {
303
- console.error(chalk.red(`${_logPrefix}GetInfluxDBResultsServiceInstance: Error: [${error}]`));
304
- }
305
- return {
306
- subscriptionKey,
307
- data: retVal
308
- };
309
- }
310
-
311
- // Write data points ----------------------------------------------------------------------------------------------
312
- // Agent context payload
313
- // {"nid":"somehost@e58f5d75-6ff6-4e04-92a4-f2bcd722fec0-someuseragent|MainProcess|0","id":"somehost@e58f5d75-6ff6-4e04-92a4-f2bcd722fec0-someuseragent|MainProcess|0","hostName":"somehost","agentName":"e58f5d75-6ff6-4e04-92a4-f2bcd722fec0-someuseragent","threadId":"MainProcess","asyncRunnerId":"0"}
314
- async OutputInfluxDB(writeApi: WriteApi, instrumentPayload: InstrumentPayload): Promise<boolean> {
315
- if (writeApi) {
316
- try {
317
- if (this.shuttingDown) {
318
- return false;
319
- }
320
-
321
- const { serviceId, serviceInstanceId, hostName, serviceInstanceProcessId,
322
- pid, ppid, serviceName, serviceVersion } = instrumentPayload.context;
323
-
324
- let systemcpu = 0.0;
325
- if (instrumentPayload.instruments[Gauge.CPU_SYSTEM_LOAD_GAUGE]) {
326
- systemcpu = (instrumentPayload.instruments[Gauge.CPU_SYSTEM_LOAD_GAUGE].val as number);
327
- }
328
-
329
- const point = new Point('all')
330
- .measurement('service')
331
- // Context settings
332
- .tag('serviceId', serviceId as string)
333
- .tag('serviceName', serviceName as string)
334
- .tag('serviceVersion', serviceVersion as string)
335
- .tag('serviceInstanceId', serviceInstanceId as string)
336
- .tag('serviceInstanceProcessId', serviceInstanceProcessId as string)
337
- .tag('hostName', hostName as string)
338
- .tag('pid', (pid as number).toString())
339
- .tag('ppid', (ppid as number).toString())
340
- // Data fields
341
- .intField('requestCount', instrumentPayload.instruments[Gauge.REQUEST_COUNT_GAUGE].val)
342
- .intField('errorCount', instrumentPayload.instruments[Gauge.ERROR_COUNT_GAUGE].val)
343
- .intField('retryCount', instrumentPayload.instruments[Gauge.RETRY_COUNT_GAUGE].val)
344
- .intField('authenticationCount', instrumentPayload.instruments[Gauge.AUTHENTICATION_COUNT_GAUGE].val)
345
- .floatField('velocity', (instrumentPayload.instruments[Gauge.VELOCITY_GAUGE] as InstrumentVelocity).va) // Note: Using va not val here
346
- .floatField('cpu', instrumentPayload.instruments[Gauge.CPU_LOAD_GAUGE].val)
347
- .intField('activeRequestCount', instrumentPayload.instruments[Gauge.ACTIVE_REQUEST_GAUGE].val)
348
- .intField('connectionCount', instrumentPayload.instruments[Gauge.CONNECTION_COUNT_GAUGE].val)
349
- .intField('connectionPoolCount', instrumentPayload.instruments[Gauge.CONNECTION_POOL_TOTAL_GAUGE].val)
350
- .intField('connectionIdleCount', instrumentPayload.instruments[Gauge.CONNECTION_POOL_IDLE_GAUGE].val)
351
- .intField('connectionWaitingCount', instrumentPayload.instruments[Gauge.CONNECTION_POOL_WAITING_GAUGE].val)
352
- .intField('coreCount', instrumentPayload.instruments[Gauge.CORE_COUNT_GAUGE].val)
353
- //.intField('rx', instrumentPayload.instruments[Gauge.NETWORK_RX_GAUGE].val)
354
- //.intField('tx', instrumentPayload.instruments[Gauge.NETWORK_TX_GAUGE].val)
355
- .floatField('rx', (instrumentPayload.instruments[Gauge.NETWORK_RX_GAUGE] as InstrumentVelocity).va) // Note: Using va not val here
356
- .floatField('tx', (instrumentPayload.instruments[Gauge.NETWORK_TX_GAUGE] as InstrumentVelocity).va) // Note: Using va not val here
357
- .floatField('timer', instrumentPayload.instruments[Gauge.TIMER_GAUGE].val)
358
- .floatField('duration', instrumentPayload.instruments[Gauge.DURATION_GAUGE].val)
359
- .floatField('latency', instrumentPayload.instruments[Gauge.LATENCY_GAUGE].val)
360
- .floatField('systemcpu', systemcpu)
361
- .stringField('memory', JSON.stringify(instrumentPayload.instruments[Gauge.OBJECT_GAUGE].val))
362
-
363
- writeApi.writePoint(point);
364
- return true;
365
- } catch (error: any) {
366
- console.error(chalk.red(`${_logPrefix}OutputInfluxDB: Could not write data point: [${error}]`));
367
- console.error(chalk.red(`${JSON.stringify(instrumentPayload.context)}`));
368
- return false;
369
- }
370
- } else {
371
- console.error(chalk.red(`${_logPrefix}OutputInfluxDBService: Could not write data point as writeClient is null`));
372
- return false;
373
- }
374
- }
375
- }
@@ -1,286 +0,0 @@
1
- import { IKafkaConsumer, logFunction } from './commonTypes'
2
- import { ISubscriptionPayload, ISubscriptionKey, SubscriptionTopic, IKafkaData } from '@nsshunt/stssocketio-client'
3
-
4
- import { KafkaManager, IKafkaManagerConfig } from './kafka/kafkamanager'
5
- import { InfluxDBManager } from './influxdb/influxDBManager'
6
- import { v4 as uuidv4 } from 'uuid';
7
-
8
- import { $Options } from '@nsshunt/stsconfig'
9
- import { STSOptionsBase } from '@nsshunt/stsutils';
10
-
11
- import chalk from 'chalk';
12
-
13
- const goptions = $Options()
14
-
15
- declare interface IKafkaSubscription {
16
- kafkaTopic: string
17
- kafkaGroupId: string
18
- kafkaConsumer: IKafkaConsumer
19
- kafkaFromBeginning: boolean
20
- }
21
-
22
- declare interface ISubscription {
23
- subscriptionKey: ISubscriptionKey
24
- kafka?: IKafkaSubscription
25
- cb: (payload: ISubscriptionPayload) => void
26
- }
27
-
28
- declare type ISubscriptions = Record<string, ISubscription>;
29
-
30
- export interface IInstrumentationSubscriberOptions {
31
- SubscriptionInterval: number
32
- logger?: logFunction
33
- }
34
-
35
- export class InstrumentationSubscriber extends STSOptionsBase {
36
- #subscriptions: ISubscriptions = { };
37
- #influxDBManager: InfluxDBManager;
38
- #interval: NodeJS.Timer | null = null;
39
- #km: KafkaManager;
40
- #logger: logFunction | null = null;
41
-
42
- constructor(options: IInstrumentationSubscriberOptions) {
43
- super(options);
44
-
45
- if (options.logger) {
46
- this.#logger = options.logger;
47
- }
48
-
49
- this.#influxDBManager = new InfluxDBManager();
50
-
51
- const kmc: IKafkaManagerConfig = {
52
- clientId: `${goptions.kafka_clientId}_${uuidv4()}`,
53
- brokers: goptions.kafka_brokers.split(','),
54
- keepAlive: goptions.kafka_keep_alive,
55
- adminTimeout: goptions.kafka_admin_timeout,
56
- connectionTimeout: goptions.kafka_connection_timeout,
57
- logLevel: goptions.kafka_log_level,
58
- useSSL: goptions.kafka_use_ssl,
59
- requestTimeout: goptions.kafka_request_timeout
60
- }
61
- if (goptions.kafka_use_ssl) {
62
- kmc.ssl = {
63
- rejectUnauthorized: goptions.kafka_ssl_rejectUnauthorized,
64
- cafile: goptions.kafka_ssl_cafile,
65
- certfileFile: goptions.kafka_ssl_certfile,
66
- keyfile: goptions.kafka_ssl_keyfile
67
- }
68
- }
69
- this.#km = new KafkaManager(kmc);
70
- }
71
-
72
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
73
- #Log(msg: any): void {
74
- if (this.#logger) {
75
- this.#logger(msg);
76
- } else {
77
- console.log(msg);
78
- }
79
- }
80
-
81
- async #UnSubscribeKafka(subscription: ISubscription): Promise<void> {
82
- const unsubscribeKafka = async () => {
83
- const kafka = subscription.kafka;
84
- if (kafka) {
85
- // Un-Subscribe from this kafka topic
86
- this.#Log(chalk.yellow(`InstrumentationSubscriber:#UnSubscribeKafka(): Unsubscribe from Kafka topc: [${kafka.kafkaTopic}] Starting`));
87
- await kafka.kafkaConsumer?.Stop();
88
- await kafka.kafkaConsumer?.Disconnect();
89
- this.#Log(chalk.yellow(`InstrumentationSubscriber:#UnSubscribeKafka(): Unsubscribe from Kafka topc: [${kafka.kafkaTopic}] Completed.`));
90
- } else {
91
- this.#Log(chalk.magenta(`InstrumentationSubscriber:#UnSubscribeKafka(): Kafka details do not exist for this topc: [${JSON.stringify(subscription.subscriptionKey)}].`));
92
- }
93
- };
94
- return unsubscribeKafka();
95
- }
96
-
97
- async #SubscribeKafka(subscription: ISubscription): Promise<void> {
98
- const kafkaSubscribe = async () => {
99
- if (subscription.subscriptionKey.id) {
100
-
101
- const kafkaSafeKey = `${subscription.subscriptionKey.key}`.replace(/@/g, '_').replace(/\|/g, '_');
102
-
103
- const kafkaGroupId = uuidv4();
104
- subscription.kafka = {
105
- kafkaTopic: kafkaSafeKey,
106
- kafkaGroupId: kafkaGroupId,
107
- kafkaConsumer: this.#km.CreateConsumer(kafkaGroupId),
108
- kafkaFromBeginning: goptions.kafka_consume_from_beginning
109
- };
110
- this.#Log(`InstrumentationSubscriber:#SubscribeKafka(): Subscribe to Kafka topc: [${subscription.kafka.kafkaTopic}] Starting`.yellow)
111
-
112
- const kafka = subscription.kafka;
113
- await kafka.kafkaConsumer.Connect();
114
- await kafka.kafkaConsumer.Subscribe([kafka.kafkaTopic], subscription.kafka.kafkaFromBeginning );
115
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
116
- await kafka.kafkaConsumer.StartConsumingMessages((topic, key, partition, value, headers) => {
117
- try {
118
- if (key != "" && value != "") {
119
- if (topic.localeCompare(key) === 0) {
120
- subscription.cb({
121
- subscriptionKey: subscription.subscriptionKey,// Original requested topic (may be kafka un-safe)
122
- data: {
123
- kafkaTopic: kafka.kafkaTopic, // Safe kafka topic key with prefix. kafkaTopic, topic and key should be same value
124
- kafkaGroupId: kafka.kafkaGroupId,
125
- partition,
126
- topic, // kafkaTopic, topic and key should be same value
127
- key, // kafkaTopic, topic and key should be same value
128
- value
129
- } as IKafkaData
130
- });
131
- } else {
132
- this.#Log(chalk.red(`InstrumentationSubscriber:#SubscribeKafka(): Invalid message format from Kafka data, topic: [${topic}] and key: [${key}] do not match`));
133
- }
134
- } else {
135
- this.#Log(chalk.red(`InstrumentationSubscriber:#SubscribeKafka(): Invalid message format from Kafka data, topic: [${topic}], key: [${key}], value: [${value}]`));
136
- }
137
- } catch (error) {
138
- this.#Log(chalk.red(`InstrumentationSubscriber:#SubscribeKafka(): Error: [${error}]`));
139
- }
140
- });
141
- this.#Log(chalk.yellow(`InstrumentationSubscriber:#SubscribeKafka(): Subscribe to Kafka topc: [${kafka.kafkaTopic}] Completed`));
142
- } else {
143
- this.#Log(chalk.magenta(`InstrumentationSubscriber:#SubscribeKafka(): Could not subscribe to Kafka topc, missing combinedKey for topic: [${JSON.stringify(subscription.subscriptionKey)}]`));
144
- }
145
- }
146
- return kafkaSubscribe();
147
- }
148
-
149
- async #OutputSubscription(subscription: ISubscription): Promise<ISubscriptionPayload> {
150
- // Service subscriptions
151
- const { subscriptionKey } = subscription;
152
- switch (subscriptionKey.topic) {
153
- // Services -------------------------------------------------------------------------------------------
154
- case SubscriptionTopic.AllServicesCombined :
155
- return this.#influxDBManager.serviceManager.GetInfluxDBResultsRootService(subscriptionKey);
156
- case SubscriptionTopic.Services :
157
- return this.#influxDBManager.serviceManager.GetInfluxDBResultsService(subscriptionKey);
158
- case SubscriptionTopic.ServiceInstances :
159
- if (subscriptionKey.key) { // key = service_id
160
- return this.#influxDBManager.serviceManager.GetInfluxDBResultsServiceInstances(subscriptionKey);
161
- } else {
162
- throw new Error(`#OutputSubscription: key not provided for subscription: [${JSON.stringify(subscriptionKey)}]`);
163
- }
164
- case SubscriptionTopic.ServiceInstance :
165
- if (subscriptionKey.key) { // key = service instance id
166
- return this.#influxDBManager.serviceManager.GetInfluxDBResultsServiceInstance(subscriptionKey);
167
- } else {
168
- throw new Error(`#OutputSubscription: key not provided for subscription: [${JSON.stringify(subscriptionKey)}]`);
169
- }
170
-
171
- // User Agents -------------------------------------------------------------------------------------------
172
- case SubscriptionTopic.AllAgentsCombined :
173
- return this.#influxDBManager.agentManager.GetInfluxDBResultsRootAgent(subscriptionKey);
174
- case SubscriptionTopic.Agents :
175
- return this.#influxDBManager.agentManager.GetInfluxDBResultsAgent(subscriptionKey);
176
- case SubscriptionTopic.AgentWorkers :
177
- if (subscriptionKey.key) { // key = agent instance id
178
- return this.#influxDBManager.agentManager.GetInfluxDBResultsAgentThreads(subscriptionKey);
179
- } else {
180
- throw new Error(`#OutputSubscription: key not provided for subscription: [${JSON.stringify(subscriptionKey)}]`);
181
- }
182
- case SubscriptionTopic.AgentWorker :
183
- if (subscriptionKey.key && subscriptionKey.subkey) { // key = agent instance id, subkey = agent instance worker id
184
- return this.#influxDBManager.agentManager.GetInfluxDBResultsAgentThread(subscriptionKey);
185
- } else {
186
- throw new Error(`#OutputSubscription: key and/or subkey not provided for subscription: [${JSON.stringify(subscriptionKey.topic)}]`);
187
- }
188
-
189
- // Logging (both service and agent) -----------------------------------------------------------------------
190
- case SubscriptionTopic.LogProcessing :
191
- // Kafka processing will be handled by a dedicated kafka run consumer
192
- return { subscriptionKey, data: null };
193
- default :
194
- return { subscriptionKey, data: null };
195
- }
196
- }
197
-
198
- #ExecuteSubscriptions = async () => {
199
- const promArray: Promise<ISubscriptionPayload>[] = [ ];
200
- const indexArray: ISubscription[] = [ ];
201
-
202
- for (const [, subscription] of Object.entries(this.#subscriptions)) {
203
- // If NOT Kafka, go get the data from influxdb
204
- if (subscription.subscriptionKey.topic.localeCompare(SubscriptionTopic.LogProcessing.toString()) !== 0) {
205
- promArray.push(this.#OutputSubscription(subscription));
206
- indexArray.push(subscription);
207
- }
208
- }
209
- const retVal = await Promise.all(promArray);
210
- try {
211
- for (let i=0; i < retVal.length; i++) {
212
- // Provided we have data, invoke the callback
213
- if (retVal[i].data) {
214
- indexArray[i].cb(retVal[i]);
215
- }
216
- }
217
- } catch (error) {
218
- this.#Log(chalk.red(`InstrumentationSubscriber:#ExecuteSubscriptions(): Error: [${error}], [${JSON.stringify(retVal)}]`));
219
- }
220
- }
221
-
222
- Subscribe(subscriptionKey: ISubscriptionKey, cb: (payload: ISubscriptionPayload) => void) {
223
- if (this.#interval) {
224
- clearInterval(this.#interval);
225
- this.#interval = null;
226
- }
227
- if (this.#subscriptions[subscriptionKey.id]) {
228
- // Subscription already exists - ignoring
229
- this.#Log(chalk.magenta(`InstrumentationSubscriber.Subscribe(): Subscription already exists: [${subscriptionKey.id}] - ignoring.`));
230
- } else {
231
- this.#subscriptions[subscriptionKey.id] = {
232
- subscriptionKey,
233
- cb
234
- }
235
- if (subscriptionKey.topic.localeCompare(SubscriptionTopic.LogProcessing) === 0) {
236
- this.#SubscribeKafka(this.#subscriptions[subscriptionKey.id]);
237
- }
238
- this.#Log(`InstrumentationSubscriber.Subscribe(): subscriptionKey.id: [${subscriptionKey.id}] successfully subscribed.`.grey);
239
-
240
- if (!this.#interval) {
241
- // Output subscription immediately and then iterate ...
242
- this.#ExecuteSubscriptions();
243
- let interval = 1000; // default
244
- if (this.options) {
245
- interval = this.options.SubscriptionInterval
246
- }
247
- this.#interval = setInterval(() => {
248
- this.#ExecuteSubscriptions();
249
- }, interval);
250
- }
251
- }
252
- }
253
-
254
- UnSubscribe(subscriptionKey: ISubscriptionKey) {
255
- if (!this.#subscriptions[subscriptionKey.id]) {
256
- this.#Log(chalk.magenta(`UnSubscribe(): Warning, subscriptionKey.id: [${subscriptionKey.id}] does not exist within subscription records`));
257
- } else {
258
- if (subscriptionKey.topic.localeCompare(SubscriptionTopic.LogProcessing) === 0) {
259
- this.#UnSubscribeKafka(this.#subscriptions[subscriptionKey.id]);
260
- }
261
- delete this.#subscriptions[subscriptionKey.id];
262
-
263
- if (Object.keys(this.#subscriptions).length === 0) {
264
- if (this.#interval) {
265
- clearInterval(this.#interval);
266
- this.#interval = null;
267
- }
268
- }
269
- }
270
- }
271
-
272
- #UnSubscribeAll() {
273
- for (const [, subscription] of Object.entries(this.#subscriptions)) {
274
- this.UnSubscribe(subscription.subscriptionKey);
275
- }
276
- }
277
-
278
- async Start() {
279
- return this.#influxDBManager.Start();
280
- }
281
-
282
- async Stop() {
283
- this.#UnSubscribeAll();
284
- return this.#influxDBManager.Terminate();
285
- }
286
- }