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 java.util.ArrayList;
19  import java.util.Collections;
20  import java.util.HashMap;
21  import java.util.List;
22  import java.util.Map;
23  
24  import org.codelibs.core.lang.StringUtil;
25  import org.codelibs.fess.Constants;
26  import org.codelibs.fess.app.service.FailureUrlService;
27  import org.codelibs.fess.ds.DataStore;
28  import org.codelibs.fess.ds.DataStoreFactory;
29  import org.codelibs.fess.ds.callback.IndexUpdateCallback;
30  import org.codelibs.fess.es.client.FessEsClient;
31  import org.codelibs.fess.es.config.exentity.DataConfig;
32  import org.codelibs.fess.mylasta.direction.FessConfig;
33  import org.codelibs.fess.util.ComponentUtil;
34  import org.elasticsearch.index.query.QueryBuilder;
35  import org.elasticsearch.index.query.QueryBuilders;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  public class DataIndexHelper {
40  
41      private static final Logger logger = LoggerFactory.getLogger(DataIndexHelper.class);
42  
43      private static final String DELETE_OLD_DOCS = "delete_old_docs";
44  
45      protected long crawlingExecutionInterval = Constants.DEFAULT_CRAWLING_EXECUTION_INTERVAL;
46  
47      protected int crawlerPriority = Thread.NORM_PRIORITY;
48  
49      protected final List<DataCrawlingThread> dataCrawlingThreadList = Collections.synchronizedList(new ArrayList<DataCrawlingThread>());
50  
51      public void crawl(final String sessionId) {
52          final List<DataConfig> configList = ComponentUtil.getCrawlingConfigHelper().getAllDataConfigList();
53  
54          if (configList.isEmpty()) {
55              // nothing
56              if (logger.isInfoEnabled()) {
57                  logger.info("No crawling target data.");
58              }
59              return;
60          }
61  
62          doCrawl(sessionId, configList);
63      }
64  
65      public void crawl(final String sessionId, final List<String> configIdList) {
66          final List<DataConfig> configList = ComponentUtil.getCrawlingConfigHelper().getDataConfigListByIds(configIdList);
67  
68          if (configList.isEmpty()) {
69              // nothing
70              if (logger.isInfoEnabled()) {
71                  logger.info("No crawling target urls.");
72              }
73              return;
74          }
75  
76          doCrawl(sessionId, configList);
77      }
78  
79      protected void doCrawl(final String sessionId, final List<DataConfig> configList) {
80          final int multiprocessCrawlingCount = ComponentUtil.getFessConfig().getCrawlingThreadCount();
81  
82          final long startTime = System.currentTimeMillis();
83  
84          final IndexUpdateCallback indexUpdateCallback = ComponentUtil.getComponent(IndexUpdateCallback.class);
85  
86          final List<String> sessionIdList = new ArrayList<>();
87          dataCrawlingThreadList.clear();
88          final List<String> dataCrawlingThreadStatusList = new ArrayList<>();
89          for (final DataConfig dataConfig : configList) {
90              final Map<String, String> initParamMap = new HashMap<>();
91              final String sid = ComponentUtil.getCrawlingConfigHelper().store(sessionId, dataConfig);
92              sessionIdList.add(sid);
93  
94              initParamMap.put(Constants.SESSION_ID, sessionId);
95              initParamMap.put(Constants.CRAWLING_INFO_ID, sid);
96  
97              final DataCrawlingThread dataCrawlingThread = new DataCrawlingThread(dataConfig, indexUpdateCallback, initParamMap);
98              dataCrawlingThread.setPriority(crawlerPriority);
99              dataCrawlingThread.setName(sid);
100             dataCrawlingThread.setDaemon(true);
101 
102             dataCrawlingThreadList.add(dataCrawlingThread);
103             dataCrawlingThreadStatusList.add(Constants.READY);
104 
105         }
106 
107         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
108 
109         int startedCrawlerNum = 0;
110         int activeCrawlerNum = 0;
111         while (startedCrawlerNum < dataCrawlingThreadList.size()) {
112             // Force to stop crawl
113             if (systemHelper.isForceStop()) {
114                 for (final DataCrawlingThread crawlerThread : dataCrawlingThreadList) {
115                     crawlerThread.stopCrawling();
116                 }
117                 break;
118             }
119 
120             if (activeCrawlerNum < multiprocessCrawlingCount) {
121                 // start crawling
122                 dataCrawlingThreadList.get(startedCrawlerNum).start();
123                 dataCrawlingThreadStatusList.set(startedCrawlerNum, Constants.RUNNING);
124                 startedCrawlerNum++;
125                 activeCrawlerNum++;
126                 try {
127                     Thread.sleep(crawlingExecutionInterval);
128                 } catch (final InterruptedException e) {
129                     if (logger.isDebugEnabled()) {
130                         logger.debug("Interrupted.", e);
131                     }
132                 }
133                 continue;
134             }
135 
136             // check status
137             for (int i = 0; i < startedCrawlerNum; i++) {
138                 if (!dataCrawlingThreadList.get(i).isRunning() && dataCrawlingThreadStatusList.get(i).equals(Constants.RUNNING)) {
139                     dataCrawlingThreadList.get(i).awaitTermination();
140                     dataCrawlingThreadStatusList.set(i, Constants.DONE);
141                     activeCrawlerNum--;
142                 }
143             }
144             try {
145                 Thread.sleep(crawlingExecutionInterval);
146             } catch (final InterruptedException e) {
147                 if (logger.isDebugEnabled()) {
148                     logger.debug("Interrupted.", e);
149                 }
150             }
151         }
152 
153         boolean finishedAll = false;
154         while (!finishedAll) {
155             finishedAll = true;
156             for (int i = 0; i < dataCrawlingThreadList.size(); i++) {
157                 dataCrawlingThreadList.get(i).awaitTermination(crawlingExecutionInterval);
158                 if (!dataCrawlingThreadList.get(i).isRunning() && dataCrawlingThreadStatusList.get(i).equals(Constants.RUNNING)) {
159                     dataCrawlingThreadStatusList.set(i, Constants.DONE);
160                 }
161                 if (!dataCrawlingThreadStatusList.get(i).equals(Constants.DONE)) {
162                     finishedAll = false;
163                 }
164             }
165         }
166         dataCrawlingThreadList.clear();
167         dataCrawlingThreadStatusList.clear();
168 
169         // put cralwing info
170         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
171 
172         final long execTime = System.currentTimeMillis() - startTime;
173         crawlingInfoHelper.putToInfoMap(Constants.DATA_CRAWLING_EXEC_TIME, Long.toString(execTime));
174         if (logger.isInfoEnabled()) {
175             logger.info("[EXEC TIME] crawling time: " + execTime + "ms");
176         }
177 
178         crawlingInfoHelper.putToInfoMap(Constants.DATA_INDEX_EXEC_TIME, Long.toString(indexUpdateCallback.getExecuteTime()));
179         crawlingInfoHelper.putToInfoMap(Constants.DATA_INDEX_SIZE, Long.toString(indexUpdateCallback.getDocumentSize()));
180 
181         for (final String sid : sessionIdList) {
182             // remove config
183             ComponentUtil.getCrawlingConfigHelper().remove(sid);
184         }
185 
186     }
187 
188     protected static class DataCrawlingThread extends Thread {
189 
190         private final DataConfig dataConfig;
191 
192         private final IndexUpdateCallback indexUpdateCallback;
193 
194         private final Map<String, String> initParamMap;
195 
196         protected boolean finished = false;
197 
198         protected boolean running = false;
199 
200         private DataStore dataStore;
201 
202         protected DataCrawlingThread(final DataConfig dataConfig, final IndexUpdateCallback indexUpdateCallback,
203                 final Map<String, String> initParamMap) {
204             this.dataConfig = dataConfig;
205             this.indexUpdateCallback = indexUpdateCallback;
206             this.initParamMap = initParamMap;
207         }
208 
209         @Override
210         public void run() {
211             running = true;
212             try {
213                 process();
214             } finally {
215                 running = false;
216                 finished = true;
217             }
218         }
219 
220         protected void process() {
221             final DataStoreFactory dataStoreFactory = ComponentUtil.getDataStoreFactory();
222             dataStore = dataStoreFactory.getDataStore(dataConfig.getHandlerName());
223             if (dataStore == null) {
224                 logger.error("DataStore(" + dataConfig.getHandlerName() + ") is not found.");
225             } else {
226                 try {
227                     dataStore.store(dataConfig, indexUpdateCallback, initParamMap);
228                 } catch (final Throwable e) {
229                     logger.error("Failed to process a data crawling: " + dataConfig.getName(), e);
230                     ComponentUtil.getComponent(FailureUrlService.class).store(dataConfig, e.getClass().getCanonicalName(),
231                             dataConfig.getConfigId() + ":" + dataConfig.getName(), e);
232                 } finally {
233                     indexUpdateCallback.commit();
234                     deleteOldDocs();
235                 }
236             }
237         }
238 
239         private void deleteOldDocs() {
240             if (Constants.FALSE.equals(initParamMap.get(DELETE_OLD_DOCS))) {
241                 return;
242             }
243             final String sessionId = initParamMap.get(Constants.SESSION_ID);
244             if (StringUtil.isBlank(sessionId)) {
245                 logger.warn("Invalid sessionId at " + dataConfig);
246                 return;
247             }
248             final FessConfig fessConfig = ComponentUtil.getFessConfig();
249             final QueryBuilder queryBuilder =
250                     QueryBuilders
251                             .boolQuery()
252                             .must(QueryBuilders.termQuery(fessConfig.getIndexFieldConfigId(), dataConfig.getConfigId()))
253                             .must(QueryBuilders.boolQuery().mustNot(QueryBuilders.rangeQuery(fessConfig.getIndexFieldExpires()).gt("now"))
254                                     .mustNot(QueryBuilders.existsQuery(fessConfig.getIndexFieldExpires())))
255                             .mustNot(QueryBuilders.termQuery(fessConfig.getIndexFieldSegment(), sessionId));
256             try {
257                 final FessEsClient fessEsClient = ComponentUtil.getFessEsClient();
258                 final String index = fessConfig.getIndexDocumentUpdateIndex();
259                 fessEsClient.admin().indices().prepareRefresh(index).execute().actionGet();
260                 final long numOfDeleted = fessEsClient.deleteByQuery(index, queryBuilder);
261                 logger.info("Deleted {} old docs.", numOfDeleted);
262             } catch (final Exception e) {
263                 logger.error("Could not delete old docs at " + dataConfig, e);
264             }
265         }
266 
267         public boolean isFinished() {
268             return finished;
269         }
270 
271         public void stopCrawling() {
272             if (dataStore != null) {
273                 dataStore.stop();
274             }
275         }
276 
277         public String getCrawlingInfoId() {
278             return initParamMap.get(Constants.CRAWLING_INFO_ID);
279         }
280 
281         public boolean isRunning() {
282             return running;
283         }
284 
285         public void awaitTermination() {
286             try {
287                 join();
288             } catch (final InterruptedException e) {
289                 if (logger.isDebugEnabled()) {
290                     logger.debug("Interrupted.", e);
291                 }
292             }
293         }
294 
295         public void awaitTermination(final long mills) {
296             try {
297                 join(mills);
298             } catch (final InterruptedException e) {
299                 if (logger.isDebugEnabled()) {
300                     logger.debug("Interrupted.", e);
301                 }
302             }
303         }
304     }
305 
306     public void setCrawlingExecutionInterval(final long crawlingExecutionInterval) {
307         this.crawlingExecutionInterval = crawlingExecutionInterval;
308     }
309 
310     public void setCrawlerPriority(final int crawlerPriority) {
311         this.crawlerPriority = crawlerPriority;
312     }
313 }