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