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.util.concurrent.ExecutorService;
22  import java.util.concurrent.Executors;
23  import java.util.concurrent.TimeUnit;
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.timer.SystemMonitorTarget;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.elasticsearch.monitor.jvm.JvmInfo;
38  import org.elasticsearch.monitor.os.OsProbe;
39  import org.elasticsearch.monitor.process.ProcessProbe;
40  import org.kohsuke.args4j.CmdLineException;
41  import org.kohsuke.args4j.CmdLineParser;
42  import org.kohsuke.args4j.Option;
43  import org.lastaflute.di.core.external.GenericExternalContext;
44  import org.lastaflute.di.core.external.GenericExternalContextComponentDefRegister;
45  import org.lastaflute.di.core.factory.SingletonLaContainerFactory;
46  import org.slf4j.Logger;
47  import org.slf4j.LoggerFactory;
48  
49  public class ThumbnailGenerator {
50  
51      private static final Logger logger = LoggerFactory.getLogger(ThumbnailGenerator.class);
52  
53      @Resource
54      public FessEsClient fessEsClient;
55  
56      protected static class Options {
57          @Option(name = "-s", aliases = "--sessionId", metaVar = "sessionId", usage = "Session ID")
58          protected String sessionId;
59  
60          @Option(name = "-n", aliases = "--name", metaVar = "name", usage = "Name")
61          protected String name;
62  
63          @Option(name = "-p", aliases = "--properties", metaVar = "properties", usage = "Properties File")
64          protected String propertiesPath;
65  
66          @Option(name = "-t", aliases = "--numOfThreads", metaVar = "numOfThreads", usage = "The number of threads")
67          protected int numOfThreads = 1;
68  
69          @Option(name = "-c", aliases = "--cleanup", usage = "Clean-Up mode")
70          protected boolean cleanup;
71  
72          protected Options() {
73              // nothing
74          }
75  
76          @Override
77          public String toString() {
78              return "Options [sessionId=" + sessionId + ", name=" + name + ", propertiesPath=" + propertiesPath + ", numOfThreads="
79                      + numOfThreads + "]";
80          }
81  
82      }
83  
84      static void initializeProbes() {
85          // Force probes to be loaded
86          ProcessProbe.getInstance();
87          OsProbe.getInstance();
88          JvmInfo.jvmInfo();
89      }
90  
91      public static void main(final String[] args) {
92          final Options options = new Options();
93  
94          final CmdLineParser parser = new CmdLineParser(options);
95          try {
96              parser.parseArgument(args);
97          } catch (final CmdLineException e) {
98              System.err.println(e.getMessage());
99              System.err.println("java " + ThumbnailGenerator.class.getCanonicalName() + " [options...] arguments...");
100             parser.printUsage(System.err);
101             return;
102         }
103 
104         if (logger.isDebugEnabled()) {
105             try {
106                 ManagementFactory.getRuntimeMXBean().getInputArguments().stream().forEach(s -> logger.debug("Parameter: " + s));
107                 System.getProperties().entrySet().stream().forEach(e -> logger.debug("Property: " + e.getKey() + "=" + e.getValue()));
108                 System.getenv().entrySet().forEach(e -> logger.debug("Env: " + e.getKey() + "=" + e.getValue()));
109                 logger.debug("Option: " + options);
110             } catch (final Exception e) {
111                 // ignore
112             }
113         }
114 
115         final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
116         if (StringUtil.isNotBlank(httpAddress)) {
117             System.setProperty(EsClient.HTTP_ADDRESS, httpAddress);
118         }
119 
120         TimeoutTask systemMonitorTask = null;
121         int exitCode;
122         try {
123             SingletonLaContainerFactory.setConfigPath("app.xml");
124             SingletonLaContainerFactory.setExternalContext(new GenericExternalContext());
125             SingletonLaContainerFactory.setExternalContextComponentDefRegister(new GenericExternalContextComponentDefRegister());
126             SingletonLaContainerFactory.init();
127 
128             final Thread shutdownCallback = new Thread("ShutdownHook") {
129                 @Override
130                 public void run() {
131                     if (logger.isDebugEnabled()) {
132                         logger.debug("Destroying LaContainer..");
133                     }
134                     destroyContainer();
135                 }
136             };
137             Runtime.getRuntime().addShutdownHook(shutdownCallback);
138 
139             systemMonitorTask =
140                     TimeoutManager.getInstance().addTimeoutTarget(new SystemMonitorTarget(),
141                             ComponentUtil.getFessConfig().getSuggestSystemMonitorIntervalAsInteger(), true);
142 
143             final int totalCount = process(options);
144             if (totalCount != 0) {
145                 logger.info("Created " + totalCount + " thumbnail files.");
146             } else {
147                 logger.info("No new thumbnails found.");
148             }
149             exitCode = 0;
150         } catch (final ContainerNotAvailableException e) {
151             if (logger.isDebugEnabled()) {
152                 logger.debug("ThumbnailGenerator is stopped.", e);
153             } else if (logger.isInfoEnabled()) {
154                 logger.info("ThumbnailGenerator is stopped.");
155             }
156             exitCode = Constants.EXIT_FAIL;
157         } catch (final Throwable t) {
158             logger.error("ThumbnailGenerator does not work correctly.", t);
159             exitCode = Constants.EXIT_FAIL;
160         } finally {
161             if (systemMonitorTask != null) {
162                 systemMonitorTask.cancel();
163             }
164             destroyContainer();
165         }
166 
167         System.exit(exitCode);
168     }
169 
170     private static void destroyContainer() {
171         synchronized (SingletonLaContainerFactory.class) {
172             SingletonLaContainerFactory.destroy();
173         }
174     }
175 
176     private static int process(final Options options) {
177         final DynamicProperties systemProperties = ComponentUtil.getSystemProperties();
178 
179         if (StringUtil.isNotBlank(options.propertiesPath)) {
180             systemProperties.reload(options.propertiesPath);
181         } else {
182             try {
183                 final File propFile = File.createTempFile("thumbnail_", ".properties");
184                 if (propFile.delete() && logger.isDebugEnabled()) {
185                     logger.debug("Deleted a temp file: " + propFile.getAbsolutePath());
186                 }
187                 systemProperties.reload(propFile.getAbsolutePath());
188                 propFile.deleteOnExit();
189             } catch (final IOException e) {
190                 logger.warn("Failed to create system properties file.", e);
191             }
192         }
193 
194         int totalCount = 0;
195         int count = 1;
196         final ExecutorService executorService = Executors.newFixedThreadPool(options.numOfThreads);
197         try {
198             while (count != 0) {
199                 count = ComponentUtil.getThumbnailManager().generate(executorService, options.cleanup);
200                 totalCount += count;
201             }
202             executorService.shutdown();
203             executorService.awaitTermination(60, TimeUnit.SECONDS);
204         } catch (InterruptedException e) {
205             if (logger.isDebugEnabled()) {
206                 logger.debug("Interrupted.", e);
207             }
208         } finally {
209             executorService.shutdownNow();
210         }
211         return totalCount;
212     }
213 }