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.indexer;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  import java.util.Map;
21  import java.util.function.Consumer;
22  
23  import javax.annotation.PreDestroy;
24  import javax.annotation.Resource;
25  
26  import org.codelibs.core.lang.StringUtil;
27  import org.codelibs.fess.Constants;
28  import org.codelibs.fess.crawler.Crawler;
29  import org.codelibs.fess.crawler.entity.AccessResult;
30  import org.codelibs.fess.crawler.entity.AccessResultData;
31  import org.codelibs.fess.crawler.entity.EsAccessResult;
32  import org.codelibs.fess.crawler.entity.EsUrlQueue;
33  import org.codelibs.fess.crawler.service.DataService;
34  import org.codelibs.fess.crawler.service.UrlFilterService;
35  import org.codelibs.fess.crawler.service.UrlQueueService;
36  import org.codelibs.fess.crawler.service.impl.EsDataService;
37  import org.codelibs.fess.crawler.transformer.Transformer;
38  import org.codelibs.fess.crawler.util.EsResultList;
39  import org.codelibs.fess.es.client.FessEsClient;
40  import org.codelibs.fess.es.log.exbhv.ClickLogBhv;
41  import org.codelibs.fess.es.log.exbhv.FavoriteLogBhv;
42  import org.codelibs.fess.exception.ContainerNotAvailableException;
43  import org.codelibs.fess.exception.FessSystemException;
44  import org.codelibs.fess.helper.IndexingHelper;
45  import org.codelibs.fess.helper.IntervalControlHelper;
46  import org.codelibs.fess.helper.SearchLogHelper;
47  import org.codelibs.fess.helper.SystemHelper;
48  import org.codelibs.fess.mylasta.direction.FessConfig;
49  import org.codelibs.fess.util.ComponentUtil;
50  import org.codelibs.fess.util.DocList;
51  import org.codelibs.fess.util.MemoryUtil;
52  import org.codelibs.fess.util.ThreadDumpUtil;
53  import org.elasticsearch.action.search.SearchRequestBuilder;
54  import org.elasticsearch.index.query.QueryBuilder;
55  import org.elasticsearch.index.query.QueryBuilders;
56  import org.elasticsearch.search.sort.SortOrder;
57  import org.slf4j.Logger;
58  import org.slf4j.LoggerFactory;
59  
60  public class IndexUpdater extends Thread {
61      private static final Logger logger = LoggerFactory.getLogger(IndexUpdater.class);
62  
63      protected List<String> sessionIdList;
64  
65      @Resource
66      protected FessEsClient fessEsClient;
67  
68      @Resource
69      protected DataService<EsAccessResult> dataService;
70  
71      @Resource
72      protected UrlQueueService<EsUrlQueue> urlQueueService;
73  
74      @Resource
75      protected UrlFilterService urlFilterService;
76  
77      @Resource
78      protected ClickLogBhv clickLogBhv;
79  
80      @Resource
81      protected FavoriteLogBhv favoriteLogBhv;
82  
83      @Resource
84      protected SystemHelper systemHelper;
85  
86      @Resource
87      protected IndexingHelper indexingHelper;
88  
89      protected boolean finishCrawling = false;
90  
91      protected long executeTime;
92  
93      protected long documentSize;
94  
95      protected int maxIndexerErrorCount = 0;
96  
97      protected int maxErrorCount = 2;
98  
99      protected List<String> finishedSessionIdList = new ArrayList<>();
100 
101     private final List<DocBoostMatcher> docBoostMatcherList = new ArrayList<>();
102 
103     private List<Crawler> crawlerList;
104 
105     public IndexUpdater() {
106         // nothing
107     }
108 
109     @PreDestroy
110     public void destroy() {
111         if (!finishCrawling) {
112             if (logger.isInfoEnabled()) {
113                 logger.info("Stopping all crawler.");
114             }
115             forceStop();
116         }
117     }
118 
119     public void addFinishedSessionId(final String sessionId) {
120         synchronized (finishedSessionIdList) {
121             finishedSessionIdList.add(sessionId);
122         }
123     }
124 
125     private void deleteBySessionId(final String sessionId) {
126         try {
127             urlFilterService.delete(sessionId);
128         } catch (final Exception e) {
129             logger.warn("Failed to delete url filters: " + sessionId, e);
130         }
131         try {
132             urlQueueService.delete(sessionId);
133         } catch (final Exception e) {
134             logger.warn("Failed to delete url queues: " + sessionId, e);
135         }
136         try {
137             dataService.delete(sessionId);
138         } catch (final Exception e) {
139             logger.warn("Failed to delete data: " + sessionId, e);
140         }
141     }
142 
143     @Override
144     public void run() {
145         if (dataService == null) {
146             throw new FessSystemException("DataService is null.");
147         }
148 
149         if (logger.isDebugEnabled()) {
150             logger.debug("Starting indexUpdater.");
151         }
152 
153         executeTime = 0;
154         documentSize = 0;
155 
156         final FessConfig fessConfig = ComponentUtil.getFessConfig();
157         final long updateInterval = fessConfig.getIndexerWebfsUpdateIntervalAsInteger().longValue();
158         final int maxEmptyListCount = fessConfig.getIndexerWebfsMaxEmptyListCountAsInteger().intValue();
159         final IntervalControlHelper intervalControlHelper = ComponentUtil.getIntervalControlHelper();
160         try {
161             final Consumer<SearchRequestBuilder> cb =
162                     builder -> {
163                         final QueryBuilder queryBuilder =
164                                 QueryBuilders
165                                         .boolQuery()
166                                         .filter(QueryBuilders.termsQuery(EsAccessResult.SESSION_ID, sessionIdList))
167                                         .filter(QueryBuilders.termQuery(EsAccessResult.STATUS,
168                                                 org.codelibs.fess.crawler.Constants.OK_STATUS));
169                         builder.setQuery(queryBuilder);
170                         builder.setFrom(0);
171                         final int maxDocumentCacheSize = fessConfig.getIndexerWebfsMaxDocumentCacheSizeAsInteger().intValue();
172                         builder.setSize(maxDocumentCacheSize <= 0 ? 1 : maxDocumentCacheSize);
173                         builder.addSort(EsAccessResult.CREATE_TIME, SortOrder.ASC);
174                     };
175 
176             final DocList.html#DocList">DocList docList = new DocList();
177             final List<EsAccessResult> accessResultList = new ArrayList<>();
178 
179             long updateTime = System.currentTimeMillis();
180             int errorCount = 0;
181             int emptyListCount = 0;
182             long cleanupTime = -1;
183             while (!finishCrawling || !accessResultList.isEmpty()) {
184                 try {
185                     final int sessionIdListSize = finishedSessionIdList.size();
186                     intervalControlHelper.setCrawlerRunning(true);
187 
188                     updateTime = System.currentTimeMillis() - updateTime;
189 
190                     final long interval = updateInterval - updateTime;
191                     if (interval > 0) {
192                         // sleep
193                         try {
194                             Thread.sleep(interval); // 10 sec (default)
195                         } catch (final InterruptedException e) {
196                             logger.warn("Interrupted index update.", e);
197                         }
198                     }
199 
200                     docList.clear();
201                     accessResultList.clear();
202 
203                     intervalControlHelper.delayByRules();
204 
205                     if (logger.isDebugEnabled()) {
206                         logger.debug("Processing documents in IndexUpdater queue.");
207                     }
208 
209                     updateTime = System.currentTimeMillis();
210 
211                     List<EsAccessResult> arList = getAccessResultList(cb, cleanupTime);
212                     if (arList.isEmpty()) {
213                         emptyListCount++;
214                     } else {
215                         emptyListCount = 0; // reset
216                     }
217                     long hitCount = ((EsResultList<EsAccessResult>) arList).getTotalHits();
218                     while (hitCount > 0) {
219                         if (arList.isEmpty()) {
220                             try {
221                                 Thread.sleep(fessConfig.getIndexerWebfsCommitMarginTimeAsInteger().longValue());
222                             } catch (final Exception e) {
223                                 // ignore
224                             }
225                             cleanupTime = -1;
226                         } else {
227                             processAccessResults(docList, accessResultList, arList);
228                             cleanupTime = cleanupAccessResults(accessResultList);
229                         }
230                         arList = getAccessResultList(cb, cleanupTime);
231                         hitCount = ((EsResultList<EsAccessResult>) arList).getTotalHits();
232                     }
233                     if (!docList.isEmpty()) {
234                         indexingHelper.sendDocuments(fessEsClient, docList);
235                     }
236 
237                     synchronized (finishedSessionIdList) {
238                         if (sessionIdListSize != 0 && sessionIdListSize == finishedSessionIdList.size()) {
239                             cleanupFinishedSessionData();
240                         }
241                     }
242                     executeTime += System.currentTimeMillis() - updateTime;
243 
244                     if (logger.isDebugEnabled()) {
245                         logger.debug("Processed documents in IndexUpdater queue.");
246                     }
247 
248                     // reset count
249                     errorCount = 0;
250                 } catch (final Exception e) {
251                     if (errorCount > maxErrorCount) {
252                         throw e;
253                     }
254                     errorCount++;
255                     logger.warn("Failed to access data. Retry to access.. " + errorCount, e);
256                 } finally {
257                     if (systemHelper.isForceStop()) {
258                         finishCrawling = true;
259                         if (logger.isDebugEnabled()) {
260                             logger.debug("Stopped indexUpdater.");
261                         }
262                     }
263                 }
264 
265                 if (emptyListCount >= maxEmptyListCount) {
266                     if (logger.isInfoEnabled()) {
267                         logger.info("Terminating indexUpdater. " + "emptyListCount is over " + maxEmptyListCount + ".");
268                     }
269                     // terminate crawling
270                     finishCrawling = true;
271                     forceStop();
272                     if (fessConfig.getIndexerThreadDumpEnabledAsBoolean()) {
273                         ThreadDumpUtil.printThreadDump();
274                     }
275                     org.codelibs.fess.exec.Crawler.addError("QueueTimeout");
276                 }
277 
278                 if (!ComponentUtil.available()) {
279                     logger.info("IndexUpdater is terminated.");
280                     forceStop();
281                     break;
282                 }
283             }
284 
285             if (logger.isDebugEnabled()) {
286                 logger.debug("Finished indexUpdater.");
287             }
288         } catch (final ContainerNotAvailableException e) {
289             if (logger.isDebugEnabled()) {
290                 logger.error("IndexUpdater is terminated.", e);
291             } else if (logger.isInfoEnabled()) {
292                 logger.info("IndexUpdater is terminated.");
293             }
294             forceStop();
295         } catch (final Throwable t) {
296             if (ComponentUtil.available()) {
297                 logger.error("IndexUpdater is terminated.", t);
298             } else if (logger.isDebugEnabled()) {
299                 logger.error("IndexUpdater is terminated.", t);
300                 org.codelibs.fess.exec.Crawler.addError(t.getClass().getSimpleName());
301             } else if (logger.isInfoEnabled()) {
302                 logger.info("IndexUpdater is terminated.");
303                 org.codelibs.fess.exec.Crawler.addError(t.getClass().getSimpleName());
304             }
305             forceStop();
306         } finally {
307             intervalControlHelper.setCrawlerRunning(true);
308         }
309 
310         if (logger.isInfoEnabled()) {
311             logger.info("[EXEC TIME] index update time: " + executeTime + "ms");
312         }
313 
314     }
315 
316     private void processAccessResults(final DocList docList, final List<EsAccessResult> accessResultList, final List<EsAccessResult> arList) {
317         final FessConfig fessConfig = ComponentUtil.getFessConfig();
318         final long maxDocumentRequestSize = fessConfig.getIndexerWebfsMaxDocumentRequestSizeAsInteger().longValue();
319         for (final EsAccessResult accessResult : arList) {
320             if (logger.isDebugEnabled()) {
321                 logger.debug("Indexing " + accessResult.getUrl());
322             }
323             accessResult.setStatus(Constants.DONE_STATUS);
324             accessResultList.add(accessResult);
325 
326             if (accessResult.getHttpStatusCode() != 200) {
327                 // invalid page
328                 if (logger.isDebugEnabled()) {
329                     logger.debug("Skipped. The response code is " + accessResult.getHttpStatusCode() + ".");
330                 }
331                 continue;
332             }
333 
334             final long startTime = System.currentTimeMillis();
335             final AccessResultData<?> accessResultData = accessResult.getAccessResultData();
336             if (accessResultData != null) {
337                 accessResult.setAccessResultData(null);
338                 try {
339                     final Transformer transformer = ComponentUtil.getComponent(accessResultData.getTransformerName());
340                     if (transformer == null) {
341                         // no transformer
342                         logger.warn("No transformer: " + accessResultData.getTransformerName());
343                         continue;
344                     }
345                     @SuppressWarnings("unchecked")
346                     final Map<String, Object> map = (Map<String, Object>) transformer.getData(accessResultData);
347                     if (map.isEmpty()) {
348                         // no transformer
349                         logger.warn("No data: " + accessResult.getUrl());
350                         continue;
351                     }
352 
353                     if (Constants.FALSE.equals(map.get(Constants.INDEXING_TARGET))) {
354                         if (logger.isDebugEnabled()) {
355                             logger.debug("Skipped. " + "This document is not a index target. ");
356                         }
357                         continue;
358                     } else {
359                         map.remove(Constants.INDEXING_TARGET);
360                     }
361 
362                     updateDocument(map);
363 
364                     docList.add(map);
365                     final long processingTime = System.currentTimeMillis() - startTime;
366                     docList.addProcessingTime(processingTime);
367                     if (logger.isDebugEnabled()) {
368                         logger.debug("Added the document(" + MemoryUtil.byteCountToDisplaySize(docList.getContentSize()) + ", "
369                                 + processingTime + "ms). " + "The number of a document cache is " + docList.size() + ".");
370                     }
371 
372                     if (accessResult.getContentLength() == null) {
373                         indexingHelper.sendDocuments(fessEsClient, docList);
374                     } else {
375                         docList.addContentSize(accessResult.getContentLength().longValue());
376                         if (docList.getContentSize() >= maxDocumentRequestSize) {
377                             indexingHelper.sendDocuments(fessEsClient, docList);
378                         }
379                     }
380                     documentSize++;
381                     if (logger.isDebugEnabled()) {
382                         logger.debug("The number of an added document is " + documentSize + ".");
383                     }
384                 } catch (final Exception e) {
385                     logger.warn("Could not add a doc: " + accessResult.getUrl(), e);
386                 }
387             } else {
388                 if (logger.isDebugEnabled()) {
389                     logger.debug("Skipped. No content. ");
390                 }
391             }
392 
393         }
394     }
395 
396     protected void updateDocument(final Map<String, Object> map) {
397         final FessConfig fessConfig = ComponentUtil.getFessConfig();
398 
399         if (fessConfig.getIndexerClickCountEnabledAsBoolean()) {
400             addClickCountField(map);
401         }
402 
403         if (fessConfig.getIndexerFavoriteCountEnabledAsBoolean()) {
404             addFavoriteCountField(map);
405         }
406 
407         float documentBoost = 0.0f;
408         for (final DocBoostMatcher docBoostMatcher : docBoostMatcherList) {
409             if (docBoostMatcher.match(map)) {
410                 documentBoost = docBoostMatcher.getValue(map);
411                 break;
412             }
413         }
414 
415         if (documentBoost > 0) {
416             addBoostValue(map, documentBoost);
417         }
418 
419         if (!map.containsKey(fessConfig.getIndexFieldDocId())) {
420             map.put(fessConfig.getIndexFieldDocId(), systemHelper.generateDocId(map));
421         }
422 
423         ComponentUtil.getLanguageHelper().updateDocument(map);
424     }
425 
426     protected void addBoostValue(final Map<String, Object> map, final float documentBoost) {
427         final FessConfig fessConfig = ComponentUtil.getFessConfig();
428         map.put(fessConfig.getIndexFieldBoost(), documentBoost);
429         if (logger.isDebugEnabled()) {
430             logger.debug("Set a document boost (" + documentBoost + ").");
431         }
432     }
433 
434     protected void addClickCountField(final Map<String, Object> doc) {
435         final FessConfig fessConfig = ComponentUtil.getFessConfig();
436         final String url = (String) doc.get(fessConfig.getIndexFieldUrl());
437         if (StringUtil.isNotBlank(url)) {
438             final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
439             final int count = searchLogHelper.getClickCount(url);
440             doc.put(fessConfig.getIndexFieldClickCount(), count);
441             if (logger.isDebugEnabled()) {
442                 logger.debug("Click Count: " + count + ", url: " + url);
443             }
444         }
445     }
446 
447     protected void addFavoriteCountField(final Map<String, Object> map) {
448         final FessConfig fessConfig = ComponentUtil.getFessConfig();
449         final String url = (String) map.get(fessConfig.getIndexFieldUrl());
450         if (StringUtil.isNotBlank(url)) {
451             final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
452             final long count = searchLogHelper.getFavoriteCount(url);
453             map.put(fessConfig.getIndexFieldFavoriteCount(), count);
454             if (logger.isDebugEnabled()) {
455                 logger.debug("Favorite Count: " + count + ", url: " + url);
456             }
457         }
458     }
459 
460     private long cleanupAccessResults(final List<EsAccessResult> accessResultList) {
461         if (!accessResultList.isEmpty()) {
462             final long execTime = System.currentTimeMillis();
463             final int size = accessResultList.size();
464             dataService.update(accessResultList);
465             accessResultList.clear();
466             final long time = System.currentTimeMillis() - execTime;
467             if (logger.isDebugEnabled()) {
468                 logger.debug("Updated " + size + " access results. The execution time is " + time + "ms.");
469             }
470             return time;
471         }
472         return -1;
473     }
474 
475     private List<EsAccessResult> getAccessResultList(final Consumer<SearchRequestBuilder> cb, final long cleanupTime) {
476         if (logger.isDebugEnabled()) {
477             logger.debug("Getting documents in IndexUpdater queue.");
478         }
479         final long execTime = System.currentTimeMillis();
480         final List<EsAccessResult> arList = ((EsDataService) dataService).getAccessResultList(cb);
481         final FessConfig fessConfig = ComponentUtil.getFessConfig();
482         if (!arList.isEmpty()) {
483             final long commitMarginTime = fessConfig.getIndexerWebfsCommitMarginTimeAsInteger().longValue();
484             for (final AccessResult<?> ar : arList.toArray(new AccessResult[arList.size()])) {
485                 if (ar.getCreateTime().longValue() > execTime - commitMarginTime) {
486                     arList.remove(ar);
487                 }
488             }
489         }
490         final long totalHits = ((EsResultList<EsAccessResult>) arList).getTotalHits();
491         if (logger.isInfoEnabled()) {
492             final StringBuilder buf = new StringBuilder(100);
493             buf.append("Processing ");
494             if (totalHits > 0) {
495                 buf.append(arList.size()).append('/').append(totalHits).append(" docs (Doc:{access ");
496             } else {
497                 buf.append("no docs (Doc:{access ");
498             }
499             buf.append(System.currentTimeMillis() - execTime).append("ms");
500             if (cleanupTime >= 0) {
501                 buf.append(", cleanup ").append(cleanupTime).append("ms");
502             }
503             buf.append("}, ");
504             buf.append(MemoryUtil.getMemoryUsageLog());
505             buf.append(')');
506             logger.info(buf.toString());
507         }
508         final long unprocessedDocumentSize = fessConfig.getIndexerUnprocessedDocumentSizeAsInteger().longValue();
509         final IntervalControlHelper intervalControlHelper = ComponentUtil.getIntervalControlHelper();
510         if (totalHits > unprocessedDocumentSize && intervalControlHelper.isCrawlerRunning()) {
511             if (logger.isInfoEnabled()) {
512                 logger.info("Stopped all crawler threads. " + " You have " + totalHits + " (>" + unprocessedDocumentSize + ") "
513                         + " unprocessed docs.");
514             }
515             intervalControlHelper.setCrawlerRunning(false);
516         }
517         return arList;
518     }
519 
520     private void cleanupFinishedSessionData() {
521         final long execTime = System.currentTimeMillis();
522         // cleanup
523         for (final String sessionId : finishedSessionIdList) {
524             final long execTime2 = System.currentTimeMillis();
525             if (logger.isDebugEnabled()) {
526                 logger.debug("Deleting document data: " + sessionId);
527             }
528             deleteBySessionId(sessionId);
529             if (logger.isDebugEnabled()) {
530                 logger.debug("Deleted " + sessionId + " documents. The execution time is " + (System.currentTimeMillis() - execTime2)
531                         + "ms.");
532             }
533         }
534         finishedSessionIdList.clear();
535 
536         if (logger.isInfoEnabled()) {
537             logger.info("Deleted completed document data. " + "The execution time is " + (System.currentTimeMillis() - execTime) + "ms.");
538         }
539     }
540 
541     private void forceStop() {
542         systemHelper.setForceStop(true);
543         for (final Crawler crawler : crawlerList) {
544             crawler.stop();
545         }
546     }
547 
548     public long getExecuteTime() {
549         return executeTime;
550     }
551 
552     public List<String> getSessionIdList() {
553         return sessionIdList;
554     }
555 
556     public void setSessionIdList(final List<String> sessionIdList) {
557         this.sessionIdList = sessionIdList;
558     }
559 
560     public void setFinishCrawling(final boolean finishCrawling) {
561         this.finishCrawling = finishCrawling;
562     }
563 
564     public long getDocumentSize() {
565         return documentSize;
566     }
567 
568     @Override
569     public void setUncaughtExceptionHandler(final UncaughtExceptionHandler eh) {
570         super.setUncaughtExceptionHandler(eh);
571     }
572 
573     public static void setDefaultUncaughtExceptionHandler(final UncaughtExceptionHandler eh) {
574         Thread.setDefaultUncaughtExceptionHandler(eh);
575     }
576 
577     public void setMaxIndexerErrorCount(final int maxIndexerErrorCount) {
578         this.maxIndexerErrorCount = maxIndexerErrorCount;
579     }
580 
581     public void addDocBoostMatcher(final DocBoostMatcher rule) {
582         docBoostMatcherList.add(rule);
583     }
584 
585     public void setCrawlerList(final List<Crawler> crawlerList) {
586         this.crawlerList = crawlerList;
587     }
588 }