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.exec;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.BufferedReader;
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.InputStreamReader;
24  import java.lang.management.ManagementFactory;
25  import java.text.SimpleDateFormat;
26  import java.util.ArrayList;
27  import java.util.Date;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.Queue;
32  import java.util.concurrent.ConcurrentLinkedQueue;
33  import java.util.concurrent.atomic.AtomicBoolean;
34  import java.util.stream.Collectors;
35  
36  import javax.annotation.Resource;
37  
38  import org.codelibs.core.CoreLibConstants;
39  import org.codelibs.core.lang.StringUtil;
40  import org.codelibs.core.misc.DynamicProperties;
41  import org.codelibs.core.timer.TimeoutManager;
42  import org.codelibs.core.timer.TimeoutTask;
43  import org.codelibs.fess.Constants;
44  import org.codelibs.fess.app.service.CrawlingInfoService;
45  import org.codelibs.fess.app.service.PathMappingService;
46  import org.codelibs.fess.crawler.client.EsClient;
47  import org.codelibs.fess.es.client.FessEsClient;
48  import org.codelibs.fess.exception.ContainerNotAvailableException;
49  import org.codelibs.fess.helper.CrawlingInfoHelper;
50  import org.codelibs.fess.helper.DataIndexHelper;
51  import org.codelibs.fess.helper.DuplicateHostHelper;
52  import org.codelibs.fess.helper.PathMappingHelper;
53  import org.codelibs.fess.helper.WebFsIndexHelper;
54  import org.codelibs.fess.mylasta.direction.FessConfig;
55  import org.codelibs.fess.mylasta.mail.CrawlerPostcard;
56  import org.codelibs.fess.timer.SystemMonitorTarget;
57  import org.codelibs.fess.util.ComponentUtil;
58  import org.codelibs.fess.util.ThreadDumpUtil;
59  import org.elasticsearch.monitor.jvm.JvmInfo;
60  import org.elasticsearch.monitor.os.OsProbe;
61  import org.elasticsearch.monitor.process.ProcessProbe;
62  import org.kohsuke.args4j.CmdLineException;
63  import org.kohsuke.args4j.CmdLineParser;
64  import org.kohsuke.args4j.Option;
65  import org.lastaflute.core.mail.Postbox;
66  import org.lastaflute.di.core.external.GenericExternalContext;
67  import org.lastaflute.di.core.external.GenericExternalContextComponentDefRegister;
68  import org.lastaflute.di.core.factory.SingletonLaContainerFactory;
69  import org.slf4j.Logger;
70  import org.slf4j.LoggerFactory;
71  
72  public class Crawler {
73  
74      private static final Logger logger = LoggerFactory.getLogger(Crawler.class);
75  
76      private static final String WEB_FS_CRAWLING_PROCESS = "WebFsCrawler";
77  
78      private static final String DATA_CRAWLING_PROCESS = "DataStoreCrawler";
79  
80      private static AtomicBoolean running = new AtomicBoolean(false);
81  
82      private static Queue<String> errors = new ConcurrentLinkedQueue<>();
83  
84      @Resource
85      protected FessEsClient fessEsClient;
86  
87      @Resource
88      protected WebFsIndexHelper webFsIndexHelper;
89  
90      @Resource
91      protected DataIndexHelper dataIndexHelper;
92  
93      @Resource
94      protected PathMappingService pathMappingService;
95  
96      @Resource
97      protected CrawlingInfoService crawlingInfoService;
98  
99      public static void addError(final String msg) {
100         if (StringUtil.isNotBlank(msg)) {
101             errors.offer(msg);
102         }
103     }
104 
105     public static class Options {
106 
107         @Option(name = "-s", aliases = "--sessionId", metaVar = "sessionId", usage = "Session ID")
108         public String sessionId;
109 
110         @Option(name = "-n", aliases = "--name", metaVar = "name", usage = "Name")
111         public String name;
112 
113         @Option(name = "-w", aliases = "--webConfigIds", metaVar = "webConfigIds", usage = "Web Config IDs")
114         public String webConfigIds;
115 
116         @Option(name = "-f", aliases = "--fileConfigIds", metaVar = "fileConfigIds", usage = "File Config IDs")
117         public String fileConfigIds;
118 
119         @Option(name = "-d", aliases = "--dataConfigIds", metaVar = "dataConfigIds", usage = "Data Config IDs")
120         public String dataConfigIds;
121 
122         @Option(name = "-p", aliases = "--properties", metaVar = "properties", usage = "Properties File")
123         public String propertiesPath;
124 
125         @Option(name = "-e", aliases = "--expires", metaVar = "expires", usage = "Expires for documents")
126         public String expires;
127 
128         protected Options() {
129             // nothing
130         }
131 
132         protected List<String> getWebConfigIdList() {
133             if (StringUtil.isNotBlank(webConfigIds)) {
134                 final String[] values = webConfigIds.split(",");
135                 return createConfigIdList(values);
136             }
137             return null;
138         }
139 
140         protected List<String> getFileConfigIdList() {
141             if (StringUtil.isNotBlank(fileConfigIds)) {
142                 final String[] values = fileConfigIds.split(",");
143                 return createConfigIdList(values);
144             }
145             return null;
146         }
147 
148         protected List<String> getDataConfigIdList() {
149             if (StringUtil.isNotBlank(dataConfigIds)) {
150                 final String[] values = dataConfigIds.split(",");
151                 return createConfigIdList(values);
152             }
153             return null;
154         }
155 
156         private static List<String> createConfigIdList(final String[] values) {
157             final List<String> idList = new ArrayList<>();
158             for (final String value : values) {
159                 idList.add(value);
160             }
161             return idList;
162         }
163 
164         @Override
165         public String toString() {
166             return "Options [sessionId=" + sessionId + ", name=" + name + ", webConfigIds=" + webConfigIds + ", fileConfigIds="
167                     + fileConfigIds + ", dataConfigIds=" + dataConfigIds + ", propertiesPath=" + propertiesPath + ", expires=" + expires
168                     + "]";
169         }
170 
171     }
172 
173     static void initializeProbes() {
174         // Force probes to be loaded
175         ProcessProbe.getInstance();
176         OsProbe.getInstance();
177         JvmInfo.jvmInfo();
178     }
179 
180     public static void main(final String[] args) {
181         final Options options = new Options();
182 
183         final CmdLineParser parser = new CmdLineParser(options);
184         try {
185             parser.parseArgument(args);
186         } catch (final CmdLineException e) {
187             System.err.println(e.getMessage());
188             System.err.println("java " + Crawler.class.getCanonicalName() + " [options...] arguments...");
189             parser.printUsage(System.err);
190             return;
191         }
192 
193         if (logger.isDebugEnabled()) {
194             try {
195                 ManagementFactory.getRuntimeMXBean().getInputArguments().stream().forEach(s -> logger.debug("Parameter: " + s));
196                 System.getProperties().entrySet().stream().forEach(e -> logger.debug("Property: " + e.getKey() + "=" + e.getValue()));
197                 System.getenv().entrySet().forEach(e -> logger.debug("Env: " + e.getKey() + "=" + e.getValue()));
198                 logger.debug("Option: " + options);
199             } catch (final Exception e) {
200                 // ignore
201             }
202         }
203 
204         initializeProbes();
205 
206         final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
207         if (StringUtil.isNotBlank(httpAddress)) {
208             System.setProperty(EsClient.HTTP_ADDRESS, httpAddress);
209         }
210 
211         TimeoutTask systemMonitorTask = null;
212         Thread commandThread = null;
213         int exitCode;
214         try {
215             running.set(true);
216             SingletonLaContainerFactory.setConfigPath("app.xml");
217             SingletonLaContainerFactory.setExternalContext(new GenericExternalContext());
218             SingletonLaContainerFactory.setExternalContextComponentDefRegister(new GenericExternalContextComponentDefRegister());
219             SingletonLaContainerFactory.init();
220 
221             final Thread shutdownCallback = new Thread("ShutdownHook") {
222                 @Override
223                 public void run() {
224                     destroyContainer();
225                 }
226 
227             };
228             Runtime.getRuntime().addShutdownHook(shutdownCallback);
229 
230             commandThread = new Thread(() -> {
231                 try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
232                     String command;
233                     while (true) {
234                         try {
235                             while (!reader.ready()) {
236                                 Thread.sleep(1000L);
237                             }
238                             command = reader.readLine().trim();
239                             if (logger.isDebugEnabled()) {
240                                 logger.debug("Process command: " + command);
241                             }
242                             if (Constants.CRAWLER_PROCESS_COMMAND_THREAD_DUMP.equals(command)) {
243                                 ThreadDumpUtil.printThreadDump();
244                             } else {
245                                 logger.warn("Unknown process command: " + command);
246                             }
247                             if (Thread.interrupted()) {
248                                 return;
249                             }
250                         } catch (final InterruptedException e) {
251                             return;
252                         }
253                     }
254                 } catch (final IOException e) {
255                     logger.debug("I/O exception.", e);
256                 }
257             }, "ProcessCommand");
258             commandThread.start();
259 
260             systemMonitorTask =
261                     TimeoutManager.getInstance().addTimeoutTarget(new SystemMonitorTarget(),
262                             ComponentUtil.getFessConfig().getCrawlerSystemMonitorIntervalAsInteger(), true);
263 
264             exitCode = process(options);
265         } catch (final ContainerNotAvailableException e) {
266             if (logger.isDebugEnabled()) {
267                 logger.debug("Crawler is stopped.", e);
268             } else if (logger.isInfoEnabled()) {
269                 logger.info("Crawler is stopped.");
270             }
271             exitCode = Constants.EXIT_FAIL;
272         } catch (final Throwable t) {
273             logger.error("Crawler does not work correctly.", t);
274             exitCode = Constants.EXIT_FAIL;
275         } finally {
276             if (commandThread != null && commandThread.isAlive()) {
277                 commandThread.interrupt();
278             }
279             if (systemMonitorTask != null) {
280                 systemMonitorTask.cancel();
281             }
282             destroyContainer();
283         }
284 
285         if (exitCode != Constants.EXIT_OK) {
286             System.exit(exitCode);
287         }
288     }
289 
290     private static void destroyContainer() {
291         if (running.getAndSet(false)) {
292             if (logger.isDebugEnabled()) {
293                 logger.debug("Destroying LaContainer...");
294             }
295             SingletonLaContainerFactory.destroy();
296             logger.info("Destroyed LaContainer.");
297         }
298     }
299 
300     private static int process(final Options options) {
301         final Crawler crawler = ComponentUtil.getComponent(Crawler.class);
302 
303         if (StringUtil.isBlank(options.sessionId)) {
304             // use a default session id
305             final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
306             options.sessionId = sdf.format(new Date());
307         }
308 
309         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
310         final DynamicProperties systemProperties = ComponentUtil.getSystemProperties();
311 
312         if (StringUtil.isNotBlank(options.propertiesPath)) {
313             systemProperties.reload(options.propertiesPath);
314         } else {
315             try {
316                 final File propFile = File.createTempFile("crawler_", ".properties");
317                 if (propFile.delete() && logger.isDebugEnabled()) {
318                     logger.debug("Deleted a temp file: " + propFile.getAbsolutePath());
319                 }
320                 systemProperties.reload(propFile.getAbsolutePath());
321                 propFile.deleteOnExit();
322             } catch (final IOException e) {
323                 logger.warn("Failed to create system properties file.", e);
324             }
325         }
326 
327         try {
328             crawlingInfoHelper.store(options.sessionId, true);
329             final String dayForCleanupStr;
330             int dayForCleanup = -1;
331             if (StringUtil.isNotBlank(options.expires)) {
332                 dayForCleanupStr = options.expires;
333                 try {
334                     dayForCleanup = Integer.parseInt(dayForCleanupStr);
335                 } catch (final NumberFormatException e) {}
336             } else {
337                 dayForCleanup = ComponentUtil.getFessConfig().getDayForCleanup();
338             }
339             crawlingInfoHelper.updateParams(options.sessionId, options.name, dayForCleanup);
340         } catch (final Exception e) {
341             logger.warn("Failed to store crawling information.", e);
342         }
343 
344         try {
345             return crawler.doCrawl(options);
346         } finally {
347             try {
348                 crawlingInfoHelper.store(options.sessionId, false);
349             } catch (final Exception e) {
350                 logger.warn("Failed to store crawling information.", e);
351             }
352 
353             final Map<String, String> infoMap = crawlingInfoHelper.getInfoMap(options.sessionId);
354 
355             final StringBuilder buf = new StringBuilder(500);
356             for (final Map.Entry<String, String> entry : infoMap.entrySet()) {
357                 if (buf.length() != 0) {
358                     buf.append(',');
359                 }
360                 buf.append(entry.getKey()).append('=').append(entry.getValue());
361             }
362             logger.info("[CRAWL INFO] " + buf.toString());
363 
364             // notification
365             try {
366                 crawler.sendMail(infoMap);
367             } catch (final Exception e) {
368                 logger.warn("Failed to send a mail.", e);
369             }
370 
371         }
372     }
373 
374     protected void sendMail(final Map<String, String> infoMap) {
375         final FessConfig fessConfig = ComponentUtil.getFessConfig();
376         final String toStrs = fessConfig.getNotificationTo();
377         if (StringUtil.isNotBlank(toStrs)) {
378             final String[] toAddresses = toStrs.split(",");
379             final Map<String, String> dataMap = new HashMap<>();
380             for (final Map.Entry<String, String> entry : infoMap.entrySet()) {
381                 dataMap.put(StringUtil.decapitalize(entry.getKey()), entry.getValue());
382             }
383 
384             String hostname = fessConfig.getMailHostname();
385             if (StringUtil.isBlank(hostname)) {
386                 hostname = ComponentUtil.getSystemHelper().getHostname();
387             }
388             dataMap.put("hostname", hostname);
389 
390             logger.debug("\ninfoMap: {}\ndataMap: {}", infoMap, dataMap);
391 
392             final Postbox postbox = ComponentUtil.getComponent(Postbox.class);
393             CrawlerPostcard.droppedInto(postbox, postcard -> {
394                 postcard.setFrom(fessConfig.getMailFromAddress(), fessConfig.getMailFromName());
395                 postcard.addReplyTo(fessConfig.getMailReturnPath());
396                 stream(toAddresses).of(stream -> stream.forEach(address -> {
397                     postcard.addTo(address);
398                 }));
399                 postcard.setCrawlerEndTime(getValueFromMap(dataMap, "crawlerEndTime", StringUtil.EMPTY));
400                 postcard.setCrawlerExecTime(getValueFromMap(dataMap, "crawlerExecTime", "0"));
401                 postcard.setCrawlerStartTime(getValueFromMap(dataMap, "crawlerStartTime", StringUtil.EMPTY));
402                 postcard.setDataCrawlEndTime(getValueFromMap(dataMap, "dataCrawlEndTime", StringUtil.EMPTY));
403                 postcard.setDataCrawlExecTime(getValueFromMap(dataMap, "dataCrawlExecTime", "0"));
404                 postcard.setDataCrawlStartTime(getValueFromMap(dataMap, "dataCrawlStartTime", StringUtil.EMPTY));
405                 postcard.setDataIndexSize(getValueFromMap(dataMap, "dataIndexSize", "0"));
406                 postcard.setDataIndexExecTime(getValueFromMap(dataMap, "dataIndexExecTime", "0"));
407                 postcard.setHostname(getValueFromMap(dataMap, "hostname", StringUtil.EMPTY));
408                 postcard.setWebFsCrawlEndTime(getValueFromMap(dataMap, "webFsCrawlEndTime", StringUtil.EMPTY));
409                 postcard.setWebFsCrawlExecTime(getValueFromMap(dataMap, "webFsCrawlExecTime", "0"));
410                 postcard.setWebFsCrawlStartTime(getValueFromMap(dataMap, "webFsCrawlStartTime", StringUtil.EMPTY));
411                 postcard.setWebFsIndexExecTime(getValueFromMap(dataMap, "webFsIndexExecTime", "0"));
412                 postcard.setWebFsIndexSize(getValueFromMap(dataMap, "webFsIndexSize", "0"));
413                 if (Constants.TRUE.equalsIgnoreCase(infoMap.get(Constants.CRAWLER_STATUS))) {
414                     postcard.setStatus(Constants.OK);
415                 } else {
416                     postcard.setStatus(Constants.FAIL);
417                 }
418             });
419         }
420     }
421 
422     private String getValueFromMap(final Map<String, String> dataMap, final String key, final String defaultValue) {
423         final String value = dataMap.get(key);
424         if (StringUtil.isBlank(value)) {
425             return defaultValue;
426         }
427         return value;
428     }
429 
430     public int doCrawl(final Options options) {
431         if (logger.isInfoEnabled()) {
432             logger.info("Starting Crawler..");
433         }
434 
435         final PathMappingHelper pathMappingHelper = ComponentUtil.getPathMappingHelper();
436 
437         final long totalTime = System.currentTimeMillis();
438 
439         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
440 
441         try {
442             writeTimeToSessionInfo(crawlingInfoHelper, Constants.CRAWLER_START_TIME);
443 
444             // setup path mapping
445             final List<String> ptList = new ArrayList<>();
446             ptList.add(Constants.PROCESS_TYPE_CRAWLING);
447             ptList.add(Constants.PROCESS_TYPE_BOTH);
448             pathMappingHelper.setPathMappingList(options.sessionId, pathMappingService.getPathMappingList(ptList));
449 
450             // duplicate host
451             try {
452                 final DuplicateHostHelper duplicateHostHelper = ComponentUtil.getDuplicateHostHelper();
453                 duplicateHostHelper.init();
454             } catch (final Exception e) {
455                 logger.warn("Could not initialize duplicateHostHelper.", e);
456             }
457 
458             // delete expired sessions
459             crawlingInfoService.deleteSessionIdsBefore(options.sessionId, options.name, ComponentUtil.getSystemHelper()
460                     .getCurrentTimeAsLong());
461 
462             final List<String> webConfigIdList = options.getWebConfigIdList();
463             final List<String> fileConfigIdList = options.getFileConfigIdList();
464             final List<String> dataConfigIdList = options.getDataConfigIdList();
465             final boolean runAll = webConfigIdList == null && fileConfigIdList == null && dataConfigIdList == null;
466 
467             Thread webFsCrawlerThread = null;
468             Thread dataCrawlerThread = null;
469 
470             if (runAll || webConfigIdList != null || fileConfigIdList != null) {
471                 webFsCrawlerThread = new Thread((Runnable) () -> {
472                     // crawl web
473                         writeTimeToSessionInfo(crawlingInfoHelper, Constants.WEB_FS_CRAWLER_START_TIME);
474                         webFsIndexHelper.crawl(options.sessionId, webConfigIdList, fileConfigIdList);
475                         writeTimeToSessionInfo(crawlingInfoHelper, Constants.WEB_FS_CRAWLER_END_TIME);
476                     }, WEB_FS_CRAWLING_PROCESS);
477                 webFsCrawlerThread.start();
478             }
479 
480             if (runAll || dataConfigIdList != null) {
481                 dataCrawlerThread = new Thread((Runnable) () -> {
482                     // crawl data system
483                         writeTimeToSessionInfo(crawlingInfoHelper, Constants.DATA_CRAWLER_START_TIME);
484                         dataIndexHelper.crawl(options.sessionId, dataConfigIdList);
485                         writeTimeToSessionInfo(crawlingInfoHelper, Constants.DATA_CRAWLER_END_TIME);
486                     }, DATA_CRAWLING_PROCESS);
487                 dataCrawlerThread.start();
488             }
489 
490             joinCrawlerThread(webFsCrawlerThread);
491             joinCrawlerThread(dataCrawlerThread);
492 
493             if (logger.isInfoEnabled()) {
494                 logger.info("Finished Crawler");
495             }
496 
497             return Constants.EXIT_OK;
498         } catch (final Throwable t) {
499             logger.warn("An exception occurs on the crawl task.", t);
500             return Constants.EXIT_FAIL;
501         } finally {
502             pathMappingHelper.removePathMappingList(options.sessionId);
503             crawlingInfoHelper.putToInfoMap(Constants.CRAWLER_STATUS, errors.isEmpty() ? Constants.T.toString() : Constants.F.toString());
504             if (!errors.isEmpty()) {
505                 crawlingInfoHelper.putToInfoMap(Constants.CRAWLER_ERRORS, errors.stream().map(s -> s.replace(" ", StringUtil.EMPTY))
506                         .collect(Collectors.joining(" ")));
507             }
508             writeTimeToSessionInfo(crawlingInfoHelper, Constants.CRAWLER_END_TIME);
509             crawlingInfoHelper.putToInfoMap(Constants.CRAWLER_EXEC_TIME, Long.toString(System.currentTimeMillis() - totalTime));
510 
511         }
512     }
513 
514     protected void writeTimeToSessionInfo(final CrawlingInfoHelper crawlingInfoHelper, final String key) {
515         if (crawlingInfoHelper != null) {
516             final SimpleDateFormat dateFormat = new SimpleDateFormat(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
517             crawlingInfoHelper.putToInfoMap(key, dateFormat.format(new Date()));
518         }
519     }
520 
521     private void joinCrawlerThread(final Thread crawlerThread) {
522         if (crawlerThread != null) {
523             try {
524                 crawlerThread.join();
525             } catch (final Exception e) {
526                 logger.info("Interrupted a crawling process: " + crawlerThread.getName());
527             }
528         }
529     }
530 }