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 java.io.File;
19  import java.io.IOException;
20  import java.lang.management.ManagementFactory;
21  import java.time.LocalDateTime;
22  import java.util.concurrent.CountDownLatch;
23  import java.util.concurrent.atomic.AtomicInteger;
24  
25  import javax.annotation.Resource;
26  
27  import org.codelibs.core.lang.StringUtil;
28  import org.codelibs.core.misc.DynamicProperties;
29  import org.codelibs.core.timer.TimeoutManager;
30  import org.codelibs.core.timer.TimeoutTask;
31  import org.codelibs.fess.Constants;
32  import org.codelibs.fess.crawler.client.EsClient;
33  import org.codelibs.fess.es.client.FessEsClient;
34  import org.codelibs.fess.exception.ContainerNotAvailableException;
35  import org.codelibs.fess.helper.SuggestHelper;
36  import org.codelibs.fess.timer.SystemMonitorTarget;
37  import org.codelibs.fess.util.ComponentUtil;
38  import org.elasticsearch.monitor.jvm.JvmInfo;
39  import org.elasticsearch.monitor.os.OsProbe;
40  import org.elasticsearch.monitor.process.ProcessProbe;
41  import org.kohsuke.args4j.CmdLineException;
42  import org.kohsuke.args4j.CmdLineParser;
43  import org.kohsuke.args4j.Option;
44  import org.lastaflute.di.core.external.GenericExternalContext;
45  import org.lastaflute.di.core.external.GenericExternalContextComponentDefRegister;
46  import org.lastaflute.di.core.factory.SingletonLaContainerFactory;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  public class SuggestCreator {
51  
52      private static final Logger logger = LoggerFactory.getLogger(SuggestCreator.class);
53  
54      @Resource
55      public FessEsClient fessEsClient;
56  
57      protected static class Options {
58          @Option(name = "-s", aliases = "--sessionId", metaVar = "sessionId", usage = "Session ID")
59          protected String sessionId;
60  
61          @Option(name = "-n", aliases = "--name", metaVar = "name", usage = "Name")
62          protected String name;
63  
64          @Option(name = "-p", aliases = "--properties", metaVar = "properties", usage = "Properties File")
65          protected String propertiesPath;
66  
67          protected Options() {
68              // nothing
69          }
70  
71          @Override
72          public String toString() {
73              return "Options [sessionId=" + sessionId + ", name=" + name + ", propertiesPath=" + propertiesPath + "]";
74          }
75      }
76  
77      static void initializeProbes() {
78          // Force probes to be loaded
79          ProcessProbe.getInstance();
80          OsProbe.getInstance();
81          JvmInfo.jvmInfo();
82      }
83  
84      public static void main(final String[] args) {
85          final Options options = new Options();
86  
87          final CmdLineParser parser = new CmdLineParser(options);
88          try {
89              parser.parseArgument(args);
90          } catch (final CmdLineException e) {
91              System.err.println(e.getMessage());
92              System.err.println("java " + SuggestCreator.class.getCanonicalName() + " [options...] arguments...");
93              parser.printUsage(System.err);
94              return;
95          }
96  
97          if (logger.isDebugEnabled()) {
98              try {
99                  ManagementFactory.getRuntimeMXBean().getInputArguments().stream().forEach(s -> logger.debug("Parameter: " + s));
100                 System.getProperties().entrySet().stream().forEach(e -> logger.debug("Property: " + e.getKey() + "=" + e.getValue()));
101                 System.getenv().entrySet().forEach(e -> logger.debug("Env: " + e.getKey() + "=" + e.getValue()));
102                 logger.debug("Option: " + options);
103             } catch (final Exception e) {
104                 // ignore
105             }
106         }
107 
108         final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
109         if (StringUtil.isNotBlank(httpAddress)) {
110             System.setProperty(EsClient.HTTP_ADDRESS, httpAddress);
111         }
112 
113         TimeoutTask systemMonitorTask = null;
114         int exitCode;
115         try {
116             SingletonLaContainerFactory.setConfigPath("app.xml");
117             SingletonLaContainerFactory.setExternalContext(new GenericExternalContext());
118             SingletonLaContainerFactory.setExternalContextComponentDefRegister(new GenericExternalContextComponentDefRegister());
119             SingletonLaContainerFactory.init();
120 
121             final Thread shutdownCallback = new Thread("ShutdownHook") {
122                 @Override
123                 public void run() {
124                     if (logger.isDebugEnabled()) {
125                         logger.debug("Destroying LaContainer..");
126                     }
127                     destroyContainer();
128                 }
129             };
130             Runtime.getRuntime().addShutdownHook(shutdownCallback);
131 
132             systemMonitorTask =
133                     TimeoutManager.getInstance().addTimeoutTarget(new SystemMonitorTarget(),
134                             ComponentUtil.getFessConfig().getSuggestSystemMonitorIntervalAsInteger(), true);
135 
136             exitCode = process(options);
137         } catch (final ContainerNotAvailableException e) {
138             if (logger.isDebugEnabled()) {
139                 logger.debug("SuggestCreator is stopped.", e);
140             } else if (logger.isInfoEnabled()) {
141                 logger.info("SuggestCreator is stopped.");
142             }
143             exitCode = Constants.EXIT_FAIL;
144         } catch (final Throwable t) {
145             logger.error("Suggest creator does not work correctly.", t);
146             exitCode = Constants.EXIT_FAIL;
147         } finally {
148             if (systemMonitorTask != null) {
149                 systemMonitorTask.cancel();
150             }
151             destroyContainer();
152         }
153 
154         logger.info("Finished SuggestCreator.");
155         System.exit(exitCode);
156     }
157 
158     private static void destroyContainer() {
159         synchronized (SingletonLaContainerFactory.class) {
160             SingletonLaContainerFactory.destroy();
161         }
162     }
163 
164     private static int process(final Options options) {
165         final DynamicProperties systemProperties = ComponentUtil.getSystemProperties();
166 
167         if (StringUtil.isNotBlank(options.propertiesPath)) {
168             systemProperties.reload(options.propertiesPath);
169         } else {
170             try {
171                 final File propFile = File.createTempFile("suggest_", ".properties");
172                 if (propFile.delete() && logger.isDebugEnabled()) {
173                     logger.debug("Deleted a temp file: " + propFile.getAbsolutePath());
174                 }
175                 systemProperties.reload(propFile.getAbsolutePath());
176                 propFile.deleteOnExit();
177             } catch (final IOException e) {
178                 logger.warn("Failed to create system properties file.", e);
179             }
180         }
181 
182         final SuggestCreator creator = ComponentUtil.getComponent(SuggestCreator.class);
183         final LocalDateTime startTime = LocalDateTime.now();
184         int ret = creator.create();
185         if (ret == 0) {
186             ret = creator.purge(startTime);
187         }
188         return ret;
189     }
190 
191     private int create() {
192         if (!ComponentUtil.getFessConfig().isSuggestDocuments()) {
193             logger.info("Skip create suggest document.");
194             return 0;
195         }
196 
197         logger.info("Start create suggest document.");
198 
199         final AtomicInteger result = new AtomicInteger(1);
200         final CountDownLatch latch = new CountDownLatch(1);
201 
202         final SuggestHelper suggestHelper = ComponentUtil.getSuggestHelper();
203 
204         logger.info("Create update index.");
205         suggestHelper.suggester().createNextIndex();
206 
207         logger.info("Store all bad words.");
208         suggestHelper.storeAllBadWords(true);
209 
210         logger.info("Store all elevate words.");
211         suggestHelper.storeAllElevateWords(true);
212 
213         logger.info("Parse words from indexed documents.");
214         suggestHelper.indexFromDocuments(ret -> {
215             logger.info("Success index from documents.");
216             result.set(0);
217             latch.countDown();
218         }, t -> {
219             logger.error("Failed to update suggest index.", t);
220             latch.countDown();
221         });
222 
223         try {
224             latch.await();
225         } catch (final InterruptedException ignore) {
226             if (logger.isDebugEnabled()) {
227                 logger.debug("Interrupted.", ignore);
228             }
229         }
230 
231         logger.info("Store search logs.");
232         suggestHelper.storeSearchLog();
233 
234         logger.info("Switch indices.");
235         suggestHelper.suggester().switchIndex();
236 
237         logger.info("Remove old indices.");
238         suggestHelper.suggester().removeDisableIndices();
239 
240         return result.get();
241     }
242 
243     private int purge(final LocalDateTime time) {
244         final SuggestHelper suggestHelper = ComponentUtil.getSuggestHelper();
245 
246         try {
247             suggestHelper.purgeDocumentSuggest(time);
248             final long cleanupDay = ComponentUtil.getFessConfig().getPurgeSuggestSearchLogDay();
249             if (cleanupDay > 0) {
250                 suggestHelper.purgeSearchlogSuggest(time.minusDays(cleanupDay));
251             }
252             return 0;
253         } catch (final Exception e) {
254             logger.info("Purge error.", e);
255             return 1;
256         }
257     }
258 
259 }