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.app.web.admin.maintenance;
17  
18  import java.io.IOException;
19  import java.net.InetAddress;
20  import java.nio.file.Files;
21  import java.nio.file.Path;
22  import java.nio.file.Paths;
23  import java.text.SimpleDateFormat;
24  import java.util.Arrays;
25  import java.util.Date;
26  import java.util.Properties;
27  import java.util.stream.Stream;
28  import java.util.zip.ZipEntry;
29  import java.util.zip.ZipOutputStream;
30  
31  import javax.annotation.Resource;
32  
33  import org.codelibs.core.io.CopyUtil;
34  import org.codelibs.core.lang.StringUtil;
35  import org.codelibs.curl.CurlResponse;
36  import org.codelibs.fess.Constants;
37  import org.codelibs.fess.app.web.base.FessAdminAction;
38  import org.codelibs.fess.es.client.FessEsClient;
39  import org.codelibs.fess.mylasta.direction.FessConfig.SimpleImpl;
40  import org.codelibs.fess.util.ComponentUtil;
41  import org.elasticsearch.action.ActionListener;
42  import org.lastaflute.web.Execute;
43  import org.lastaflute.web.response.ActionResponse;
44  import org.lastaflute.web.response.HtmlResponse;
45  import org.lastaflute.web.ruts.process.ActionRuntime;
46  import org.slf4j.Logger;
47  import org.slf4j.LoggerFactory;
48  
49  public class AdminMaintenanceAction extends FessAdminAction {
50  
51      // ===================================================================================
52      //                                                                            Constant
53      //
54      private static final Logger logger = LoggerFactory.getLogger(AdminMaintenanceAction.class);
55  
56      private static final String[] ES_CAT_NAMES = new String[] { "aliases", "allocation", "count", "fielddata", "health", "indices",
57              "master", "nodeattrs", "nodes", "pending_tasks", "plugins", "recovery", "repositories", "thread_pool", "shards", "segments",
58              "snapshots", "templates" };
59  
60      // ===================================================================================
61      //                                                                           Attribute
62      //
63  
64      @Resource
65      protected FessEsClient fessEsClient;
66  
67      // ===================================================================================
68      //                                                                               Hook
69      //                                                                              ======
70      @Override
71      protected void setupHtmlData(final ActionRuntime runtime) {
72          super.setupHtmlData(runtime);
73          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameMaintenance()));
74      }
75  
76      // ===================================================================================
77      //                                                                      Search Execute
78      //                                                                      ==============
79  
80      @Execute
81      public HtmlResponse index() {
82          saveToken();
83          return asIndexHtml();
84      }
85  
86      private HtmlResponse asIndexHtml() {
87          return asHtml(path_AdminMaintenance_AdminMaintenanceJsp).useForm(ActionForm.class, op -> op.setup(f -> {
88              f.replaceAliases = Constants.ON;
89              f.resetDictionaries = Constants.ON;
90          }));
91      }
92  
93      @Execute
94      public HtmlResponse reindexOnly(final ActionForm form) {
95          validate(form, messages -> {}, this::asIndexHtml);
96          verifyToken(this::asIndexHtml);
97          if (startReindex(isCheckboxEnabled(form.replaceAliases), isCheckboxEnabled(form.resetDictionaries), form.numberOfShardsForDoc,
98                  form.autoExpandReplicasForDoc)) {
99              saveInfo(messages -> messages.addSuccessStartedDataUpdate(GLOBAL));
100         }
101         return redirect(getClass());
102     }
103 
104     @Execute
105     public HtmlResponse reloadDocIndex(final ActionForm form) {
106         validate(form, messages -> {}, this::asIndexHtml);
107         verifyToken(this::asIndexHtml);
108         final String docIndex = fessConfig.getIndexDocumentUpdateIndex();
109         fessEsClient
110                 .admin()
111                 .indices()
112                 .prepareClose(docIndex)
113                 .execute(
114                         ActionListener.wrap(
115                                 res -> {
116                                     logger.info("Close " + docIndex);
117                                     fessEsClient
118                                             .admin()
119                                             .indices()
120                                             .prepareOpen(docIndex)
121                                             .execute(
122                                                     ActionListener.wrap(res2 -> logger.info("Open " + docIndex),
123                                                             e -> logger.warn("Failed to open " + docIndex, e)));
124                                 }, e -> logger.warn("Failed to close " + docIndex, e)));
125         saveInfo(messages -> messages.addSuccessStartedDataUpdate(GLOBAL));
126         return redirect(getClass());
127     }
128 
129     @Execute
130     public HtmlResponse clearCrawlerIndex(final ActionForm form) {
131         validate(form, messages -> {}, this::asIndexHtml);
132         verifyToken(this::asIndexHtml);
133         fessEsClient
134                 .admin()
135                 .indices()
136                 .prepareDelete(//
137                         fessConfig.getIndexDocumentCrawlerIndex() + ".queue", //
138                         fessConfig.getIndexDocumentCrawlerIndex() + ".data", //
139                         fessConfig.getIndexDocumentCrawlerIndex() + ".filter")
140                 .execute(
141                         ActionListener.wrap(res -> logger.info("Deleted .crawler indices."),
142                                 e -> logger.warn("Failed to delete .crawler.* indices.", e)));
143         saveInfo(messages -> messages.addSuccessStartedDataUpdate(GLOBAL));
144         return redirect(getClass());
145     }
146 
147     @Execute
148     public ActionResponse downloadLogs(final ActionForm form) {
149         validate(form, messages -> {}, this::asIndexHtml);
150         verifyTokenKeep(this::asIndexHtml);
151 
152         final String diagnosticId = "log" + new SimpleDateFormat("yyyyMMddHHmm").format(ComponentUtil.getSystemHelper().getCurrentTime());
153         return asStream(diagnosticId + ".zip").contentTypeOctetStream().stream(out -> {
154             try (ZipOutputStream zos = new ZipOutputStream(out.stream())) {
155                 writeLogFiles(zos, diagnosticId);
156                 writeSystemProperties(zos, diagnosticId);
157                 writeFessBasicConfig(zos, diagnosticId);
158                 writeFessConfig(zos, diagnosticId);
159                 writeElasticsearchCat(zos, diagnosticId);
160                 writeElasticsearchJson(zos, diagnosticId);
161             }
162         });
163     }
164 
165     protected void writeElasticsearchJson(final ZipOutputStream zos, final String id) {
166         writeElastisearchJsonApi(zos, id, "cluster", "health");
167         writeElastisearchJsonApi(zos, id, "cluster", "state");
168         writeElastisearchJsonApi(zos, id, "cluster", "stats");
169         writeElastisearchJsonApi(zos, id, "cluster", "pending_tasks");
170         writeElastisearchJsonApi(zos, id, "nodes", "stats");
171         writeElastisearchJsonApi(zos, id, "nodes", "_all");
172         writeElastisearchJsonApi(zos, id, "nodes", "usage");
173         writeElastisearchJsonApi(zos, id, "remote", "info");
174         writeElastisearchJsonApi(zos, id, "tasks", "");
175         writeElastisearchJsonApi(zos, id, "nodes", "hot_threads");
176     }
177 
178     protected void writeElastisearchJsonApi(final ZipOutputStream zos, final String id, final String v1, final String v2) {
179         final ZipEntry entry = new ZipEntry(id + "/es_" + v1 + "_" + v2 + ".json");
180         try {
181             zos.putNextEntry(entry);
182             try (CurlResponse response = ComponentUtil.getCurlHelper().get("/_" + v1 + "/" + v2).execute()) {
183                 CopyUtil.copy(response.getContentAsStream(), zos);
184             }
185         } catch (final Exception e) {
186             logger.warn("Failed to access /_" + v1 + "/" + v2, e);
187         }
188     }
189 
190     protected void writeElasticsearchCat(final ZipOutputStream zos, final String id) {
191         Arrays.stream(ES_CAT_NAMES).forEach(name -> {
192             final ZipEntry entry = new ZipEntry(id + "/es_cat_" + name + ".txt");
193             try {
194                 zos.putNextEntry(entry);
195                 try (CurlResponse response = ComponentUtil.getCurlHelper().get("/_cat/" + name).param("v", "").execute()) {
196                     CopyUtil.copy(response.getContentAsStream(), zos);
197                 }
198             } catch (final Exception e) {
199                 logger.warn("Failed to access /_cat/" + name, e);
200             }
201         });
202     }
203 
204     protected void writeFessConfig(final ZipOutputStream zos, final String id) {
205         if (fessConfig instanceof SimpleImpl) {
206             final Properties prop = new Properties();
207             ((SimpleImpl) fessConfig).keySet().stream().forEach(k -> prop.setProperty(k, fessConfig.get(k)));
208 
209             final ZipEntry entry = new ZipEntry(id + "/fess_config.properties");
210             try {
211                 zos.putNextEntry(entry);
212                 prop.store(zos, getHostInfo());
213             } catch (final IOException e) {
214                 logger.warn("Failed to access system.properties.", e);
215             }
216         }
217     }
218 
219     protected void writeFessBasicConfig(final ZipOutputStream zos, final String id) {
220         final ZipEntry entry = new ZipEntry(id + "/fess_basic_config.bulk");
221         try {
222             zos.putNextEntry(entry);
223             try (CurlResponse response =
224                     ComponentUtil.getCurlHelper().get("/.fess_basic_config/_data").param("format", "json")
225                             .param("scroll", fessConfig.getIndexScrollSearchTimeout()).execute()) {
226                 CopyUtil.copy(response.getContentAsStream(), zos);
227             }
228         } catch (final IOException e) {
229             logger.warn("Failed to access system.properties.", e);
230         }
231     }
232 
233     protected void writeSystemProperties(final ZipOutputStream zos, final String id) {
234         final ZipEntry entry = new ZipEntry(id + "/system.properties");
235         try {
236             zos.putNextEntry(entry);
237             ComponentUtil.getSystemProperties().store(zos, getHostInfo());
238         } catch (final IOException e) {
239             logger.warn("Failed to access system.properties.", e);
240         }
241     }
242 
243     protected void writeLogFiles(final ZipOutputStream zos, final String id) {
244         final String logFilePath = systemHelper.getLogFilePath();
245         if (StringUtil.isNotBlank(logFilePath)) {
246             final Path logDirPath = Paths.get(logFilePath);
247             try (Stream<Path> stream = Files.list(logDirPath)) {
248                 stream.filter(entry -> isLogFilename(entry.getFileName().toString())).forEach(filePath -> {
249                     final ZipEntry entry = new ZipEntry(id + "/" + filePath.getFileName().toString());
250                     try {
251                         zos.putNextEntry(entry);
252                         final long len = Files.copy(filePath, zos);
253                         if (logger.isDebugEnabled()) {
254                             logger.debug(filePath.getFileName() + ": " + len);
255                         }
256                     } catch (final IOException e) {
257                         logger.warn("Failed to access " + filePath, e);
258                     }
259                 });
260             } catch (final Exception e) {
261                 logger.warn("Failed to access log files.", e);
262             }
263         }
264     }
265 
266     protected String getHostInfo() {
267         final StringBuilder buf = new StringBuilder();
268         try {
269             final InetAddress ia = InetAddress.getLocalHost();
270             final String hostname = ia.getHostName();
271             if (StringUtil.isNotBlank(hostname)) {
272                 buf.append(hostname);
273             }
274             final String ip = ia.getHostAddress();
275             if (StringUtil.isNotBlank(ip)) {
276                 if (buf.length() > 0) {
277                     buf.append(" : ");
278                 }
279                 buf.append(ip);
280             }
281         } catch (final Exception e) {
282             // ignore
283         }
284         return buf.toString();
285     }
286 
287     protected boolean isLogFilename(final String name) {
288         return name.endsWith(".log") || name.endsWith(".log.gz");
289     }
290 
291     protected boolean startReindex(final boolean replaceAliases, final boolean resetDictionaries, final String numberOfShards,
292             final String autoExpandReplicas) {
293         final String docIndex = "fess";
294         final String fromIndex = fessConfig.getIndexDocumentUpdateIndex();
295         final String toIndex = docIndex + "." + new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
296         if (fessEsClient.createIndex(docIndex, toIndex, numberOfShards, autoExpandReplicas, resetDictionaries)) {
297             fessEsClient.admin().cluster().prepareHealth(toIndex).setWaitForYellowStatus().execute(ActionListener.wrap(response -> {
298                 fessEsClient.addMapping(docIndex, "doc", toIndex);
299                 fessEsClient.reindex(fromIndex, toIndex, replaceAliases);
300                 if (replaceAliases && !fessEsClient.updateAlias(toIndex)) {
301                     logger.warn("Failed to update aliases for " + fromIndex + " and " + toIndex);
302                 }
303             }, e -> logger.warn("Failed to reindex from " + fromIndex + " to " + toIndex, e)));
304             return true;
305         }
306         saveError(messages -> messages.addErrorsFailedToReindex(GLOBAL, fromIndex, toIndex));
307         return false;
308     }
309 
310 }