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.job;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.File;
21  import java.io.FileOutputStream;
22  import java.util.ArrayList;
23  import java.util.List;
24  import java.util.Properties;
25  
26  import javax.servlet.ServletContext;
27  
28  import org.apache.commons.lang3.RandomStringUtils;
29  import org.apache.commons.lang3.SystemUtils;
30  import org.codelibs.core.lang.StringUtil;
31  import org.codelibs.fess.Constants;
32  import org.codelibs.fess.exception.FessSystemException;
33  import org.codelibs.fess.exec.SuggestCreator;
34  import org.codelibs.fess.helper.ProcessHelper;
35  import org.codelibs.fess.mylasta.direction.FessConfig;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.codelibs.fess.util.InputStreamThread;
38  import org.codelibs.fess.util.JobProcess;
39  import org.codelibs.fess.util.ResourceUtil;
40  import org.slf4j.Logger;
41  import org.slf4j.LoggerFactory;
42  
43  public class SuggestJob extends ExecJob {
44  
45      private static final Logger logger = LoggerFactory.getLogger(SuggestJob.class);
46  
47      @Deprecated
48      public String execute(final JobExecutor jobExecutor) {
49          jobExecutor(jobExecutor);
50          return execute();
51      }
52  
53      @Override
54      public String execute() {
55          final StringBuilder resultBuf = new StringBuilder();
56  
57          if (sessionId == null) { // create session id
58              sessionId = RandomStringUtils.randomAlphabetic(15);
59          }
60          resultBuf.append("Session Id: ").append(sessionId).append("\n");
61          if (jobExecutor != null) {
62              jobExecutor.addShutdownListener(() -> ComponentUtil.getProcessHelper().destroyProcess(sessionId));
63          }
64  
65          try {
66              executeSuggestCreator();
67          } catch (final Exception e) {
68              logger.warn("Failed to create suggest data.", e);
69              resultBuf.append(e.getMessage()).append("\n");
70          }
71  
72          return resultBuf.toString();
73  
74      }
75  
76      protected void executeSuggestCreator() {
77          final List<String> cmdList = new ArrayList<>();
78          final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
79          final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
80          final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
81          final FessConfig fessConfig = ComponentUtil.getFessConfig();
82  
83          cmdList.add(fessConfig.getJavaCommandPath());
84  
85          // -cp
86          cmdList.add("-cp");
87          final StringBuilder buf = new StringBuilder(100);
88          ResourceUtil.getOverrideConfPath().ifPresent(p -> {
89              buf.append(p);
90              buf.append(cpSeparator);
91          });
92          final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
93          if (StringUtil.isNotBlank(confPath)) {
94              buf.append(confPath);
95              buf.append(cpSeparator);
96          }
97          // WEB-INF/env/suggest/resources
98          buf.append("WEB-INF");
99          buf.append(File.separator);
100         buf.append("env");
101         buf.append(File.separator);
102         buf.append(getExecuteType());
103         buf.append(File.separator);
104         buf.append("resources");
105         buf.append(cpSeparator);
106         // WEB-INF/classes
107         buf.append("WEB-INF");
108         buf.append(File.separator);
109         buf.append("classes");
110         // target/classes
111         final String userDir = System.getProperty("user.dir");
112         final File targetDir = new File(userDir, "target");
113         final File targetClassesDir = new File(targetDir, "classes");
114         if (targetClassesDir.isDirectory()) {
115             buf.append(cpSeparator);
116             buf.append(targetClassesDir.getAbsolutePath());
117         }
118         // WEB-INF/lib
119         appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")), "WEB-INF" + File.separator + "lib"
120                 + File.separator);
121         // WEB-INF/env/suggest/lib
122         appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/" + getExecuteType() + "/lib")), "WEB-INF"
123                 + File.separator + "env" + File.separator + getExecuteType() + File.separator + "lib" + File.separator);
124         final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
125         if (targetLibDir.isDirectory()) {
126             appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
127         }
128         cmdList.add(buf.toString());
129 
130         if (useLocalElasticsearch) {
131             final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
132             if (StringUtil.isNotBlank(httpAddress)) {
133                 cmdList.add("-D" + Constants.FESS_ES_HTTP_ADDRESS + "=" + httpAddress);
134             }
135         }
136 
137         final String systemLastaEnv = System.getProperty("lasta.env");
138         if (StringUtil.isNotBlank(systemLastaEnv)) {
139             if (systemLastaEnv.equals("web")) {
140                 cmdList.add("-Dlasta.env=" + getExecuteType());
141             } else {
142                 cmdList.add("-Dlasta.env=" + systemLastaEnv);
143             }
144         } else if (StringUtil.isNotBlank(lastaEnv)) {
145             cmdList.add("-Dlasta.env=" + lastaEnv);
146         }
147 
148         addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
149         cmdList.add("-Dfess." + getExecuteType() + ".process=true");
150         if (logFilePath == null) {
151             final String value = System.getProperty("fess.log.path");
152             logFilePath = value != null ? value : new File(targetDir, "logs").getAbsolutePath();
153         }
154         cmdList.add("-Dfess.log.path=" + logFilePath);
155         addSystemProperty(cmdList, "fess.log.name", "fess-" + getExecuteType(), "-" + getExecuteType());
156         if (logLevel == null) {
157             addSystemProperty(cmdList, "fess.log.level", null, null);
158         } else {
159             cmdList.add("-Dfess.log.level=" + logLevel);
160         }
161         stream(fessConfig.getJvmSuggestOptionsAsArray()).of(
162                 stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));
163 
164         File ownTmpDir = null;
165         final String tmpDir = System.getProperty("java.io.tmpdir");
166         if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
167             ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
168             if (ownTmpDir.mkdirs()) {
169                 cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
170             } else {
171                 ownTmpDir = null;
172             }
173         }
174 
175         if (!jvmOptions.isEmpty()) {
176             jvmOptions.stream().filter(StringUtil::isNotBlank).forEach(cmdList::add);
177         }
178 
179         cmdList.add(SuggestCreator.class.getCanonicalName());
180 
181         cmdList.add("--sessionId");
182         cmdList.add(sessionId);
183 
184         File propFile = null;
185         try {
186             cmdList.add("-p");
187             propFile = File.createTempFile(getExecuteType() + "_", ".properties");
188             cmdList.add(propFile.getAbsolutePath());
189             try (FileOutputStream out = new FileOutputStream(propFile)) {
190                 final Properties prop = new Properties();
191                 prop.putAll(ComponentUtil.getSystemProperties());
192                 prop.store(out, cmdList.toString());
193             }
194 
195             final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();
196 
197             if (logger.isInfoEnabled()) {
198                 logger.info("SuggestCreator: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
199             }
200 
201             final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
202                 pb.directory(baseDir);
203                 pb.redirectErrorStream(true);
204             });
205 
206             final InputStreamThread it = jobProcess.getInputStreamThread();
207             it.start();
208 
209             final Process currentProcess = jobProcess.getProcess();
210             currentProcess.waitFor();
211             it.join(5000);
212 
213             final int exitValue = currentProcess.exitValue();
214 
215             if (logger.isInfoEnabled()) {
216                 logger.info("SuggestCreator: Exit Code=" + exitValue + " - SuggestCreator Process Output:\n" + it.getOutput());
217             }
218             if (exitValue != 0) {
219                 throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
220             }
221             ComponentUtil.getPopularWordHelper().clearCache();
222         } catch (final FessSystemException e) {
223             throw e;
224         } catch (final InterruptedException e) {
225             logger.warn("SuggestCreator Process interrupted.");
226         } catch (final Exception e) {
227             throw new FessSystemException("SuggestCreator Process terminated.", e);
228         } finally {
229             try {
230                 processHelper.destroyProcess(sessionId);
231             } finally {
232                 if (propFile != null && !propFile.delete()) {
233                     logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
234                 }
235                 deleteTempDir(ownTmpDir);
236             }
237         }
238     }
239 
240     @Override
241     protected String getExecuteType() {
242         return "suggest";
243     }
244 
245 }