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.text.SimpleDateFormat;
23  import java.util.ArrayList;
24  import java.util.Date;
25  import java.util.List;
26  import java.util.Properties;
27  import java.util.concurrent.atomic.AtomicInteger;
28  
29  import javax.servlet.ServletContext;
30  
31  import org.apache.commons.lang3.StringUtils;
32  import org.apache.commons.lang3.SystemUtils;
33  import org.codelibs.core.lang.StringUtil;
34  import org.codelibs.fess.Constants;
35  import org.codelibs.fess.es.config.exbhv.ScheduledJobBhv;
36  import org.codelibs.fess.exception.FessSystemException;
37  import org.codelibs.fess.exec.Crawler;
38  import org.codelibs.fess.helper.ProcessHelper;
39  import org.codelibs.fess.helper.SystemHelper;
40  import org.codelibs.fess.mylasta.direction.FessConfig;
41  import org.codelibs.fess.util.ComponentUtil;
42  import org.codelibs.fess.util.InputStreamThread;
43  import org.codelibs.fess.util.JobProcess;
44  import org.codelibs.fess.util.ResourceUtil;
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  public class CrawlJob extends ExecJob {
49  
50      private static final Logger logger = LoggerFactory.getLogger(CrawlJob.class);
51  
52      protected String namespace = Constants.CRAWLING_INFO_SYSTEM_NAME;
53  
54      protected String[] webConfigIds;
55  
56      protected String[] fileConfigIds;
57  
58      protected String[] dataConfigIds;
59  
60      protected int documentExpires = -2;
61  
62      public CrawlJob namespace(final String namespace) {
63          this.namespace = namespace;
64          return this;
65      }
66  
67      public CrawlJob documentExpires(final int documentExpires) {
68          this.documentExpires = documentExpires;
69          return this;
70      }
71  
72      public CrawlJob webConfigIds(final String[] webConfigIds) {
73          this.webConfigIds = webConfigIds;
74          return this;
75      }
76  
77      public CrawlJob fileConfigIds(final String[] fileConfigIds) {
78          this.fileConfigIds = fileConfigIds;
79          return this;
80      }
81  
82      public CrawlJob dataConfigIds(final String[] dataConfigIds) {
83          this.dataConfigIds = dataConfigIds;
84          return this;
85      }
86  
87      @Deprecated
88      public String execute(final JobExecutor jobExecutor) {
89          jobExecutor(jobExecutor);
90          return execute();
91      }
92  
93      @Override
94      public String execute() {
95          //   check # of crawler processes
96          final int maxCrawlerProcesses = ComponentUtil.getFessConfig().getJobMaxCrawlerProcessesAsInteger();
97          if (maxCrawlerProcesses > 0) {
98              final int runningJobCount = getRunningJobCount();
99              if (runningJobCount > maxCrawlerProcesses) {
100                 throw new FessSystemException(runningJobCount + " crawler processes are running. Max processes are " + maxCrawlerProcesses
101                         + ".");
102             }
103         }
104 
105         final StringBuilder resultBuf = new StringBuilder(100);
106         final boolean runAll = webConfigIds == null && fileConfigIds == null && dataConfigIds == null;
107 
108         if (sessionId == null) { // create session id
109             final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
110             sessionId = sdf.format(new Date());
111         }
112         resultBuf.append("Session Id: ").append(sessionId).append("\n");
113         resultBuf.append("Web  Config Id:");
114         if (webConfigIds == null) {
115             if (runAll) {
116                 resultBuf.append(" ALL\n");
117             } else {
118                 resultBuf.append(" NONE\n");
119             }
120         } else {
121             for (final String id : webConfigIds) {
122                 resultBuf.append(' ').append(id);
123             }
124             resultBuf.append('\n');
125         }
126         resultBuf.append("File Config Id:");
127         if (fileConfigIds == null) {
128             if (runAll) {
129                 resultBuf.append(" ALL\n");
130             } else {
131                 resultBuf.append(" NONE\n");
132             }
133         } else {
134             for (final String id : fileConfigIds) {
135                 resultBuf.append(' ').append(id);
136             }
137             resultBuf.append('\n');
138         }
139         resultBuf.append("Data Config Id:");
140         if (dataConfigIds == null) {
141             if (runAll) {
142                 resultBuf.append(" ALL\n");
143             } else {
144                 resultBuf.append(" NONE\n");
145             }
146         } else {
147             for (final String id : dataConfigIds) {
148                 resultBuf.append(' ').append(id);
149             }
150             resultBuf.append('\n');
151         }
152 
153         if (jobExecutor != null) {
154             jobExecutor.addShutdownListener(() -> ComponentUtil.getProcessHelper().destroyProcess(sessionId));
155         }
156 
157         try {
158             executeCrawler();
159             ComponentUtil.getKeyMatchHelper().update();
160         } catch (final FessSystemException e) {
161             throw e;
162         } catch (final Exception e) {
163             throw new FessSystemException("Failed to execute a crawl job.", e);
164         }
165 
166         return resultBuf.toString();
167 
168     }
169 
170     protected int getRunningJobCount() {
171         final AtomicInteger counter = new AtomicInteger(0);
172         final FessConfig fessConfig = ComponentUtil.getFessConfig();
173         ComponentUtil.getComponent(ScheduledJobBhv.class).selectCursor(cb -> {
174             cb.query().setAvailable_Equal(Constants.T);
175             cb.query().setCrawler_Equal(Constants.T);
176         }, scheduledJob -> {
177             if (fessConfig.isSchedulerTarget(scheduledJob.getTarget())) {
178                 if (scheduledJob.isRunning()) {
179                     if (logger.isDebugEnabled()) {
180                         logger.debug(scheduledJob.getId() + " is running.");
181                     }
182                     counter.incrementAndGet();
183                 } else if (logger.isDebugEnabled()) {
184                     logger.debug(scheduledJob.getId() + " is not running.");
185                 }
186             }
187         });
188         return counter.get();
189     }
190 
191     protected void executeCrawler() {
192         final List<String> cmdList = new ArrayList<>();
193         final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
194         final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
195         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
196         final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
197         final FessConfig fessConfig = ComponentUtil.getFessConfig();
198 
199         cmdList.add(fessConfig.getJavaCommandPath());
200 
201         // -cp
202         cmdList.add("-cp");
203         final StringBuilder buf = new StringBuilder(100);
204         ResourceUtil.getOverrideConfPath().ifPresent(p -> {
205             buf.append(p);
206             buf.append(cpSeparator);
207         });
208         final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
209         if (StringUtil.isNotBlank(confPath)) {
210             buf.append(confPath);
211             buf.append(cpSeparator);
212         }
213         // WEB-INF/env/crawler/resources
214         buf.append("WEB-INF");
215         buf.append(File.separator);
216         buf.append("env");
217         buf.append(File.separator);
218         buf.append(getExecuteType());
219         buf.append(File.separator);
220         buf.append("resources");
221         buf.append(cpSeparator);
222         // WEB-INF/classes
223         buf.append("WEB-INF");
224         buf.append(File.separator);
225         buf.append("classes");
226         // target/classes
227         final String userDir = System.getProperty("user.dir");
228         final File targetDir = new File(userDir, "target");
229         final File targetClassesDir = new File(targetDir, "classes");
230         if (targetClassesDir.isDirectory()) {
231             buf.append(cpSeparator);
232             buf.append(targetClassesDir.getAbsolutePath());
233         }
234         // WEB-INF/lib
235         appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")), "WEB-INF" + File.separator + "lib"
236                 + File.separator);
237         // WEB-INF/env/crawler/lib
238         appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/" + getExecuteType() + "/lib")), "WEB-INF"
239                 + File.separator + "env" + File.separator + getExecuteType() + File.separator + "lib" + File.separator);
240         final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
241         if (targetLibDir.isDirectory()) {
242             appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
243         }
244         cmdList.add(buf.toString());
245 
246         if (useLocalElasticsearch) {
247             final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
248             if (StringUtil.isNotBlank(httpAddress)) {
249                 cmdList.add("-D" + Constants.FESS_ES_HTTP_ADDRESS + "=" + httpAddress);
250             }
251         }
252 
253         final String systemLastaEnv = System.getProperty("lasta.env");
254         if (StringUtil.isNotBlank(systemLastaEnv)) {
255             if (systemLastaEnv.equals("web")) {
256                 cmdList.add("-Dlasta.env=" + getExecuteType());
257             } else {
258                 cmdList.add("-Dlasta.env=" + systemLastaEnv);
259             }
260         } else if (StringUtil.isNotBlank(lastaEnv)) {
261             cmdList.add("-Dlasta.env=" + lastaEnv);
262         }
263 
264         addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
265         cmdList.add("-Dfess." + getExecuteType() + ".process=true");
266         cmdList.add("-Dfess.log.path=" + (logFilePath != null ? logFilePath : systemHelper.getLogFilePath()));
267         addSystemProperty(cmdList, "fess.log.name", "fess-" + getExecuteType(), "-" + getExecuteType());
268         if (logLevel == null) {
269             addSystemProperty(cmdList, "fess.log.level", null, null);
270         } else {
271             cmdList.add("-Dfess.log.level=" + logLevel);
272             if (logLevel.equalsIgnoreCase("debug")) {
273                 cmdList.add("-Dorg.apache.tika.service.error.warn=true");
274             }
275         }
276         stream(fessConfig.getJvmCrawlerOptionsAsArray()).of(
277                 stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));
278 
279         File ownTmpDir = null;
280         final String tmpDir = System.getProperty("java.io.tmpdir");
281         if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
282             ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
283             if (ownTmpDir.mkdirs()) {
284                 cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
285                 cmdList.add("-Dpdfbox.fontcache=" + ownTmpDir.getAbsolutePath());
286             } else {
287                 ownTmpDir = null;
288             }
289         }
290 
291         cmdList.add(ComponentUtil.getThumbnailManager().getThumbnailPathOption());
292 
293         if (!jvmOptions.isEmpty()) {
294             jvmOptions.stream().filter(StringUtil::isNotBlank).forEach(cmdList::add);
295         }
296 
297         cmdList.add(Crawler.class.getCanonicalName());
298 
299         cmdList.add("--sessionId");
300         cmdList.add(sessionId);
301         cmdList.add("--name");
302         cmdList.add(namespace);
303 
304         if (webConfigIds != null && webConfigIds.length > 0) {
305             cmdList.add("-w");
306             cmdList.add(StringUtils.join(webConfigIds, ','));
307         }
308         if (fileConfigIds != null && fileConfigIds.length > 0) {
309             cmdList.add("-f");
310             cmdList.add(StringUtils.join(fileConfigIds, ','));
311         }
312         if (dataConfigIds != null && dataConfigIds.length > 0) {
313             cmdList.add("-d");
314             cmdList.add(StringUtils.join(dataConfigIds, ','));
315         }
316         if (documentExpires >= -1) {
317             cmdList.add("-e");
318             cmdList.add(Integer.toString(documentExpires));
319         }
320 
321         File propFile = null;
322         try {
323             cmdList.add("-p");
324             propFile = File.createTempFile(getExecuteType() + "_", ".properties");
325             cmdList.add(propFile.getAbsolutePath());
326             try (FileOutputStream out = new FileOutputStream(propFile)) {
327                 final Properties prop = new Properties();
328                 prop.putAll(ComponentUtil.getSystemProperties());
329                 prop.store(out, cmdList.toString());
330             }
331 
332             final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();
333 
334             if (logger.isInfoEnabled()) {
335                 logger.info("Crawler: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
336             }
337 
338             final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
339                 pb.directory(baseDir);
340                 pb.redirectErrorStream(true);
341             });
342 
343             final InputStreamThread it = jobProcess.getInputStreamThread();
344             it.start();
345 
346             final Process currentProcess = jobProcess.getProcess();
347             currentProcess.waitFor();
348             it.join(5000);
349 
350             final int exitValue = currentProcess.exitValue();
351 
352             if (logger.isInfoEnabled()) {
353                 logger.info("Crawler: Exit Code=" + exitValue + " - Crawler Process Output:\n" + it.getOutput());
354             }
355             if (exitValue != 0) {
356                 throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
357             }
358         } catch (final FessSystemException e) {
359             throw e;
360         } catch (final InterruptedException e) {
361             logger.warn("Crawler Process interrupted.");
362         } catch (final Exception e) {
363             throw new FessSystemException("Crawler Process terminated.", e);
364         } finally {
365             try {
366                 processHelper.destroyProcess(sessionId);
367             } finally {
368                 if (propFile != null && !propFile.delete()) {
369                     logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
370                 }
371                 deleteTempDir(ownTmpDir);
372             }
373         }
374     }
375 
376     @Override
377     protected String getExecuteType() {
378         return "crawler";
379     }
380 
381 }