/
ShellBolt.java
409 lines (353 loc) · 14.9 KB
/
ShellBolt.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
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.storm.task;
import org.apache.storm.Config;
import org.apache.storm.Constants;
import org.apache.storm.generated.ShellComponent;
import org.apache.storm.metric.api.IMetric;
import org.apache.storm.metric.api.rpc.IShellMetric;
import org.apache.storm.multilang.BoltMsg;
import org.apache.storm.multilang.ShellMsg;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.utils.ShellBoltMessageQueue;
import org.apache.storm.utils.ShellLogHandler;
import org.apache.storm.utils.ShellProcess;
import org.apache.storm.utils.ShellUtils;
import clojure.lang.RT;
import com.google.common.util.concurrent.MoreExecutors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* A bolt that shells out to another process to process tuples. ShellBolt
* communicates with that process over stdio using a special protocol. An ~100
* line library is required to implement that protocol, and adapter libraries
* currently exist for Ruby and Python.
*
* To run a ShellBolt on a cluster, the scripts that are shelled out to must be
* in the resources directory within the jar submitted to the master.
* During development/testing on a local machine, that resources directory just
* needs to be on the classpath.
*
* When creating topologies using the Java API, subclass this bolt and implement
* the IRichBolt interface to create components for the topology that use other languages. For example:
*
*
* ```java
* public class MyBolt extends ShellBolt implements IRichBolt {
* public MyBolt() {
* super("python", "mybolt.py");
* }
*
* public void declareOutputFields(OutputFieldsDeclarer declarer) {
* declarer.declare(new Fields("field1", "field2"));
* }
* }
* ```
*/
public class ShellBolt implements IBolt {
public static final String HEARTBEAT_STREAM_ID = "__heartbeat";
public static final Logger LOG = LoggerFactory.getLogger(ShellBolt.class);
private static final long serialVersionUID = -339575186639193348L;
OutputCollector _collector;
Map<String, Tuple> _inputs = new ConcurrentHashMap<>();
private String[] _command;
private Map<String, String> env = new HashMap<>();
private ShellLogHandler _logHandler;
private ShellProcess _process;
private volatile boolean _running = true;
private volatile Throwable _exception;
private ShellBoltMessageQueue _pendingWrites = new ShellBoltMessageQueue();
private Random _rand;
private Thread _readerThread;
private Thread _writerThread;
private TopologyContext _context;
private int workerTimeoutMills;
private ScheduledExecutorService heartBeatExecutorService;
private AtomicLong lastHeartbeatTimestamp = new AtomicLong();
private AtomicBoolean sendHeartbeatFlag = new AtomicBoolean(false);
private boolean _isLocalMode = false;
private boolean changeDirectory = true;
public ShellBolt(ShellComponent component) {
this(component.get_execution_command(), component.get_script());
}
public ShellBolt(String... command) {
_command = command;
}
public ShellBolt setEnv(Map<String, String> env) {
this.env = env;
return this;
}
public boolean shouldChangeChildCWD() {
return changeDirectory;
}
/**
* Set if the current working directory of the child process should change
* to the resources dir from extracted from the jar, or if it should stay
* the same as the worker process to access things from the blob store.
* @param changeDirectory true change the directory (default) false
* leave the directory the same as the worker process.
*/
public void changeChildCWD(boolean changeDirectory) {
this.changeDirectory = changeDirectory;
}
public void prepare(Map stormConf, TopologyContext context,
final OutputCollector collector) {
Object maxPending = stormConf.get(Config.TOPOLOGY_SHELLBOLT_MAX_PENDING);
if (maxPending != null) {
this._pendingWrites = new ShellBoltMessageQueue(((Number)maxPending).intValue());
}
_rand = new Random();
_collector = collector;
_context = context;
if (stormConf.containsKey(Config.TOPOLOGY_SUBPROCESS_TIMEOUT_SECS)) {
workerTimeoutMills = 1000 * RT.intCast(stormConf.get(Config.TOPOLOGY_SUBPROCESS_TIMEOUT_SECS));
} else {
workerTimeoutMills = 1000 * RT.intCast(stormConf.get(Config.SUPERVISOR_WORKER_TIMEOUT_SECS));
}
_process = new ShellProcess(_command);
if (!env.isEmpty()) {
_process.setEnv(env);
}
//subprocesses must send their pid first thing
Number subpid = _process.launch(stormConf, context, changeDirectory);
LOG.info("Launched subprocess with pid " + subpid);
_logHandler = ShellUtils.getLogHandler(stormConf);
_logHandler.setUpContext(ShellBolt.class, _process, _context);
// reader
_readerThread = new Thread(new BoltReaderRunnable());
_readerThread.start();
_writerThread = new Thread(new BoltWriterRunnable());
_writerThread.start();
LOG.info("Start checking heartbeat...");
setHeartbeat();
heartBeatExecutorService = MoreExecutors.getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
heartBeatExecutorService.scheduleAtFixedRate(new BoltHeartbeatTimerTask(this), 1, 1, TimeUnit.SECONDS);
}
public void execute(Tuple input) {
if (_exception != null) {
throw new RuntimeException(_exception);
}
//just need an id
String genId = Long.toString(_rand.nextLong());
_inputs.put(genId, input);
try {
BoltMsg boltMsg = createBoltMessage(input, genId);
_pendingWrites.putBoltMsg(boltMsg);
} catch(InterruptedException e) {
// It's likely that Bolt is shutting down so no need to throw RuntimeException
// just ignore
}
}
private BoltMsg createBoltMessage(Tuple input, String genId) {
BoltMsg boltMsg = new BoltMsg();
boltMsg.setId(genId);
boltMsg.setComp(input.getSourceComponent());
boltMsg.setStream(input.getSourceStreamId());
boltMsg.setTask(input.getSourceTask());
boltMsg.setTuple(input.getValues());
return boltMsg;
}
public void cleanup() {
_running = false;
heartBeatExecutorService.shutdownNow();
_writerThread.interrupt();
_readerThread.interrupt();
_process.destroy();
_inputs.clear();
}
private void handleAck(Object id) {
Tuple acked = _inputs.remove(id);
if(acked==null) {
throw new RuntimeException("Acked a non-existent or already acked/failed id: " + id);
}
_collector.ack(acked);
}
private void handleFail(Object id) {
Tuple failed = _inputs.remove(id);
if(failed==null) {
throw new RuntimeException("Failed a non-existent or already acked/failed id: " + id);
}
_collector.fail(failed);
}
private void handleError(String msg) {
_collector.reportError(new Exception("Shell Process Exception: " + msg));
}
private void handleEmit(ShellMsg shellMsg) throws InterruptedException {
List<Tuple> anchors = new ArrayList<>();
List<String> recvAnchors = shellMsg.getAnchors();
if (recvAnchors != null) {
for (String anchor : recvAnchors) {
Tuple t = _inputs.get(anchor);
if (t == null) {
throw new RuntimeException("Anchored onto " + anchor + " after ack/fail");
}
anchors.add(t);
}
}
if(shellMsg.getTask() == 0) {
List<Integer> outtasks = _collector.emit(shellMsg.getStream(), anchors, shellMsg.getTuple());
if (shellMsg.areTaskIdsNeeded()) {
_pendingWrites.putTaskIds(outtasks);
}
} else {
_collector.emitDirect((int) shellMsg.getTask(),
shellMsg.getStream(), anchors, shellMsg.getTuple());
}
}
private void handleMetrics(ShellMsg shellMsg) {
//get metric name
String name = shellMsg.getMetricName();
if (name.isEmpty()) {
throw new RuntimeException("Receive Metrics name is empty");
}
//get metric by name
IMetric iMetric = _context.getRegisteredMetricByName(name);
if (iMetric == null) {
throw new RuntimeException("Could not find metric by name["+name+"] ");
}
if ( !(iMetric instanceof IShellMetric)) {
throw new RuntimeException("Metric["+name+"] is not IShellMetric, can not call by RPC");
}
IShellMetric iShellMetric = (IShellMetric)iMetric;
//call updateMetricFromRPC with params
Object paramsObj = shellMsg.getMetricParams();
try {
iShellMetric.updateMetricFromRPC(paramsObj);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void setHeartbeat() {
lastHeartbeatTimestamp.set(System.currentTimeMillis());
}
private long getLastHeartbeat() {
return lastHeartbeatTimestamp.get();
}
private void die(Throwable exception) {
String processInfo = _process.getProcessInfoString() + _process.getProcessTerminationInfoString();
_exception = new RuntimeException(processInfo, exception);
String message = String.format("Halting process: ShellBolt died. Command: %s, ProcessInfo %s",
Arrays.toString(_command),
processInfo);
LOG.error(message, exception);
_collector.reportError(exception);
if (_running || (exception instanceof Error)) { //don't exit if not running, unless it is an Error
System.exit(11);
}
}
private class BoltHeartbeatTimerTask extends TimerTask {
private ShellBolt bolt;
public BoltHeartbeatTimerTask(ShellBolt bolt) {
this.bolt = bolt;
}
@Override
public void run() {
long currentTimeMillis = System.currentTimeMillis();
long lastHeartbeat = getLastHeartbeat();
LOG.debug("BOLT - current time : {}, last heartbeat : {}, worker timeout (ms) : {}",
currentTimeMillis, lastHeartbeat, workerTimeoutMills);
if (currentTimeMillis - lastHeartbeat > workerTimeoutMills) {
bolt.die(new RuntimeException("subprocess heartbeat timeout"));
}
sendHeartbeatFlag.compareAndSet(false, true);
}
}
private class BoltReaderRunnable implements Runnable {
public void run() {
while (_running) {
try {
ShellMsg shellMsg = _process.readShellMsg();
String command = shellMsg.getCommand();
if (command == null) {
throw new IllegalArgumentException("Command not found in bolt message: " + shellMsg);
}
setHeartbeat();
// We don't need to take care of sync, cause we're always updating heartbeat
switch (command) {
case "ack":
handleAck(shellMsg.getId());
break;
case "fail":
handleFail(shellMsg.getId());
break;
case "error":
handleError(shellMsg.getMsg());
break;
case "log":
_logHandler.log(shellMsg);
break;
case "emit":
handleEmit(shellMsg);
break;
case "metrics":
handleMetrics(shellMsg);
break;
}
} catch (InterruptedException e) {
// It's likely that Bolt is shutting down so no need to die.
// just ignore and loop will be terminated eventually
} catch (Throwable t) {
die(t);
}
}
}
}
private class BoltWriterRunnable implements Runnable {
public void run() {
while (_running) {
try {
if (sendHeartbeatFlag.get()) {
LOG.debug("BOLT - sending heartbeat request to subprocess");
String genId = Long.toString(_rand.nextLong());
_process.writeBoltMsg(createHeartbeatBoltMessage(genId));
sendHeartbeatFlag.compareAndSet(true, false);
}
Object write = _pendingWrites.poll(1, SECONDS);
if (write instanceof BoltMsg) {
_process.writeBoltMsg((BoltMsg) write);
} else if (write instanceof List<?>) {
_process.writeTaskIds((List<Integer>) write);
} else if (write != null) {
throw new RuntimeException(
"Unknown class type to write: " + write.getClass().getName());
}
} catch (InterruptedException e) {
// It's likely that Bolt is shutting down so no need to die.
// just ignore and loop will be terminated eventually
} catch (Throwable t) {
die(t);
}
}
}
private BoltMsg createHeartbeatBoltMessage(String genId) {
BoltMsg msg = new BoltMsg();
msg.setId(genId);
msg.setTask(Constants.SYSTEM_TASK_ID);
msg.setStream(HEARTBEAT_STREAM_ID);
msg.setTuple(new ArrayList<>());
return msg;
}
}
}