whatap 2.0.6 → 2.0.7
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.
- package/README.md +23 -0
- package/help.txt +5 -0
- package/index.js +17 -2
- package/lib/conf/config-default.js +2 -0
- package/lib/core/agent.js +26 -0
- package/lib/udp/async_sender.js +181 -41
- package/lib/udp/packet_queue.js +25 -7
- package/lib/udp/udp_session.js +20 -2
- package/lib/util/launcher.js +102 -0
- package/package.json +2 -2
- package/.claude/settings.local.json +0 -62
- package/.vscode/keep-context.json +0 -4
package/README.md
CHANGED
|
@@ -33,6 +33,18 @@ app_name=MyNodeApp # Application name
|
|
|
33
33
|
app_process_name=node # Process name
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
Optional settings:
|
|
37
|
+
|
|
38
|
+
```ini
|
|
39
|
+
# UDP send loop between the agent and whatap_nodejs (default: true).
|
|
40
|
+
# true : drains the send queue in bounded batches (supports high TPS)
|
|
41
|
+
# false : legacy sender, one packet per timer tick (limited to roughly 700~1000 packets/s)
|
|
42
|
+
udp_send_batch_enabled=true
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Only `true` / `false` are recognized, and the value must not be followed by a comment on the same line.
|
|
46
|
+
Changes in `whatap.conf` are applied without a restart (at the next configuration reload, about 10 seconds).
|
|
47
|
+
|
|
36
48
|
|
|
37
49
|
|
|
38
50
|
## 🚀 Usage
|
|
@@ -69,6 +81,17 @@ If you prefer not to modify your application code, you can use the `-r` flag:
|
|
|
69
81
|
node -r whatap app.js
|
|
70
82
|
```
|
|
71
83
|
|
|
84
|
+
The same applies when the agent is injected through `NODE_OPTIONS="-r whatap"` (for example by the WhaTap Operator).
|
|
85
|
+
Package manager launcher processes (`npm`, `npx`, `yarn`, `pnpm`, `corepack`) inherit `NODE_OPTIONS` too, but they are not your
|
|
86
|
+
application, so the agent skips them automatically and is initialized only in the application process
|
|
87
|
+
(e.g. `npm run start` -> `next start`).
|
|
88
|
+
|
|
89
|
+
| Environment variable | Description |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `WHATAP_FORCE_INIT=true` | Always initialize the agent, even if the process looks like a package manager launcher or is listed in `WHATAP_EXCLUDE_PROCESS` (only the value `true` is recognized) |
|
|
92
|
+
| `WHATAP_EXCLUDE_PROCESS=cross-env,nodemon` | Comma separated entry script names (besides the package managers) that must not initialize the agent. Names are compared without directory and extension, case-insensitively |
|
|
93
|
+
| `WHATAP_PRINT=1` | Prints a one-line notice to stderr when the agent skips a process |
|
|
94
|
+
|
|
72
95
|
### ECMAScript Module (ESM) System
|
|
73
96
|
|
|
74
97
|
```javascript
|
package/help.txt
CHANGED
|
@@ -8,3 +8,8 @@ WhatapAgent.plugin("extra", function(pack){
|
|
|
8
8
|
pack.putInt(9001,41);
|
|
9
9
|
});
|
|
10
10
|
|
|
11
|
+
|
|
12
|
+
//NODE_OPTIONS="-r whatap" 로 에이전트를 주입하는 경우 (예: Operator 자동 주입)
|
|
13
|
+
//npm/npx/yarn/pnpm/corepack 런처 프로세스는 자동으로 초기화에서 제외되고 실제 앱 프로세스에서만 초기화됩니다.
|
|
14
|
+
//런처가 아닌데 제외되는 경우 강제로 초기화: WHATAP_FORCE_INIT=true
|
|
15
|
+
//런처 외에 초기화를 제외할 진입 스크립트 이름(쉼표 구분): WHATAP_EXCLUDE_PROCESS=cross-env,nodemon
|
package/index.js
CHANGED
|
@@ -4,5 +4,20 @@
|
|
|
4
4
|
* can be found in the LICENSE file.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
var launcher = require('./lib/util/launcher');
|
|
8
|
+
|
|
9
|
+
if (launcher.isCurrentProcessLauncher()) {
|
|
10
|
+
// npm/npx/yarn/pnpm/corepack 런처는 애플리케이션이 아니다.
|
|
11
|
+
// NODE_OPTIONS="-r whatap"가 상속되어 로드되더라도 에이전트 모듈(타이머, 후킹, whatap_nodejs 기동)을
|
|
12
|
+
// 전혀 로드하지 않고, 실제 앱 프로세스(런처의 자식)에서만 에이전트가 초기화되도록 한다.
|
|
13
|
+
// (stdout을 오염시키지 않도록 안내 메시지는 WHATAP_PRINT 지정 시 stderr로만 출력한다)
|
|
14
|
+
if (process.env.WHATAP_PRINT) {
|
|
15
|
+
console.error('[WHATAP] skip agent initialization for package manager launcher (' + process.argv[1] +
|
|
16
|
+
'). set WHATAP_FORCE_INIT=true to override.');
|
|
17
|
+
}
|
|
18
|
+
exports.NodeAgent = launcher.createNoopAgent();
|
|
19
|
+
exports.Tracer = {};
|
|
20
|
+
} else {
|
|
21
|
+
exports.NodeAgent = require('./lib/core/agent').NodeAgent;
|
|
22
|
+
exports.Tracer = require('./lib/trace/trace-context-manager');
|
|
23
|
+
}
|
|
@@ -53,6 +53,8 @@ var ConfigDefault = {
|
|
|
53
53
|
"net_send_queue1_size": 512,
|
|
54
54
|
"net_send_queue2_size": 1024,
|
|
55
55
|
"max_send_queue_size": num('max_send_queue_size', 2000),
|
|
56
|
+
// 기본값 true 옵션이므로 환경변수는 'false'(대소문자 무관)일 때만 끈다 (bool()은 'true' 외의 값을 모두 false로 해석)
|
|
57
|
+
"udp_send_batch_enabled": String(process.env['udp_send_batch_enabled']).toLowerCase() !== 'false',
|
|
56
58
|
"hook_connection_open_patterns": "",
|
|
57
59
|
"log_datasource_lookup_enabled": true,
|
|
58
60
|
|
package/lib/core/agent.js
CHANGED
|
@@ -982,6 +982,25 @@ NodeAgent.prototype.acquireStartLock = function(lockFile) {
|
|
|
982
982
|
return false;
|
|
983
983
|
};
|
|
984
984
|
|
|
985
|
+
// pid가 같은 WHATAP_HOME의 "다른" 애플리케이션 PID 파일(agent-<identifier>.pid)에 기록된 에이전트인지 확인
|
|
986
|
+
NodeAgent.prototype.isAgentOwnedByOtherApp = function(whatapHome, pid, ownPidFile) {
|
|
987
|
+
try {
|
|
988
|
+
const ownName = path.basename(ownPidFile);
|
|
989
|
+
const target = String(pid).trim();
|
|
990
|
+
const files = fs.readdirSync(whatapHome);
|
|
991
|
+
for (let i = 0; i < files.length; i++) {
|
|
992
|
+
const name = files[i];
|
|
993
|
+
if (name === ownName || !/^agent-.+\.pid$/.test(name)) continue;
|
|
994
|
+
try {
|
|
995
|
+
if (fs.readFileSync(path.join(whatapHome, name), 'utf8').trim() === target) {
|
|
996
|
+
return true;
|
|
997
|
+
}
|
|
998
|
+
} catch (e) {}
|
|
999
|
+
}
|
|
1000
|
+
} catch (e) {}
|
|
1001
|
+
return false;
|
|
1002
|
+
};
|
|
1003
|
+
|
|
985
1004
|
// startGoAgent with improved PID handling
|
|
986
1005
|
NodeAgent.prototype.startGoAgent = function(opts = {}) {
|
|
987
1006
|
const self = this;
|
|
@@ -1050,7 +1069,14 @@ NodeAgent.prototype.startGoAgent = function(opts = {}) {
|
|
|
1050
1069
|
// Unix/Linux: 기존 프로세스 종료 후 새로 시작
|
|
1051
1070
|
if (process.platform === 'win32') {
|
|
1052
1071
|
Logger.print("WHATAP-106", `Agent already running (PID: ${pid}). Skipping duplicate execution.`, false);
|
|
1072
|
+
// 위에서 획득한 기동 lock을 반환하지 않으면 stale 판정(60초) 전까지 재기동이 막힌다
|
|
1073
|
+
try { fs.unlinkSync(sharedLockFile); } catch (e) {}
|
|
1053
1074
|
return;
|
|
1075
|
+
} else if (this.isAgentOwnedByOtherApp(whatapHome, pid, sharedPidFile)) {
|
|
1076
|
+
// 이 파일은 "마지막에 기동된" 에이전트 pid만 가리키므로, 같은 WHATAP_HOME을 쓰는 다른 애플리케이션
|
|
1077
|
+
// (identifier가 다른 프로세스)의 살아있는 에이전트일 수 있다. 그것을 종료하면 서로의 에이전트를
|
|
1078
|
+
// 죽이고 재기동하는 상호 kill이 반복되므로 다른 애플리케이션 소유의 에이전트는 건드리지 않는다.
|
|
1079
|
+
Logger.print("WHATAP-123", `Agent PID ${pid} belongs to another application, leaving it running`, false);
|
|
1054
1080
|
} else {
|
|
1055
1081
|
Logger.print("WHATAP-106", `Found existing agent with PID ${pid}, terminating...`, false);
|
|
1056
1082
|
try {
|
package/lib/udp/async_sender.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
const { performance } = require('perf_hooks');
|
|
1
2
|
const udpSession = require('./udp_session');
|
|
2
3
|
const PacketTypeEnum = require('./packet_type_enum');
|
|
3
4
|
const PacketQueue = require('./packet_queue');
|
|
5
|
+
const Logger = require('../logger');
|
|
6
|
+
const conf = require('../conf/configure');
|
|
7
|
+
|
|
8
|
+
// 테스트/모킹 환경(fake timers 등)에서 전역 setImmediate가 대체되어도 드레인 루프가 멈추지 않도록 timers 모듈의 것을 사용
|
|
9
|
+
const { setImmediate: nativeSetImmediate } = require('timers');
|
|
4
10
|
|
|
5
11
|
const SendType = {
|
|
6
12
|
DATAS: 1,
|
|
@@ -8,9 +14,28 @@ const SendType = {
|
|
|
8
14
|
LLM_RELAY: 3
|
|
9
15
|
};
|
|
10
16
|
|
|
17
|
+
// Drain tuning. (udp_send_batch_enabled=true 일 때 사용, 기본값)
|
|
18
|
+
// 예전 루프는 패킷 1건 처리 후 setTimeout(fn, 0)으로 다음 턴을 예약했다. Node는 0ms 타이머를
|
|
19
|
+
// 1ms로 보정하므로 송신 상한이 ~1000 packet/s(실측 800~1000)로 고정되었고, 트랜잭션당 패킷이
|
|
20
|
+
// 여러 개인 TPS 800~1000 구간부터는 큐(max_send_queue_size)가 가득 차 패킷이 drop 되었다.
|
|
21
|
+
// 또 큐가 비면 100ms 간격으로 폴링해 저부하에서도 패킷이 평균 50ms씩 지연되었다.
|
|
22
|
+
// 지금은 enqueue 시점에 바로 깨우고, 큐를 배치 단위로 비우며, 배치 사이에서만 setImmediate로
|
|
23
|
+
// 이벤트 루프에 양보한다. (setImmediate는 타이머 보정이 없고 매 루프 반복마다 I/O 처리 기회를 준다.)
|
|
24
|
+
const MAX_BATCH_PACKETS = 64; // 한 턴에 처리할 최대 패킷 수
|
|
25
|
+
const MAX_BATCH_MILLIS = 2; // 한 턴에 허용할 최대 시간 (이벤트 루프 점유 상한)
|
|
26
|
+
const TIME_CHECK_MASK = 3; // 4건마다 한 번만 시계를 확인
|
|
27
|
+
const DROP_LOG_INTERVAL = 10000; // 큐 포화로 인한 drop 로그 최소 간격(ms)
|
|
28
|
+
// udp_send_batch_enabled=false 이면 예전 방식(패킷 1건/턴 + setTimeout)으로 동작한다.
|
|
29
|
+
const LEGACY_IDLE_POLL_MILLIS = 100;
|
|
30
|
+
|
|
11
31
|
const packetQueue = PacketQueue.getInstance();
|
|
12
32
|
let initialized = false;
|
|
13
|
-
let sendThread =
|
|
33
|
+
let sendThread = false;
|
|
34
|
+
let drainImmediate = null; // 예약된 setImmediate 핸들 (null이면 큐가 비었거나 처리 중)
|
|
35
|
+
let legacyTimer = null; // 레거시 루프(udp_send_batch_enabled=false)의 타이머 핸들
|
|
36
|
+
let droppedSinceLog = 0; // 마지막 drop 로그 이후 큐 포화로 버려진 패킷 수
|
|
37
|
+
let droppedTotal = 0; // 큐 포화로 버려진 누적 패킷 수
|
|
38
|
+
let lastDropLog = -DROP_LOG_INTERVAL;
|
|
14
39
|
|
|
15
40
|
/**
|
|
16
41
|
* Send a packet asynchronously
|
|
@@ -21,13 +46,16 @@ let sendThread = null;
|
|
|
21
46
|
function send_packet(packet_type, ctx, datas = []) {
|
|
22
47
|
_initThread();
|
|
23
48
|
|
|
24
|
-
//
|
|
25
|
-
let copiedCtx = structuredClone(ctx);
|
|
49
|
+
// 큐가 가득 찼으면 비싼 deep copy 전에 버린다
|
|
26
50
|
if (packetQueue.full()) {
|
|
51
|
+
_onDrop();
|
|
27
52
|
return;
|
|
28
53
|
}
|
|
29
54
|
|
|
30
|
-
|
|
55
|
+
// Deep copy the context to prevent modification
|
|
56
|
+
let copiedCtx = structuredClone(ctx);
|
|
57
|
+
|
|
58
|
+
_enqueue([SendType.DATAS, [packet_type, copiedCtx, datas]]);
|
|
31
59
|
}
|
|
32
60
|
|
|
33
61
|
/**
|
|
@@ -37,11 +65,7 @@ function send_packet(packet_type, ctx, datas = []) {
|
|
|
37
65
|
function send_relaypack(packbytes) {
|
|
38
66
|
_initThread();
|
|
39
67
|
|
|
40
|
-
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
packetQueue.put([SendType.RELAY, packbytes]);
|
|
68
|
+
_enqueue([SendType.RELAY, packbytes]);
|
|
45
69
|
}
|
|
46
70
|
|
|
47
71
|
/**
|
|
@@ -51,54 +75,170 @@ function send_relaypack(packbytes) {
|
|
|
51
75
|
function send_llm_relaypack(packbytes) {
|
|
52
76
|
_initThread();
|
|
53
77
|
|
|
54
|
-
|
|
78
|
+
_enqueue([SendType.LLM_RELAY, packbytes]);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Put an item on the queue and make sure a drain turn is pending
|
|
83
|
+
*/
|
|
84
|
+
function _enqueue(item) {
|
|
85
|
+
if (packetQueue.put(item)) {
|
|
86
|
+
_scheduleDrain();
|
|
87
|
+
} else {
|
|
88
|
+
_onDrop();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 큐 포화로 패킷을 버릴 때마다 호출. 로그는 DROP_LOG_INTERVAL 간격으로만 남긴다.
|
|
94
|
+
* (이전에는 drop이 조용히 발생해 "CPU는 낮은데 데이터가 안 나가는" 상황을 알 수 없었다.
|
|
95
|
+
* Logger.print에도 id별 제한이 있지만, drop마다 호출되지 않도록 여기서 먼저 거른다.)
|
|
96
|
+
*/
|
|
97
|
+
function _onDrop() {
|
|
98
|
+
droppedSinceLog++;
|
|
99
|
+
droppedTotal++;
|
|
100
|
+
|
|
101
|
+
const now = performance.now();
|
|
102
|
+
if (now - lastDropLog < DROP_LOG_INTERVAL) {
|
|
55
103
|
return;
|
|
56
104
|
}
|
|
105
|
+
lastDropLog = now;
|
|
57
106
|
|
|
58
|
-
|
|
107
|
+
const count = droppedSinceLog;
|
|
108
|
+
droppedSinceLog = 0;
|
|
109
|
+
try {
|
|
110
|
+
Logger.print("WHATAP-UDP-011",
|
|
111
|
+
`Send queue is full (max_send_queue_size=${packetQueue.maxSize}), ` +
|
|
112
|
+
`dropped ${count} packets since the last report (total: ${droppedTotal})`, false);
|
|
113
|
+
} catch (e) {
|
|
114
|
+
// 로깅 실패가 애플리케이션 요청 경로로 전파되지 않도록 한다
|
|
115
|
+
}
|
|
59
116
|
}
|
|
60
117
|
|
|
61
118
|
/**
|
|
62
|
-
*
|
|
119
|
+
* Send one queued item through the UDP session
|
|
63
120
|
*/
|
|
64
|
-
function
|
|
65
|
-
|
|
66
|
-
|
|
121
|
+
function _dispatch(packet) {
|
|
122
|
+
try {
|
|
123
|
+
const [sendType, params] = packet;
|
|
124
|
+
if (sendType === SendType.DATAS) {
|
|
125
|
+
const [packet_type, ctx, datas] = params;
|
|
126
|
+
udpSession.send_packet(packet_type, ctx, datas);
|
|
127
|
+
} else if (sendType === SendType.RELAY) {
|
|
128
|
+
const packbytes = params;
|
|
129
|
+
udpSession.send_relaypack(packbytes);
|
|
130
|
+
} else if (sendType === SendType.LLM_RELAY) {
|
|
131
|
+
const packbytes = params;
|
|
132
|
+
udpSession.send_llm_relaypack(packbytes);
|
|
133
|
+
}
|
|
134
|
+
} catch (e) {
|
|
135
|
+
console.error("Error processing queue item:", e);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* udp_send_batch_enabled (기본 true). whatap.conf 에서 줄이 삭제되면 이벤트 없이 기본값으로 복원되므로
|
|
141
|
+
* 값을 캐시하지 않고 매번 읽는다.
|
|
142
|
+
*/
|
|
143
|
+
function _batchEnabled() {
|
|
144
|
+
const v = conf.getProperty('udp_send_batch_enabled', true);
|
|
145
|
+
return !(v === false || String(v).trim().toLowerCase() === 'false');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Wake the sender right after an enqueue (no-op when a turn is already pending).
|
|
150
|
+
* Invariant (batch mode): the queue is never non-empty without a pending drain turn.
|
|
151
|
+
*/
|
|
152
|
+
function _scheduleDrain() {
|
|
153
|
+
if (drainImmediate !== null) {
|
|
154
|
+
// 이미 대기 중인 턴이 있으면 옵션을 읽을 필요도 없다 (옵션이 꺼졌다면 _drain의 finally가 레거시 루프로 넘긴다)
|
|
67
155
|
return;
|
|
68
156
|
}
|
|
157
|
+
if (_batchEnabled()) {
|
|
158
|
+
drainImmediate = nativeSetImmediate(_drain);
|
|
159
|
+
} else {
|
|
160
|
+
_ensureLegacyLoop();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
69
163
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
164
|
+
/**
|
|
165
|
+
* Drain the queue for one event-loop turn (bounded by packet count and time budget)
|
|
166
|
+
*/
|
|
167
|
+
function _drain() {
|
|
168
|
+
drainImmediate = null;
|
|
73
169
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
170
|
+
try {
|
|
171
|
+
const startedAt = performance.now();
|
|
172
|
+
let handled = 0;
|
|
173
|
+
let packet;
|
|
79
174
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
} else if (sendType === SendType.LLM_RELAY) {
|
|
89
|
-
const packbytes = params;
|
|
90
|
-
udpSession.send_llm_relaypack(packbytes);
|
|
175
|
+
while ((packet = packetQueue.get()) !== null) {
|
|
176
|
+
_dispatch(packet);
|
|
177
|
+
|
|
178
|
+
if (++handled >= MAX_BATCH_PACKETS) {
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
if ((handled & TIME_CHECK_MASK) === 0 && performance.now() - startedAt >= MAX_BATCH_MILLIS) {
|
|
182
|
+
break;
|
|
91
183
|
}
|
|
92
|
-
} catch (e) {
|
|
93
|
-
console.error("Error processing queue item:", e);
|
|
94
184
|
}
|
|
185
|
+
} finally {
|
|
186
|
+
// 남은 패킷은 이벤트 루프에 한 번 양보한 뒤 이어서 처리
|
|
187
|
+
// (처리 중 enqueue가 이미 다음 턴을 예약했다면 중복 예약하지 않는다)
|
|
188
|
+
if (drainImmediate === null && !packetQueue.empty()) {
|
|
189
|
+
if (_batchEnabled()) {
|
|
190
|
+
drainImmediate = nativeSetImmediate(_drain);
|
|
191
|
+
} else {
|
|
192
|
+
// 옵션이 런타임에 꺼진 경우: 남은 패킷은 레거시 루프가 이어받는다
|
|
193
|
+
_ensureLegacyLoop();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
95
198
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
199
|
+
/**
|
|
200
|
+
* 레거시 송신 루프 (udp_send_batch_enabled=false): 패킷 1건당 setTimeout(fn, 0), 큐가 비면 100ms 폴링.
|
|
201
|
+
* 옵션이 런타임에 켜지면 다음 틱에서 종료하고 배치 방식으로 넘어간다.
|
|
202
|
+
*/
|
|
203
|
+
function _ensureLegacyLoop() {
|
|
204
|
+
if (legacyTimer === null) {
|
|
205
|
+
legacyTimer = setTimeout(_legacyTick, 0);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function _legacyTick() {
|
|
210
|
+
legacyTimer = null;
|
|
211
|
+
|
|
212
|
+
if (_batchEnabled()) {
|
|
213
|
+
_scheduleDrain();
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const packet = packetQueue.get();
|
|
218
|
+
if (packet === null) {
|
|
219
|
+
// No packet, wait and try again
|
|
220
|
+
legacyTimer = setTimeout(_legacyTick, LEGACY_IDLE_POLL_MILLIS);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
_dispatch(packet);
|
|
225
|
+
|
|
226
|
+
// Continue processing
|
|
227
|
+
// (전송 중 재진입 enqueue가 이미 타이머를 걸었다면 덮어써서 체인이 둘로 늘어나지 않게 한다)
|
|
228
|
+
_ensureLegacyLoop();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Start the async processing thread
|
|
233
|
+
*/
|
|
234
|
+
function startWhatapThread() {
|
|
235
|
+
// If thread is already running, don't start another
|
|
236
|
+
if (sendThread) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
99
239
|
|
|
100
|
-
|
|
101
|
-
|
|
240
|
+
sendThread = true;
|
|
241
|
+
_scheduleDrain();
|
|
102
242
|
}
|
|
103
243
|
|
|
104
244
|
/**
|
package/lib/udp/packet_queue.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
const conf = require('../conf/configure');
|
|
7
7
|
|
|
8
8
|
const DEFAULT_MAX_SIZE = 2000;
|
|
9
|
+
const COMPACT_THRESHOLD = 1024; // head가 이 값 이상일 때만 압축을 고려
|
|
9
10
|
|
|
10
11
|
function getConfiguredMaxSize() {
|
|
11
12
|
const size = parseInt(conf.getProperty('max_send_queue_size', DEFAULT_MAX_SIZE));
|
|
@@ -20,7 +21,10 @@ class PacketQueue {
|
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
// Initialize queue
|
|
24
|
+
// Array.shift()는 큐가 깊어질수록(수만 건 이상) O(n)으로 느려져 max_send_queue_size를 키우면
|
|
25
|
+
// 오히려 처리량이 급락한다. 앞쪽은 head 인덱스로 건너뛰고 주기적으로만 압축해 get()을 O(1)에 유지한다.
|
|
23
26
|
this.queue = [];
|
|
27
|
+
this.head = 0;
|
|
24
28
|
this.maxSize = maxSize;
|
|
25
29
|
|
|
26
30
|
// Store the instance
|
|
@@ -28,7 +32,7 @@ class PacketQueue {
|
|
|
28
32
|
}
|
|
29
33
|
|
|
30
34
|
put(item) {
|
|
31
|
-
if (this.
|
|
35
|
+
if (this.size() < this.maxSize) {
|
|
32
36
|
this.queue.push(item);
|
|
33
37
|
return true;
|
|
34
38
|
}
|
|
@@ -36,26 +40,40 @@ class PacketQueue {
|
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
get() {
|
|
39
|
-
if (this.queue.length
|
|
40
|
-
return
|
|
43
|
+
if (this.head >= this.queue.length) {
|
|
44
|
+
return null;
|
|
41
45
|
}
|
|
42
|
-
|
|
46
|
+
|
|
47
|
+
const item = this.queue[this.head];
|
|
48
|
+
this.queue[this.head++] = undefined; // 참조 해제
|
|
49
|
+
|
|
50
|
+
if (this.head === this.queue.length) {
|
|
51
|
+
// 모두 소비됨: 비용 없이 초기화
|
|
52
|
+
this.queue.length = 0;
|
|
53
|
+
this.head = 0;
|
|
54
|
+
} else if (this.head >= COMPACT_THRESHOLD && this.head * 2 >= this.queue.length) {
|
|
55
|
+
// 소비된 앞부분이 절반 이상이면 한 번에 압축 (amortized O(1))
|
|
56
|
+
this.queue = this.queue.slice(this.head);
|
|
57
|
+
this.head = 0;
|
|
58
|
+
}
|
|
59
|
+
return item;
|
|
43
60
|
}
|
|
44
61
|
|
|
45
62
|
full() {
|
|
46
|
-
return this.
|
|
63
|
+
return this.size() >= this.maxSize;
|
|
47
64
|
}
|
|
48
65
|
|
|
49
66
|
empty() {
|
|
50
|
-
return this.queue.length
|
|
67
|
+
return this.head >= this.queue.length;
|
|
51
68
|
}
|
|
52
69
|
|
|
53
70
|
size() {
|
|
54
|
-
return this.queue.length;
|
|
71
|
+
return this.queue.length - this.head;
|
|
55
72
|
}
|
|
56
73
|
|
|
57
74
|
clear() {
|
|
58
75
|
this.queue = [];
|
|
76
|
+
this.head = 0;
|
|
59
77
|
}
|
|
60
78
|
|
|
61
79
|
/**
|
package/lib/udp/udp_session.js
CHANGED
|
@@ -14,6 +14,8 @@ const GCAction = require('../system/gc-action');
|
|
|
14
14
|
const DataOuputX = require('../../lib/io/data-outputx');
|
|
15
15
|
const Logger = require('../logger');
|
|
16
16
|
|
|
17
|
+
const UDP_REINIT_INTERVAL = 1000; // 송신 오류로 인한 소켓 재생성 최소 간격 (ms)
|
|
18
|
+
|
|
17
19
|
class UdpSession {
|
|
18
20
|
constructor() {
|
|
19
21
|
this.socket = null;
|
|
@@ -23,6 +25,8 @@ class UdpSession {
|
|
|
23
25
|
this.serverHost = PacketEnum.SERVER;
|
|
24
26
|
this.serverPort = PacketEnum.PORT;
|
|
25
27
|
this.isConnected = false; // connected-UDP 여부
|
|
28
|
+
this._udpConfig = null; // udp()에 마지막으로 전달된 설정 (재생성 시 재사용)
|
|
29
|
+
this._lastReinit = 0; // 송신 오류로 소켓을 마지막으로 재생성한 시각 (ms)
|
|
26
30
|
|
|
27
31
|
// LLM Go Agent 전용 소켓
|
|
28
32
|
this.llmSocket = null;
|
|
@@ -35,7 +39,12 @@ class UdpSession {
|
|
|
35
39
|
*/
|
|
36
40
|
udp(config) {
|
|
37
41
|
const self = this;
|
|
38
|
-
|
|
42
|
+
// 인자 없이 재호출(송신 오류 후 소켓 재생성)되어도 마지막 설정(host/port)을 유지한다.
|
|
43
|
+
// 그렇지 않으면 목적지가 기본 포트(6600)로 되돌아가 다른 애플리케이션의 에이전트로 전송될 수 있다.
|
|
44
|
+
if (config) {
|
|
45
|
+
self._udpConfig = config;
|
|
46
|
+
}
|
|
47
|
+
const conf = self._udpConfig || {};
|
|
39
48
|
|
|
40
49
|
// Close existing socket if open
|
|
41
50
|
if (self.socket) {
|
|
@@ -284,11 +293,20 @@ class UdpSession {
|
|
|
284
293
|
const sendbuf = Buffer.concat(self.bufferArr);
|
|
285
294
|
|
|
286
295
|
// Send via UDP
|
|
296
|
+
const sock = self.socket;
|
|
287
297
|
const cb = (err) => {
|
|
288
298
|
if (err) {
|
|
289
299
|
Logger.printError("WHATAP-UDP-008", "Failed to send UDP packet", err, false);
|
|
290
300
|
// Consider reinitializing UDP connection on error
|
|
291
|
-
|
|
301
|
+
// 이미 교체된 소켓의 오류는 무시하고, 재생성은 일정 간격으로만 수행한다.
|
|
302
|
+
// (에이전트 기동 전/재기동 중 ECONNREFUSED가 연속 발생해도 소켓 재생성이 폭주하지 않도록)
|
|
303
|
+
const now = Date.now();
|
|
304
|
+
const elapsed = now - self._lastReinit;
|
|
305
|
+
// elapsed < 0: 시스템 시계가 뒤로 조정된 경우에도 재생성이 막히지 않도록 한다
|
|
306
|
+
if (sock === self.socket && (elapsed >= UDP_REINIT_INTERVAL || elapsed < 0)) {
|
|
307
|
+
self._lastReinit = now;
|
|
308
|
+
self.udp();
|
|
309
|
+
}
|
|
292
310
|
}
|
|
293
311
|
};
|
|
294
312
|
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2016 the WHATAP project authors. All rights reserved.
|
|
3
|
+
* Use of this source code is governed by a license that
|
|
4
|
+
* can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// NODE_OPTIONS="-r whatap" (Operator 자동 주입 등)은 npm/yarn/pnpm 같은 "패키지 매니저 런처" 프로세스와
|
|
8
|
+
// 그 자식인 실제 애플리케이션(next, node server.js ...)에 모두 상속된다.
|
|
9
|
+
// 런처는 애플리케이션이 아니므로 에이전트를 초기화하면 안 된다. (초기화하면 런처와 앱이 각자 whatap_nodejs를
|
|
10
|
+
// 띄우고, 서로의 에이전트를 종료시키며 UDP ECONNREFUSED와 트랜잭션 미수집이 발생한다.)
|
|
11
|
+
|
|
12
|
+
var fs = require('fs');
|
|
13
|
+
|
|
14
|
+
// 확장자(.js/.cjs/.mjs/.cmd/.exe/.ps1/.bat)를 제거한 실행 파일명 기준
|
|
15
|
+
// npm, npx, npm-cli, npx-cli, npm-prefix (Windows npm.cmd 헬퍼), yarn, yarnpkg, yarn-1.22.19, yarn-berry (.yarn/releases),
|
|
16
|
+
// pnpm, pnpx, corepack
|
|
17
|
+
var LAUNCHER_NAME = /^(?:npm|npx|yarn|yarnpkg|pnpm|pnpx|corepack)(?:-cli|-prefix|-berry|-\d+\.\d[\w.\-]*)?$/;
|
|
18
|
+
var SCRIPT_EXT = /\.(?:[cm]?js|cmd|exe|ps1|bat)$/i;
|
|
19
|
+
|
|
20
|
+
function baseName(file) {
|
|
21
|
+
// 플랫폼과 무관하게 '/', '\\' 둘 다 구분자로 취급
|
|
22
|
+
return file.split(/[\\/]/).pop().replace(SCRIPT_EXT, '').toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// WHATAP_EXCLUDE_PROCESS="cross-env,nodemon" : 패키지 매니저 외에 초기화를 건너뛸 진입 스크립트 이름(쉼표 구분)
|
|
26
|
+
function getExtraNames() {
|
|
27
|
+
var raw = process.env.WHATAP_EXCLUDE_PROCESS;
|
|
28
|
+
if (!raw) {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
return String(raw).split(',').map(function (name) {
|
|
32
|
+
// 경로로 지정해도 마지막 이름만 비교한다
|
|
33
|
+
return baseName(name.trim());
|
|
34
|
+
}).filter(Boolean);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isLauncherFile(file, extraNames) {
|
|
38
|
+
if (!file || typeof file !== 'string') {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
var name = baseName(file);
|
|
42
|
+
return LAUNCHER_NAME.test(name) || (!!extraNames && extraNames.indexOf(name) >= 0);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isDirectory(file) {
|
|
46
|
+
try {
|
|
47
|
+
return fs.statSync(file).isDirectory();
|
|
48
|
+
} catch (e) {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {string} entryFile - 프로세스 진입 스크립트 경로 (process.argv[1])
|
|
55
|
+
* @param {string[]} [extraNames] - 추가로 제외할 진입 스크립트 이름 (소문자, 확장자 제외)
|
|
56
|
+
* @returns {boolean} 패키지 매니저 런처(npm/npx/yarn/pnpm/corepack) 프로세스이면 true
|
|
57
|
+
*/
|
|
58
|
+
function isPackageManagerLauncher(entryFile, extraNames) {
|
|
59
|
+
if (!entryFile || typeof entryFile !== 'string') {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
var matched = isLauncherFile(entryFile, extraNames);
|
|
64
|
+
if (!matched) {
|
|
65
|
+
// /usr/local/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js 처럼 심볼릭 링크로 실행된 경우
|
|
66
|
+
try {
|
|
67
|
+
matched = isLauncherFile(fs.realpathSync(entryFile), extraNames);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
matched = false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// `node .` / `node /srv/npm` 처럼 디렉터리가 진입점이면 이름이 같아도 애플리케이션이다
|
|
74
|
+
return matched && !isDirectory(entryFile);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 현재 프로세스가 에이전트 초기화를 건너뛰어야 하는 런처인지 판단한다.
|
|
79
|
+
* WHATAP_FORCE_INIT=true 이면 항상 초기화한다 (오탐 시 우회용).
|
|
80
|
+
*/
|
|
81
|
+
function isCurrentProcessLauncher() {
|
|
82
|
+
if (String(process.env.WHATAP_FORCE_INIT).toLowerCase() === 'true') {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
return isPackageManagerLauncher(process.argv[1], getExtraNames());
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 런처 프로세스에서 require('whatap')을 호출해도 깨지지 않도록 하는 no-op NodeAgent
|
|
90
|
+
*/
|
|
91
|
+
function createNoopAgent() {
|
|
92
|
+
return {
|
|
93
|
+
init: function () { return this; },
|
|
94
|
+
plugin: function () {},
|
|
95
|
+
context: function () { return null; }
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
exports.isLauncherFile = isLauncherFile;
|
|
100
|
+
exports.isPackageManagerLauncher = isPackageManagerLauncher;
|
|
101
|
+
exports.isCurrentProcessLauncher = isCurrentProcessLauncher;
|
|
102
|
+
exports.createNoopAgent = createNoopAgent;
|
package/package.json
CHANGED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"permissions": {
|
|
3
|
-
"allow": [
|
|
4
|
-
"Read(//Users/seunghunlee/agent_workspace/apm-go-agent/**)",
|
|
5
|
-
"Read(//Users/seunghunlee/agent_workspace/golib-dev/util/urlutil/**)",
|
|
6
|
-
"Bash(go build *)",
|
|
7
|
-
"Bash(curl -sS -o /dev/null -w \"HTTP %{http_code}\\\\n\" http://localhost:3002/api/health)",
|
|
8
|
-
"Bash(kill 48136 48229)",
|
|
9
|
-
"Bash(curl -sS -o /dev/null -w \"app.js HTTP %{http_code}\\\\n\" http://localhost:3002/api/health)",
|
|
10
|
-
"Bash(ps -p 53138 -o pid,lstart,comm)",
|
|
11
|
-
"Bash(awk '$4==\"txt\"{print $NF}')",
|
|
12
|
-
"Bash(ps -p 53138 -Eww)",
|
|
13
|
-
"Bash(ps -ax -o pid,comm)",
|
|
14
|
-
"Bash(grep -iE \"whatap_nodejs$\")",
|
|
15
|
-
"Bash(kill %1)",
|
|
16
|
-
"Bash(pkill -f \"agent/darwin/arm64/whatap_nodejs.*head\")",
|
|
17
|
-
"Bash(ps -axww -o pid,lstart,command)",
|
|
18
|
-
"Bash(ps -axww)",
|
|
19
|
-
"Bash(docker buildx *)",
|
|
20
|
-
"Bash(docker info *)",
|
|
21
|
-
"Bash(docker system *)",
|
|
22
|
-
"Bash(sshpass -p 'Wh@1410X2' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 whatap@192.168.100.21 'echo \"접속 OK: $\\(whoami\\)@$\\(hostname\\)\"; echo \"arch: $\\(uname -m\\)\"; docker --version 2>&1 | head -1; echo \"docker 권한: $\\(docker ps >/dev/null 2>&1 && echo ok || echo \"sudo 필요/불가\"\\)\"')",
|
|
23
|
-
"Bash(sshpass -p Wh@1410X2 ssh -o StrictHostKeyChecking=no whatap@192.168.100.21 ' *)",
|
|
24
|
-
"Bash(git log *)",
|
|
25
|
-
"Bash(sed -n '/urls := stringutil.Tokenizer\\(this.conf.TraceNormalizeUrls/,/^\tthis.restUrlTable = pathTreeTmp/p' agent/trace/ServiceURLPatternDetector.go)",
|
|
26
|
-
"Bash(sed -n '/func \\(this \\\\*ServiceURLPatternDetector\\) Normalize/,/^}/p' agent/trace/ServiceURLPatternDetector.go)",
|
|
27
|
-
"Bash(sed -n '/type ServiceURLPatternDetector struct/,/^}/p' agent/trace/ServiceURLPatternDetector.go)",
|
|
28
|
-
"Bash(sed -n '/p := new\\(ServiceURLPatternDetector\\)/,/p.Build\\(false\\)/p' agent/trace/ServiceURLPatternDetector.go)",
|
|
29
|
-
"Bash(GOFLAGS=-mod=mod go build ./agent/trace/...)",
|
|
30
|
-
"Bash(echo \"build exit: $?\")",
|
|
31
|
-
"Bash(GOFLAGS=-mod=mod go build ./...)",
|
|
32
|
-
"Bash(echo \"전체 build exit: $?\")",
|
|
33
|
-
"Bash(GOFLAGS=-mod=mod go vet ./agent/trace/... ./agent/config/...)",
|
|
34
|
-
"Bash(echo \"vet exit: $?\")",
|
|
35
|
-
"Read(//tmp/**)",
|
|
36
|
-
"Bash(node -c lib/observers/http-observer.js)",
|
|
37
|
-
"Bash(node -e \"console.log\\(require\\('/Users/seunghunlee/workspace/go_sample/node_modules/whatap/package.json'\\).version\\)\")",
|
|
38
|
-
"Bash(git add *)",
|
|
39
|
-
"Bash(git commit *)",
|
|
40
|
-
"Bash(git fetch *)",
|
|
41
|
-
"Bash(git push *)",
|
|
42
|
-
"Bash(node --check /Users/seunghunlee/agent_workspace/nodejs_agent/lib/core/agent.js)",
|
|
43
|
-
"Bash(git -C /Users/seunghunlee/agent_workspace/nodejs_agent branch -a)",
|
|
44
|
-
"Bash(git -C /Users/seunghunlee/agent_workspace/nodejs_agent log --all --oneline -- test)",
|
|
45
|
-
"Bash(node *)",
|
|
46
|
-
"Bash(git *)",
|
|
47
|
-
"Read(//Users/seunghunlee/workspace/go_sample/node_modules/whatap/lib/core/**)",
|
|
48
|
-
"Read(//Users/seunghunlee/workspace/go_sample/**)",
|
|
49
|
-
"Bash(rm -f agent-cfd56737.pid agent-cfd56737.lock whatap_nodejs.pid)",
|
|
50
|
-
"Bash(pkill -f whatap_nodejs)",
|
|
51
|
-
"Bash(xargs kill -9)",
|
|
52
|
-
"Bash(kill 34859)",
|
|
53
|
-
"Bash(cp node_modules/whatap/lib/core/agent.js node_modules/whatap/lib/core/agent.js.2.0.5.bak)",
|
|
54
|
-
"Bash(cp /Users/seunghunlee/agent_workspace/nodejs_agent/lib/core/agent.js node_modules/whatap/lib/core/agent.js)",
|
|
55
|
-
"Bash(ls -la agent-*)",
|
|
56
|
-
"Bash(npm view *)",
|
|
57
|
-
"Bash(rm -f node_modules/whatap/lib/core/agent.js.2.0.5.bak)",
|
|
58
|
-
"Bash(npm install *)",
|
|
59
|
-
"Bash(pkill -f \"node app.js\")"
|
|
60
|
-
]
|
|
61
|
-
}
|
|
62
|
-
}
|