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 static org.codelibs.core.stream.StreamUtil.split;
19  
20  import java.util.ArrayList;
21  import java.util.Collections;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.concurrent.atomic.AtomicBoolean;
25  import java.util.regex.Pattern;
26  
27  import org.codelibs.core.lang.StringUtil;
28  import org.codelibs.fess.Constants;
29  import org.codelibs.fess.crawler.Crawler;
30  import org.codelibs.fess.crawler.CrawlerContext;
31  import org.codelibs.fess.crawler.CrawlerStatus;
32  import org.codelibs.fess.crawler.interval.FessIntervalController;
33  import org.codelibs.fess.crawler.service.impl.EsDataService;
34  import org.codelibs.fess.crawler.service.impl.EsUrlFilterService;
35  import org.codelibs.fess.crawler.service.impl.EsUrlQueueService;
36  import org.codelibs.fess.es.config.exbhv.BoostDocumentRuleBhv;
37  import org.codelibs.fess.es.config.exentity.BoostDocumentRule;
38  import org.codelibs.fess.es.config.exentity.CrawlingConfig.ConfigName;
39  import org.codelibs.fess.es.config.exentity.FileConfig;
40  import org.codelibs.fess.es.config.exentity.WebConfig;
41  import org.codelibs.fess.indexer.IndexUpdater;
42  import org.codelibs.fess.mylasta.direction.FessConfig;
43  import org.codelibs.fess.util.ComponentUtil;
44  import org.slf4j.Logger;
45  import org.slf4j.LoggerFactory;
46  
47  public class WebFsIndexHelper {
48  
49      private static final Logger logger = LoggerFactory.getLogger(WebFsIndexHelper.class);
50  
51      protected long maxAccessCount = Long.MAX_VALUE;
52  
53      protected long crawlingExecutionInterval = Constants.DEFAULT_CRAWLING_EXECUTION_INTERVAL;
54  
55      protected int indexUpdaterPriority = Thread.MAX_PRIORITY;
56  
57      protected int crawlerPriority = Thread.NORM_PRIORITY;
58  
59      protected final List<Crawler> crawlerList = Collections.synchronizedList(new ArrayList<Crawler>());
60  
61      public void crawl(final String sessionId, final List<String> webConfigIdList, final List<String> fileConfigIdList) {
62          final boolean runAll = webConfigIdList == null && fileConfigIdList == null;
63          final List<WebConfig> webConfigList;
64          if (runAll || webConfigIdList != null) {
65              webConfigList = ComponentUtil.getCrawlingConfigHelper().getWebConfigListByIds(webConfigIdList);
66          } else {
67              webConfigList = Collections.emptyList();
68          }
69          final List<FileConfig> fileConfigList;
70          if (runAll || fileConfigIdList != null) {
71              fileConfigList = ComponentUtil.getCrawlingConfigHelper().getFileConfigListByIds(fileConfigIdList);
72          } else {
73              fileConfigList = Collections.emptyList();
74          }
75  
76          if (webConfigList.isEmpty() && fileConfigList.isEmpty()) {
77              // nothing
78              if (logger.isInfoEnabled()) {
79                  logger.info("No crawling target urls.");
80              }
81              return;
82          }
83  
84          doCrawl(sessionId, webConfigList, fileConfigList);
85      }
86  
87      protected void doCrawl(final String sessionId, final List<WebConfig> webConfigList, final List<FileConfig> fileConfigList) {
88          final int multiprocessCrawlingCount = ComponentUtil.getFessConfig().getCrawlingThreadCount();
89  
90          final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
91          final FessConfig fessConfig = ComponentUtil.getFessConfig();
92  
93          final long startTime = System.currentTimeMillis();
94  
95          final List<String> sessionIdList = new ArrayList<>();
96          crawlerList.clear();
97          final List<String> crawlerStatusList = new ArrayList<>();
98          // Web
99          for (final WebConfig webConfig : webConfigList) {
100             final String sid = ComponentUtil.getCrawlingConfigHelper().store(sessionId, webConfig);
101 
102             // create crawler
103             final Crawler crawler = ComponentUtil.getComponent(Crawler.class);
104             crawler.setSessionId(sid);
105             sessionIdList.add(sid);
106 
107             final String urlsStr = webConfig.getUrls();
108             if (StringUtil.isBlank(urlsStr)) {
109                 logger.warn("No target urls. Skipped");
110                 break;
111             }
112 
113             // interval time
114             final int intervalTime =
115                     webConfig.getIntervalTime() != null ? webConfig.getIntervalTime() : Constants.DEFAULT_INTERVAL_TIME_FOR_WEB;
116             ((FessIntervalController) crawler.getIntervalController()).setDelayMillisForWaitingNewUrl(intervalTime);
117 
118             final String includedUrlsStr = webConfig.getIncludedUrls() != null ? webConfig.getIncludedUrls() : StringUtil.EMPTY;
119             final String excludedUrlsStr = webConfig.getExcludedUrls() != null ? webConfig.getExcludedUrls() : StringUtil.EMPTY;
120 
121             // num of threads
122             final CrawlerContext crawlerContext = crawler.getCrawlerContext();
123             final int numOfThread =
124                     webConfig.getNumOfThread() != null ? webConfig.getNumOfThread() : Constants.DEFAULT_NUM_OF_THREAD_FOR_WEB;
125             crawlerContext.setNumOfThread(numOfThread);
126 
127             // depth
128             final int depth = webConfig.getDepth() != null ? webConfig.getDepth() : -1;
129             crawlerContext.setMaxDepth(depth);
130 
131             // max count
132             final long maxCount = webConfig.getMaxAccessCount() != null ? webConfig.getMaxAccessCount() : maxAccessCount;
133             crawlerContext.setMaxAccessCount(maxCount);
134 
135             webConfig.initializeClientFactory(crawler.getClientFactory());
136             final Map<String, String> configParamMap = webConfig.getConfigParameterMap(ConfigName.CONFIG);
137 
138             if (Constants.TRUE.equalsIgnoreCase(configParamMap.get(Constants.CONFIG_CLEANUP_ALL))) {
139                 deleteCrawlData(sid);
140             } else if (Constants.TRUE.equalsIgnoreCase(configParamMap.get(Constants.CONFIG_CLEANUP_FILTERS))) {
141                 final EsUrlFilterService urlFilterService = ComponentUtil.getComponent(EsUrlFilterService.class);
142                 try {
143                     urlFilterService.delete(sid);
144                 } catch (final Exception e) {
145                     logger.warn("Failed to delete url filters for " + sid);
146                 }
147             }
148 
149             final DuplicateHostHelper duplicateHostHelper = ComponentUtil.getDuplicateHostHelper();
150 
151             // set urls
152             split(urlsStr, "[\r\n]").of(stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(urlValue -> {
153                 if (!urlValue.startsWith("#") && fessConfig.isValidCrawlerWebProtocol(urlValue)) {
154                     final String u = duplicateHostHelper.convert(urlValue);
155                     crawler.addUrl(u);
156                     if (logger.isInfoEnabled()) {
157                         logger.info("Target URL: " + u);
158                     }
159                 }
160             }));
161 
162             // set included urls
163             split(includedUrlsStr, "[\r\n]").of(
164                     stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(urlValue -> {
165                         if (!urlValue.startsWith("#")) {
166                             crawler.addIncludeFilter(urlValue);
167                             if (logger.isInfoEnabled()) {
168                                 logger.info("Included URL: " + urlValue);
169                             }
170                         }
171                     }));
172 
173             // set excluded urls
174             split(excludedUrlsStr, "[\r\n]").of(
175                     stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(urlValue -> {
176                         if (!urlValue.startsWith("#")) {
177                             crawler.addExcludeFilter(urlValue);
178                             if (logger.isInfoEnabled()) {
179                                 logger.info("Excluded URL: " + urlValue);
180                             }
181                         }
182                     }));
183 
184             // failure url
185             final List<String> excludedUrlList = ComponentUtil.getCrawlingConfigHelper().getExcludedUrlList(webConfig.getConfigId());
186             if (excludedUrlList != null) {
187                 excludedUrlList.stream().filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(u -> {
188                     final String urlValue = Pattern.quote(u);
189                     crawler.addExcludeFilter(urlValue);
190                     if (logger.isInfoEnabled()) {
191                         logger.info("Excluded URL from failures: " + urlValue);
192                     }
193                 });
194             }
195 
196             if (logger.isDebugEnabled()) {
197                 logger.debug("Crawling " + urlsStr);
198             }
199 
200             crawler.setBackground(true);
201             crawler.setThreadPriority(crawlerPriority);
202 
203             crawlerList.add(crawler);
204             crawlerStatusList.add(Constants.READY);
205         }
206 
207         // File
208         for (final FileConfig fileConfig : fileConfigList) {
209             final String sid = ComponentUtil.getCrawlingConfigHelper().store(sessionId, fileConfig);
210 
211             // create crawler
212             final Crawler crawler = ComponentUtil.getComponent(Crawler.class);
213             crawler.setSessionId(sid);
214             sessionIdList.add(sid);
215 
216             final String pathsStr = fileConfig.getPaths();
217             if (StringUtil.isBlank(pathsStr)) {
218                 logger.warn("No target uris. Skipped");
219                 break;
220             }
221 
222             final int intervalTime =
223                     fileConfig.getIntervalTime() != null ? fileConfig.getIntervalTime() : Constants.DEFAULT_INTERVAL_TIME_FOR_FS;
224             ((FessIntervalController) crawler.getIntervalController()).setDelayMillisForWaitingNewUrl(intervalTime);
225 
226             final String includedPathsStr = fileConfig.getIncludedPaths() != null ? fileConfig.getIncludedPaths() : StringUtil.EMPTY;
227             final String excludedPathsStr = fileConfig.getExcludedPaths() != null ? fileConfig.getExcludedPaths() : StringUtil.EMPTY;
228 
229             // num of threads
230             final CrawlerContext crawlerContext = crawler.getCrawlerContext();
231             final int numOfThread =
232                     fileConfig.getNumOfThread() != null ? fileConfig.getNumOfThread() : Constants.DEFAULT_NUM_OF_THREAD_FOR_FS;
233             crawlerContext.setNumOfThread(numOfThread);
234 
235             // depth
236             final int depth = fileConfig.getDepth() != null ? fileConfig.getDepth() : -1;
237             crawlerContext.setMaxDepth(depth);
238 
239             // max count
240             final long maxCount = fileConfig.getMaxAccessCount() != null ? fileConfig.getMaxAccessCount() : maxAccessCount;
241             crawlerContext.setMaxAccessCount(maxCount);
242 
243             fileConfig.initializeClientFactory(crawler.getClientFactory());
244             final Map<String, String> configParamMap = fileConfig.getConfigParameterMap(ConfigName.CONFIG);
245 
246             if (Constants.TRUE.equalsIgnoreCase(configParamMap.get(Constants.CONFIG_CLEANUP_ALL))) {
247                 deleteCrawlData(sid);
248             } else if (Constants.TRUE.equalsIgnoreCase(configParamMap.get(Constants.CONFIG_CLEANUP_FILTERS))) {
249                 final EsUrlFilterService urlFilterService = ComponentUtil.getComponent(EsUrlFilterService.class);
250                 try {
251                     urlFilterService.delete(sid);
252                 } catch (final Exception e) {
253                     logger.warn("Failed to delete url filters for " + sid);
254                 }
255             }
256 
257             // set paths
258             split(pathsStr, "[\r\n]").of(stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(urlValue -> {
259                 if (!urlValue.startsWith("#")) {
260                     final String u;
261                     if (!fessConfig.isValidCrawlerFileProtocol(urlValue)) {
262                         if (urlValue.startsWith("/")) {
263                             u = "file:" + urlValue;
264                         } else {
265                             u = "file:/" + urlValue;
266                         }
267                     } else {
268                         u = urlValue;
269                     }
270                     crawler.addUrl(u);
271                     if (logger.isInfoEnabled()) {
272                         logger.info("Target Path: " + u);
273                     }
274                 }
275             }));
276 
277             // set included paths
278             final AtomicBoolean urlEncodeDisabled = new AtomicBoolean(false);
279             split(includedPathsStr, "[\r\n]").of(
280                     stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(line -> {
281                         if (!line.startsWith("#")) {
282                             final String urlValue;
283                             if (urlEncodeDisabled.get()) {
284                                 urlValue = line;
285                                 urlEncodeDisabled.set(false);
286                             } else {
287                                 urlValue = systemHelper.encodeUrlFilter(line);
288                             }
289                             crawler.addIncludeFilter(urlValue);
290                             if (logger.isInfoEnabled()) {
291                                 logger.info("Included Path: " + urlValue);
292                             }
293                         } else if (line.startsWith("#DISABLE_URL_ENCODE")) {
294                             urlEncodeDisabled.set(true);
295                         }
296                     }));
297 
298             // set excluded paths
299             urlEncodeDisabled.set(false);
300             split(excludedPathsStr, "[\r\n]").of(
301                     stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(line -> {
302                         if (!line.startsWith("#")) {
303                             final String urlValue;
304                             if (urlEncodeDisabled.get()) {
305                                 urlValue = line;
306                                 urlEncodeDisabled.set(false);
307                             } else {
308                                 urlValue = systemHelper.encodeUrlFilter(line);
309                             }
310                             crawler.addExcludeFilter(urlValue);
311                             if (logger.isInfoEnabled()) {
312                                 logger.info("Excluded Path: " + urlValue);
313                             }
314                         } else if (line.startsWith("#DISABLE_URL_ENCODE")) {
315                             urlEncodeDisabled.set(true);
316                         }
317                     }));
318 
319             // failure url
320             final List<String> excludedUrlList = ComponentUtil.getCrawlingConfigHelper().getExcludedUrlList(fileConfig.getConfigId());
321             if (excludedUrlList != null) {
322                 excludedUrlList.stream().filter(StringUtil::isNotBlank).map(String::trim).distinct().forEach(u -> {
323                     final String urlValue = Pattern.quote(u);
324                     crawler.addExcludeFilter(urlValue);
325                     if (logger.isInfoEnabled()) {
326                         logger.info("Excluded Path from failures: " + urlValue);
327                     }
328                 });
329             }
330 
331             if (logger.isDebugEnabled()) {
332                 logger.debug("Crawling " + pathsStr);
333             }
334 
335             crawler.setBackground(true);
336             crawler.setThreadPriority(crawlerPriority);
337 
338             crawlerList.add(crawler);
339             crawlerStatusList.add(Constants.READY);
340         }
341 
342         // run index update
343         final IndexUpdater indexUpdater = ComponentUtil.getIndexUpdater();
344         indexUpdater.setName("IndexUpdater");
345         indexUpdater.setPriority(indexUpdaterPriority);
346         indexUpdater.setSessionIdList(sessionIdList);
347         indexUpdater.setDaemon(true);
348         indexUpdater.setCrawlerList(crawlerList);
349         getAvailableBoostDocumentRuleList().forEach(rule -> {
350             indexUpdater.addDocBoostMatcher(new org.codelibs.fess.indexer.DocBoostMatcher(rule));
351         });
352         indexUpdater.start();
353 
354         int startedCrawlerNum = 0;
355         int activeCrawlerNum = 0;
356         while (startedCrawlerNum < crawlerList.size()) {
357             // Force to stop crawl
358             if (systemHelper.isForceStop()) {
359                 for (final Crawler crawler : crawlerList) {
360                     crawler.stop();
361                 }
362                 break;
363             }
364 
365             if (activeCrawlerNum < multiprocessCrawlingCount) {
366                 // start crawling
367                 crawlerList.get(startedCrawlerNum).execute();
368                 crawlerStatusList.set(startedCrawlerNum, Constants.RUNNING);
369                 startedCrawlerNum++;
370                 activeCrawlerNum++;
371                 try {
372                     Thread.sleep(crawlingExecutionInterval);
373                 } catch (final InterruptedException e) {
374                     if (logger.isDebugEnabled()) {
375                         logger.debug("Interrupted.", e);
376                     }
377                 }
378                 continue;
379             }
380 
381             // check status
382             for (int i = 0; i < startedCrawlerNum; i++) {
383                 if (crawlerList.get(i).getCrawlerContext().getStatus() == CrawlerStatus.DONE
384                         && crawlerStatusList.get(i).equals(Constants.RUNNING)) {
385                     crawlerList.get(i).awaitTermination();
386                     crawlerStatusList.set(i, Constants.DONE);
387                     final String sid = crawlerList.get(i).getCrawlerContext().getSessionId();
388                     indexUpdater.addFinishedSessionId(sid);
389                     activeCrawlerNum--;
390                 }
391             }
392             try {
393                 Thread.sleep(crawlingExecutionInterval);
394             } catch (final InterruptedException e) {
395                 if (logger.isDebugEnabled()) {
396                     logger.debug("Interrupted.", e);
397                 }
398             }
399         }
400 
401         boolean finishedAll = false;
402         while (!finishedAll) {
403             finishedAll = true;
404             for (int i = 0; i < crawlerList.size(); i++) {
405                 crawlerList.get(i).awaitTermination(crawlingExecutionInterval);
406                 if (crawlerList.get(i).getCrawlerContext().getStatus() == CrawlerStatus.DONE
407                         && !crawlerStatusList.get(i).equals(Constants.DONE)) {
408                     crawlerStatusList.set(i, Constants.DONE);
409                     final String sid = crawlerList.get(i).getCrawlerContext().getSessionId();
410                     indexUpdater.addFinishedSessionId(sid);
411                 }
412                 if (!crawlerStatusList.get(i).equals(Constants.DONE)) {
413                     finishedAll = false;
414                 }
415             }
416         }
417         crawlerList.clear();
418         crawlerStatusList.clear();
419 
420         // put cralwing info
421         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
422 
423         final long execTime = System.currentTimeMillis() - startTime;
424         crawlingInfoHelper.putToInfoMap(Constants.WEB_FS_CRAWLING_EXEC_TIME, Long.toString(execTime));
425         if (logger.isInfoEnabled()) {
426             logger.info("[EXEC TIME] crawling time: " + execTime + "ms");
427         }
428 
429         indexUpdater.setFinishCrawling(true);
430         try {
431             indexUpdater.join();
432         } catch (final InterruptedException e) {
433             logger.warn("Interrupted index update.", e);
434         }
435 
436         crawlingInfoHelper.putToInfoMap(Constants.WEB_FS_INDEX_EXEC_TIME, Long.toString(indexUpdater.getExecuteTime()));
437         crawlingInfoHelper.putToInfoMap(Constants.WEB_FS_INDEX_SIZE, Long.toString(indexUpdater.getDocumentSize()));
438 
439         if (systemHelper.isForceStop()) {
440             return;
441         }
442 
443         for (final String sid : sessionIdList) {
444             // remove config
445             ComponentUtil.getCrawlingConfigHelper().remove(sid);
446             deleteCrawlData(sid);
447         }
448     }
449 
450     protected List<BoostDocumentRule> getAvailableBoostDocumentRuleList() {
451         return ComponentUtil.getComponent(BoostDocumentRuleBhv.class).selectList(cb -> {
452             cb.query().matchAll();
453             cb.query().addOrderBy_SortOrder_Asc();
454             cb.fetchFirst(ComponentUtil.getFessConfig().getPageDocboostMaxFetchSizeAsInteger());
455         });
456     }
457 
458     protected void deleteCrawlData(final String sid) {
459         final EsUrlFilterService urlFilterService = ComponentUtil.getComponent(EsUrlFilterService.class);
460         final EsUrlQueueService urlQueueService = ComponentUtil.getComponent(EsUrlQueueService.class);
461         final EsDataService dataService = ComponentUtil.getComponent(EsDataService.class);
462 
463         try {
464             // clear url filter
465             urlFilterService.delete(sid);
466         } catch (final Exception e) {
467             logger.warn("Failed to delete UrlFilter for " + sid, e);
468         }
469 
470         try {
471             // clear queue
472             urlQueueService.clearCache();
473             urlQueueService.delete(sid);
474         } catch (final Exception e) {
475             logger.warn("Failed to delete UrlQueue for " + sid, e);
476         }
477 
478         try {
479             // clear
480             dataService.delete(sid);
481         } catch (final Exception e) {
482             logger.warn("Failed to delete AccessResult for " + sid, e);
483         }
484     }
485 
486     public void setMaxAccessCount(final long maxAccessCount) {
487         this.maxAccessCount = maxAccessCount;
488     }
489 
490     public void setCrawlingExecutionInterval(final long crawlingExecutionInterval) {
491         this.crawlingExecutionInterval = crawlingExecutionInterval;
492     }
493 
494     public void setIndexUpdaterPriority(final int indexUpdaterPriority) {
495         this.indexUpdaterPriority = indexUpdaterPriority;
496     }
497 
498     public void setCrawlerPriority(final int crawlerPriority) {
499         this.crawlerPriority = crawlerPriority;
500     }
501 
502 }