001
014
015 package com.liferay.portal.kernel.process;
016
017 import com.liferay.portal.kernel.concurrent.ConcurrentHashSet;
018 import com.liferay.portal.kernel.io.unsync.UnsyncBufferedInputStream;
019 import com.liferay.portal.kernel.io.unsync.UnsyncBufferedOutputStream;
020 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
021 import com.liferay.portal.kernel.log.Log;
022 import com.liferay.portal.kernel.log.LogFactoryUtil;
023 import com.liferay.portal.kernel.process.log.ProcessOutputStream;
024 import com.liferay.portal.kernel.util.ClassLoaderObjectInputStream;
025 import com.liferay.portal.kernel.util.NamedThreadFactory;
026 import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
027 import com.liferay.portal.kernel.util.StreamUtil;
028 import com.liferay.portal.kernel.util.StringPool;
029
030 import java.io.EOFException;
031 import java.io.File;
032 import java.io.FileDescriptor;
033 import java.io.FileOutputStream;
034 import java.io.IOException;
035 import java.io.ObjectInputStream;
036 import java.io.ObjectOutputStream;
037 import java.io.PrintStream;
038 import java.io.Serializable;
039 import java.io.StreamCorruptedException;
040
041 import java.util.ArrayList;
042 import java.util.Collections;
043 import java.util.Iterator;
044 import java.util.List;
045 import java.util.Set;
046 import java.util.concurrent.Callable;
047 import java.util.concurrent.ConcurrentHashMap;
048 import java.util.concurrent.ConcurrentMap;
049 import java.util.concurrent.ExecutionException;
050 import java.util.concurrent.ExecutorService;
051 import java.util.concurrent.Executors;
052 import java.util.concurrent.Future;
053 import java.util.concurrent.RejectedExecutionException;
054 import java.util.concurrent.TimeUnit;
055 import java.util.concurrent.TimeoutException;
056 import java.util.concurrent.atomic.AtomicReference;
057
058
061 public class ProcessExecutor {
062
063 public static <T extends Serializable> Future<T> execute(
064 String classPath, List<String> arguments,
065 ProcessCallable<? extends Serializable> processCallable)
066 throws ProcessException {
067
068 return execute("java", classPath, arguments, processCallable);
069 }
070
071 public static <T extends Serializable> Future<T> execute(
072 String classPath,
073 ProcessCallable<? extends Serializable> processCallable)
074 throws ProcessException {
075
076 return execute(
077 "java", classPath, Collections.<String>emptyList(),
078 processCallable);
079 }
080
081 public static <T extends Serializable> Future<T> execute(
082 String java, String classPath, List<String> arguments,
083 ProcessCallable<? extends Serializable> processCallable)
084 throws ProcessException {
085
086 try {
087 List<String> commands = new ArrayList<String>(arguments.size() + 4);
088
089 commands.add(java);
090 commands.add("-cp");
091 commands.add(classPath);
092 commands.addAll(arguments);
093 commands.add(ProcessExecutor.class.getName());
094
095 ProcessBuilder processBuilder = new ProcessBuilder(commands);
096
097 Process process = processBuilder.start();
098
099 ObjectOutputStream objectOutputStream = new ObjectOutputStream(
100 process.getOutputStream());
101
102 try {
103 objectOutputStream.writeObject(processCallable);
104 }
105 finally {
106 objectOutputStream.close();
107 }
108
109 ExecutorService executorService = _getExecutorService();
110
111 SubprocessReactor subprocessReactor = new SubprocessReactor(
112 process);
113
114 try {
115 Future<ProcessCallable<? extends Serializable>>
116 futureResponseProcessCallable = executorService.submit(
117 subprocessReactor);
118
119
120
121
122 _managedProcesses.add(process);
123
124 return new ProcessExecutionFutureResult<T>(
125 futureResponseProcessCallable, process);
126 }
127 catch (RejectedExecutionException ree) {
128 process.destroy();
129
130 throw new ProcessException(
131 "Cancelled execution because of a concurrent destroy", ree);
132 }
133 }
134 catch (IOException ioe) {
135 throw new ProcessException(ioe);
136 }
137 }
138
139 public static void main(String[] arguments)
140 throws ClassNotFoundException, IOException {
141
142 PrintStream oldOutPrintStream = System.out;
143
144 ObjectOutputStream objectOutputStream = null;
145 ProcessOutputStream outProcessOutputStream = null;
146
147 synchronized (oldOutPrintStream) {
148 oldOutPrintStream.flush();
149
150 FileOutputStream fileOutputStream = new FileOutputStream(
151 FileDescriptor.out);
152
153 objectOutputStream = new ObjectOutputStream(
154 new UnsyncBufferedOutputStream(fileOutputStream));
155
156 outProcessOutputStream = new ProcessOutputStream(
157 objectOutputStream, false);
158
159 ProcessContext._setProcessOutputStream(outProcessOutputStream);
160
161 PrintStream newOutPrintStream = new PrintStream(
162 outProcessOutputStream, true);
163
164 System.setOut(newOutPrintStream);
165 }
166
167 ProcessOutputStream errProcessOutputStream = new ProcessOutputStream(
168 objectOutputStream, true);
169
170 PrintStream errPrintStream = new PrintStream(
171 errProcessOutputStream, true);
172
173 System.setErr(errPrintStream);
174
175 try {
176 ObjectInputStream objectInputStream = new ObjectInputStream(
177 System.in);
178
179 ProcessCallable<?> processCallable =
180 (ProcessCallable<?>)objectInputStream.readObject();
181
182 String logPrefixString =
183 StringPool.OPEN_BRACKET.concat(
184 processCallable.toString()).concat(
185 StringPool.CLOSE_BRACKET);
186
187 byte[] logPrefix = logPrefixString.getBytes(StringPool.UTF8);
188
189 outProcessOutputStream.setLogPrefix(logPrefix);
190 errProcessOutputStream.setLogPrefix(logPrefix);
191
192 Serializable result = processCallable.call();
193
194 System.out.flush();
195
196 outProcessOutputStream.writeProcessCallable(
197 new ReturnProcessCallable<Serializable>(result));
198
199 outProcessOutputStream.flush();
200 }
201 catch (ProcessException pe) {
202 errPrintStream.flush();
203
204 errProcessOutputStream.writeProcessCallable(
205 new ExceptionProcessCallable(pe));
206
207 errProcessOutputStream.flush();
208 }
209 }
210
211 public void destroy() {
212 if (_executorService == null) {
213 return;
214 }
215
216 synchronized (ProcessExecutor.class) {
217 if (_executorService != null) {
218 _executorService.shutdownNow();
219
220
221
222
223
224
225
226
227 Iterator<Process> iterator = _managedProcesses.iterator();
228
229 while (iterator.hasNext()) {
230 Process process = iterator.next();
231
232 process.destroy();
233
234 iterator.remove();
235 }
236
237
238
239
240
241
242 _managedProcesses.clear();
243
244 _executorService = null;
245 }
246 }
247 }
248
249 public static class ProcessContext {
250
251 public static boolean attach(
252 String message, long interval, ShutdownHook shutdownHook) {
253
254 HeartbeatThread heartbeatThread = new HeartbeatThread(
255 message, interval, shutdownHook);
256
257 boolean value = _heartbeatThreadReference.compareAndSet(
258 null, heartbeatThread);
259
260 if (value) {
261 heartbeatThread.start();
262 }
263
264 return value;
265 }
266
267 public static void detach() throws InterruptedException {
268 HeartbeatThread heartbeatThread =
269 _heartbeatThreadReference.getAndSet(null);
270
271 if (heartbeatThread != null) {
272 heartbeatThread.detach();
273 heartbeatThread.join();
274 }
275 }
276
277 public static ConcurrentMap<String, Object> getAttributes() {
278 return _attributes;
279 }
280
281 public static ProcessOutputStream getProcessOutputStream() {
282 return _processOutputStream;
283 }
284
285 public static boolean isAttached() {
286 HeartbeatThread attachThread = _heartbeatThreadReference.get();
287
288 if (attachThread != null) {
289 return true;
290 }
291 else {
292 return false;
293 }
294 }
295
296 private static void _setProcessOutputStream(
297 ProcessOutputStream processOutputStream) {
298
299 _processOutputStream = processOutputStream;
300 }
301
302 private ProcessContext() {
303 }
304
305 private static ConcurrentMap<String, Object> _attributes =
306 new ConcurrentHashMap<String, Object>();
307 private static AtomicReference<HeartbeatThread>
308 _heartbeatThreadReference = new AtomicReference<HeartbeatThread>();
309 private static ProcessOutputStream _processOutputStream;
310
311 }
312
313 public static interface ShutdownHook {
314
315 public static final int BROKEN_PIPE_CODE = 1;
316
317 public static final int INTERRUPTION_CODE = 2;
318
319 public static final int UNKNOWN_CODE = 3;
320
321 public boolean shutdown(int shutdownCode, Throwable shutdownThrowable);
322
323 }
324
325 private static ExecutorService _getExecutorService() {
326 if (_executorService != null) {
327 return _executorService;
328 }
329
330 synchronized (ProcessExecutor.class) {
331 if (_executorService == null) {
332 _executorService = Executors.newCachedThreadPool(
333 new NamedThreadFactory(
334 ProcessExecutor.class.getName(), Thread.MIN_PRIORITY,
335 PortalClassLoaderUtil.getClassLoader()));
336 }
337 }
338
339 return _executorService;
340 }
341
342 private static volatile ExecutorService _executorService;
343 private static Set<Process> _managedProcesses =
344 new ConcurrentHashSet<Process>();
345
346 private static class HeartbeatThread extends Thread {
347
348 public HeartbeatThread(
349 String message, long interval, ShutdownHook shutdownHook) {
350
351 if (shutdownHook == null) {
352 throw new IllegalArgumentException("Shutdown hook is null");
353 }
354
355 _interval = interval;
356 _shutdownHook = shutdownHook;
357
358 _pringBackProcessCallable = new PingbackProcessCallable(message);
359
360 setDaemon(true);
361 setName(HeartbeatThread.class.getSimpleName());
362 }
363
364 public void detach() {
365 _detach = true;
366
367 interrupt();
368 }
369
370 @Override
371 public void run() {
372 ProcessOutputStream processOutputStream =
373 ProcessContext.getProcessOutputStream();
374
375 int shutdownCode = 0;
376 Throwable shutdownThrowable = null;
377
378 while (!_detach) {
379 try {
380 sleep(_interval);
381
382 processOutputStream.writeProcessCallable(
383 _pringBackProcessCallable);
384 }
385 catch (InterruptedException ie) {
386 if (_detach) {
387 return;
388 }
389 else {
390 shutdownThrowable = ie;
391
392 shutdownCode = ShutdownHook.INTERRUPTION_CODE;
393 }
394 }
395 catch (IOException ioe) {
396 shutdownThrowable = ioe;
397
398 shutdownCode = ShutdownHook.BROKEN_PIPE_CODE;
399 }
400 catch (Throwable throwable) {
401 shutdownThrowable = throwable;
402
403 shutdownCode = ShutdownHook.UNKNOWN_CODE;
404 }
405
406 if (shutdownCode != 0) {
407 _detach = _shutdownHook.shutdown(
408 shutdownCode, shutdownThrowable);
409 }
410 }
411 }
412
413 private volatile boolean _detach;
414 private final long _interval;
415 private final ProcessCallable<String> _pringBackProcessCallable;
416 private final ShutdownHook _shutdownHook;
417
418 }
419
420 private static class PingbackProcessCallable
421 implements ProcessCallable<String> {
422
423 public PingbackProcessCallable(String message) {
424 _message = message;
425 }
426
427 @Override
428 public String call() {
429 return _message;
430 }
431
432 private static final long serialVersionUID = 1L;
433
434 private final String _message;
435
436 }
437
438 private static class ProcessExecutionFutureResult<T> implements Future<T> {
439
440 public ProcessExecutionFutureResult(
441 Future<ProcessCallable<? extends Serializable>> future,
442 Process process) {
443
444 _future = future;
445 _process = process;
446 }
447
448 @Override
449 public boolean cancel(boolean mayInterruptIfRunning) {
450 if (_future.isCancelled() || _future.isDone()) {
451 return false;
452 }
453
454 _future.cancel(true);
455 _process.destroy();
456
457 return true;
458 }
459
460 @Override
461 public boolean isCancelled() {
462 return _future.isCancelled();
463 }
464
465 @Override
466 public boolean isDone() {
467 return _future.isDone();
468 }
469
470 @Override
471 public T get() throws ExecutionException, InterruptedException {
472 ProcessCallable<?> processCallable = _future.get();
473
474 return get(processCallable);
475 }
476
477 @Override
478 public T get(long timeout, TimeUnit timeUnit)
479 throws ExecutionException, InterruptedException, TimeoutException {
480
481 ProcessCallable<?> processCallable = _future.get(timeout, timeUnit);
482
483 return get(processCallable);
484 }
485
486 private T get(ProcessCallable<?> processCallable)
487 throws ExecutionException {
488
489 try {
490 if (processCallable instanceof ReturnProcessCallable<?>) {
491 return (T)processCallable.call();
492 }
493
494 ExceptionProcessCallable exceptionProcessCallable =
495 (ExceptionProcessCallable)processCallable;
496
497 throw exceptionProcessCallable.call();
498 }
499 catch (ProcessException pe) {
500 throw new ExecutionException(pe);
501 }
502 }
503
504 private final Future<ProcessCallable<?>> _future;
505 private final Process _process;
506
507 }
508
509 private static class SubprocessReactor
510 implements Callable<ProcessCallable<? extends Serializable>> {
511
512 public SubprocessReactor(Process process) {
513 _process = process;
514 }
515
516 @Override
517 public ProcessCallable<? extends Serializable> call() throws Exception {
518 ProcessCallable<?> resultProcessCallable = null;
519
520 UnsyncBufferedInputStream unsyncBufferedInputStream =
521 new UnsyncBufferedInputStream(_process.getInputStream());
522
523 try {
524 ObjectInputStream objectInputStream = null;
525
526 UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
527 new UnsyncByteArrayOutputStream();
528
529 while (true) {
530 try {
531
532
533
534 unsyncBufferedInputStream.mark(4);
535
536 objectInputStream = new ClassLoaderObjectInputStream(
537 unsyncBufferedInputStream,
538 PortalClassLoaderUtil.getClassLoader());
539
540
541
542
543 if (unsyncByteArrayOutputStream.size() > 0) {
544 if (_log.isWarnEnabled()) {
545 _log.warn(
546 "Found corrupt leading log " +
547 unsyncByteArrayOutputStream.toString());
548 }
549 }
550
551 unsyncByteArrayOutputStream = null;
552
553 break;
554 }
555 catch (StreamCorruptedException sce) {
556
557
558
559 unsyncBufferedInputStream.reset();
560
561 unsyncByteArrayOutputStream.write(
562 unsyncBufferedInputStream.read());
563 }
564 }
565
566 while (true) {
567 ProcessCallable<?> processCallable =
568 (ProcessCallable<?>)objectInputStream.readObject();
569
570 if ((processCallable instanceof ExceptionProcessCallable) ||
571 (processCallable instanceof ReturnProcessCallable<?>)) {
572
573 resultProcessCallable = processCallable;
574
575 continue;
576 }
577
578 Serializable returnValue = processCallable.call();
579
580 if (_log.isDebugEnabled()) {
581 _log.debug(
582 "Invoked generic process callable " +
583 processCallable + " with return value " +
584 returnValue);
585 }
586 }
587 }
588 catch (StreamCorruptedException sce) {
589 File file = File.createTempFile(
590 "corrupted-stream-dump-" + System.currentTimeMillis(),
591 ".log");
592
593 _log.error(
594 "Dumping content of corrupted object input stream to " +
595 file.getAbsolutePath(),
596 sce);
597
598 FileOutputStream fileOutputStream = new FileOutputStream(file);
599
600 StreamUtil.transfer(
601 unsyncBufferedInputStream, fileOutputStream);
602
603 throw new ProcessException(
604 "Corrupted object input stream", sce);
605 }
606 catch (EOFException eofe) {
607 throw new ProcessException(
608 "Subprocess piping back ended prematurely", eofe);
609 }
610 finally {
611 try {
612 int exitCode = _process.waitFor();
613
614 if (exitCode != 0) {
615 throw new ProcessException(
616 "Subprocess terminated with exit code " + exitCode);
617 }
618 }
619 catch (InterruptedException ie) {
620 _process.destroy();
621
622 throw new ProcessException(
623 "Forcibly killed subprocess on interruption", ie);
624 }
625
626 _managedProcesses.remove(_process);
627
628 if (resultProcessCallable != null) {
629
630
631
632 return resultProcessCallable;
633 }
634 }
635 }
636
637 private static Log _log = LogFactoryUtil.getLog(
638 SubprocessReactor.class);
639
640 private final Process _process;
641
642 }
643
644 }