/
ThreadMonitor.java
259 lines (214 loc) · 6.65 KB
/
ThreadMonitor.java
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
package delight.nashornsandbox.internal;
import static delight.nashornsandbox.internal.NashornSandboxImpl.LOG;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* JS executor thread monitor. It is designed to be run in main thread (the JS
* script is executed in other thread).
*
* <p>
* Created on 2015-08-07
* </p>
*
* @author <a href="mailto:mxro@nowhere.com>mxro</a>
* @author <a href="mailto:marcin.golebski@verbis.pl">Marcin Golebski</a>
* @version $Id$
*/
@SuppressWarnings("restriction")
public class ThreadMonitor {
private static final int MILI_TO_NANO = 1000000;
private final long maxCPUTime;
private final long maxMemory;
private final int stageOffset;
private final AtomicBoolean stop;
/** Check if interrupted script has finished. */
private final AtomicBoolean scriptFinished;
/** Check if script should be killed to stop it when abusive. */
private final AtomicBoolean scriptKilled;
private final AtomicBoolean cpuLimitExceeded;
private final AtomicInteger memoryLimitExceededStage;
private final Object monitor;
private Thread threadToMonitor;
private boolean timedOutWaitingForThreadToMonitor = false;
private ThreadMXBean threadBean;
private final com.sun.management.ThreadMXBean memoryCounter;
public ThreadMonitor(final long maxCPUTime, final long maxMemory) {
this.maxMemory = maxMemory;
this.maxCPUTime = maxCPUTime * 1000000;
stop = new AtomicBoolean(false);
scriptFinished = new AtomicBoolean(false);
scriptKilled = new AtomicBoolean(false);
cpuLimitExceeded = new AtomicBoolean(false);
memoryLimitExceededStage = new AtomicInteger(0);
monitor = new Object();
// if maxMemory is larger than 100M, split heap memory count into 4 stage, and offset will be 2
// 4 stage count will lose accuracy, only works in large allowed heap memory allocation
// this could fix the mis-killing sub-thread behavior, which happened one or two time during about 3 Mill execution ( with thread reusing ).
if(maxMemory>1024*1024*100){
stageOffset=2;
}else {
stageOffset=0;
}
// ensure the ThreadMXBean is supported in the JVM
try {
threadBean = ManagementFactory.getThreadMXBean();
// ensure the ThreadMXBean is enabled for CPU time measurement
threadBean.setThreadCpuTimeEnabled(true);
} catch (UnsupportedOperationException ex) {
if(maxCPUTime > 0) {
throw new UnsupportedOperationException("JVM does not support thread CPU time measurement");
}
}
if ((threadBean != null) && (threadBean instanceof com.sun.management.ThreadMXBean)) {
memoryCounter = (com.sun.management.ThreadMXBean) threadBean;
// ensure this feature is enabled
memoryCounter.setThreadAllocatedMemoryEnabled(true);
} else {
if (maxMemory > 0) {
throw new UnsupportedOperationException("JVM does not support thread memory counting");
}
memoryCounter = null;
}
}
private void reset() {
stop.set(false);
scriptFinished.set(false);
scriptKilled.set(false);
cpuLimitExceeded.set(false);
memoryLimitExceededStage.set(0);
threadToMonitor = null;
}
public void run() {
try {
// wait, for threadToMonitor to be set in JS evaluator thread
synchronized (monitor) {
if (threadToMonitor == null) {
monitor.wait((maxCPUTime + 500) / MILI_TO_NANO);
}
if (threadToMonitor == null) {
timedOutWaitingForThreadToMonitor = true;
throw new IllegalStateException("Executor thread not set after " + maxCPUTime / MILI_TO_NANO + " ms,usually this means the sub-thread not started properly");
}
}
final long startCPUTime = getCPUTime();
//one stage start
long stageMemory = getCurrentMemory();
while (!stop.get()) {
final long runtime = getCPUTime() - startCPUTime;
long currentMemory = getCurrentMemory();
final long memory = currentMemory - stageMemory;
boolean stageExided = isStageMemoryExided(memory);
if(stageExided){
//exceeded once , and record it
memoryLimitExceededStage.incrementAndGet();
//start next stage counting
stageMemory=currentMemory;
}
if (isCpuTimeExided(runtime) || isMemoryLimitExceeded()) {
cpuLimitExceeded.set(isCpuTimeExided(runtime));
threadToMonitor.interrupt();
synchronized (monitor) {
//wait less
monitor.wait(5);
}
if (stop.get()) {
return;
}
if (!scriptFinished.get()) {
stop.set(true);
threadToMonitor.interrupt();
scriptKilled.set(true);
}
return;
} else {
}
synchronized (monitor) {
long waitTime = getCheckInterval(runtime);
if (waitTime == 0) {
waitTime = 1;
}
monitor.wait(waitTime);
}
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private long getCheckInterval(final long runtime) {
if (maxCPUTime == 0) {
return 10;
}
if (maxMemory == 0) {
return Math.max((maxCPUTime - runtime) / MILI_TO_NANO, 5);
}
//wait less to reduce execution cost
return Math.min((maxCPUTime - runtime) / MILI_TO_NANO, 5);
}
private boolean isCpuTimeExided(final long runtime) {
if (maxCPUTime == 0) {
return false;
}
return runtime > maxCPUTime;
}
private boolean isStageMemoryExided(final long memory) {
if (maxMemory == 0) {
return false;
}
return memory > (maxMemory>>stageOffset);
}
/**
* Obtain current evaluation thread memory usage.
*
* it must be empathises that the method 'getThreadAllocatedBytes' is not strictly accurate
* so mis killing might happen.
*
* @return current memory usage
*/
private long getCurrentMemory() throws InterruptedException {
if ((maxMemory > 0) && (memoryCounter != null)) {
synchronized (monitor) {
return memoryCounter.getThreadAllocatedBytes(threadToMonitor.getId());
}
}
return 0L;
}
private long getCPUTime() {
if ((maxCPUTime > 0) && (threadBean != null)) {
return threadBean.getThreadCpuTime(threadToMonitor.getId());
} else {
return 0L;
}
}
public void stopMonitor() {
synchronized (monitor) {
stop.set(true);
monitor.notifyAll();
}
}
public boolean registerThreadToMonitor(final Thread t) {
synchronized (monitor) {
if (timedOutWaitingForThreadToMonitor) {
return false;
}
reset();
threadToMonitor = t;
monitor.notifyAll();
return true;
}
}
public void scriptFinished() {
scriptFinished.set(false);
}
public boolean isCPULimitExceeded() {
return cpuLimitExceeded.get();
}
public boolean isMemoryLimitExceeded() {
// return true stage max reached
return memoryLimitExceededStage.get()>=(1<<stageOffset);
}
public boolean isScriptKilled() {
return scriptKilled.get();
}
}