View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.helper;
17  
18  import java.io.IOException;
19  import java.io.OutputStream;
20  import java.util.List;
21  import java.util.Set;
22  import java.util.concurrent.ConcurrentHashMap;
23  import java.util.concurrent.CountDownLatch;
24  import java.util.concurrent.TimeUnit;
25  import java.util.function.Consumer;
26  
27  import javax.annotation.PreDestroy;
28  
29  import org.apache.commons.io.IOUtils;
30  import org.codelibs.core.io.CloseableUtil;
31  import org.codelibs.fess.Constants;
32  import org.codelibs.fess.exception.JobNotFoundException;
33  import org.codelibs.fess.exception.JobProcessingException;
34  import org.codelibs.fess.util.InputStreamThread;
35  import org.codelibs.fess.util.JobProcess;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  public class ProcessHelper {
40      private static final Logger logger = LoggerFactory.getLogger(ProcessHelper.class);
41  
42      protected final ConcurrentHashMap<String, JobProcess> runningProcessMap = new ConcurrentHashMap<>();
43  
44      protected int processDestroyTimeout = 10;
45  
46      @PreDestroy
47      public void destroy() {
48          for (final String sessionId : runningProcessMap.keySet()) {
49              if (logger.isInfoEnabled()) {
50                  logger.info("Stopping process " + sessionId);
51              }
52              if (destroyProcess(sessionId) == 0) {
53                  if (logger.isInfoEnabled()) {
54                      logger.info("Stopped process " + sessionId);
55                  }
56              }
57          }
58      }
59  
60      public synchronized JobProcess startProcess(final String sessionId, final List<String> cmdList, final Consumer<ProcessBuilder> pbCall) {
61          final ProcessBuilder pb = new ProcessBuilder(cmdList);
62          pbCall.accept(pb);
63          destroyProcess(sessionId);
64          JobProcess jobProcess;
65          try {
66              jobProcess = new JobProcess(pb.start());
67              destroyProcess(sessionId, runningProcessMap.putIfAbsent(sessionId, jobProcess));
68              return jobProcess;
69          } catch (final IOException e) {
70              throw new JobProcessingException("Crawler Process terminated.", e);
71          }
72      }
73  
74      public int destroyProcess(final String sessionId) {
75          final JobProcess jobProcess = runningProcessMap.remove(sessionId);
76          return destroyProcess(sessionId, jobProcess);
77      }
78  
79      public boolean isProcessRunning() {
80          return !runningProcessMap.isEmpty();
81      }
82  
83      public boolean isProcessRunning(final String sessionId) {
84          final JobProcess jobProcess = runningProcessMap.get(sessionId);
85          return jobProcess != null && jobProcess.getProcess().isAlive();
86      }
87  
88      protected int destroyProcess(final String sessionId, final JobProcess jobProcess) {
89          if (jobProcess != null) {
90              final InputStreamThread ist = jobProcess.getInputStreamThread();
91              try {
92                  ist.interrupt();
93              } catch (final Exception e) {
94                  logger.warn("Could not interrupt a thread of an input stream.", e);
95              }
96  
97              final CountDownLatch latch = new CountDownLatch(3);
98              final Process process = jobProcess.getProcess();
99              new Thread(() -> {
100                 try {
101                     CloseableUtil.closeQuietly(process.getInputStream());
102                 } catch (final Exception e) {
103                     logger.warn("Could not close a process input stream.", e);
104                 } finally {
105                     latch.countDown();
106                 }
107             }, "ProcessCloser-input-" + sessionId).start();
108             new Thread(() -> {
109                 try {
110                     CloseableUtil.closeQuietly(process.getErrorStream());
111                 } catch (final Exception e) {
112                     logger.warn("Could not close a process error stream.", e);
113                 } finally {
114                     latch.countDown();
115                 }
116             }, "ProcessCloser-error-" + sessionId).start();
117             new Thread(() -> {
118                 try {
119                     CloseableUtil.closeQuietly(process.getOutputStream());
120                 } catch (final Exception e) {
121                     logger.warn("Could not close a process output stream.", e);
122                 } finally {
123                     latch.countDown();
124                 }
125             }, "ProcessCloser-output-" + sessionId).start();
126 
127             try {
128                 latch.await(10, TimeUnit.SECONDS);
129             } catch (final InterruptedException e) {
130                 logger.warn("Interrupted to wait a process.", e);
131             }
132             try {
133                 process.destroyForcibly().waitFor(processDestroyTimeout, TimeUnit.SECONDS);
134                 return process.exitValue();
135             } catch (final Exception e) {
136                 logger.error("Could not destroy a process correctly.", e);
137             }
138         }
139         return -1;
140     }
141 
142     public Set<String> getRunningSessionIdSet() {
143         return runningProcessMap.keySet();
144     }
145 
146     public void setProcessDestroyTimeout(final int processDestroyTimeout) {
147         this.processDestroyTimeout = processDestroyTimeout;
148     }
149 
150     public void sendCommand(final String sessionId, final String command) {
151         final JobProcess jobProcess = runningProcessMap.get(sessionId);
152         if (jobProcess != null) {
153             try {
154                 final OutputStream out = jobProcess.getProcess().getOutputStream();
155                 IOUtils.write(command + "\n", out, Constants.CHARSET_UTF_8);
156                 out.flush();
157             } catch (final IOException e) {
158                 throw new JobProcessingException(e);
159             }
160         } else {
161             throw new JobNotFoundException("Job for " + sessionId + " is not found.");
162         }
163     }
164 }