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.backup;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.BufferedReader;
21  import java.io.BufferedWriter;
22  import java.io.ByteArrayInputStream;
23  import java.io.ByteArrayOutputStream;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileOutputStream;
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.io.InputStreamReader;
30  import java.io.OutputStream;
31  import java.io.OutputStreamWriter;
32  import java.io.Writer;
33  import java.time.LocalDateTime;
34  import java.time.ZoneId;
35  import java.time.format.DateTimeFormatter;
36  import java.util.Arrays;
37  import java.util.HashMap;
38  import java.util.List;
39  import java.util.Map;
40  import java.util.function.Consumer;
41  import java.util.stream.Collectors;
42  
43  import javax.annotation.Resource;
44  
45  import org.apache.commons.text.StringEscapeUtils;
46  import org.codelibs.core.exception.IORuntimeException;
47  import org.codelibs.core.io.CopyUtil;
48  import org.codelibs.core.lang.StringUtil;
49  import org.codelibs.core.misc.Pair;
50  import org.codelibs.curl.CurlResponse;
51  import org.codelibs.fess.Constants;
52  import org.codelibs.fess.app.web.base.FessAdminAction;
53  import org.codelibs.fess.es.config.exbhv.FileConfigBhv;
54  import org.codelibs.fess.es.config.exbhv.LabelTypeBhv;
55  import org.codelibs.fess.es.config.exbhv.WebConfigBhv;
56  import org.codelibs.fess.es.log.exbhv.ClickLogBhv;
57  import org.codelibs.fess.es.log.exbhv.FavoriteLogBhv;
58  import org.codelibs.fess.es.log.exbhv.SearchLogBhv;
59  import org.codelibs.fess.es.log.exbhv.UserInfoBhv;
60  import org.codelibs.fess.mylasta.direction.FessConfig;
61  import org.codelibs.fess.util.ComponentUtil;
62  import org.codelibs.fess.util.GsaConfigParser;
63  import org.codelibs.fess.util.RenderDataUtil;
64  import org.lastaflute.core.magic.async.AsyncManager;
65  import org.lastaflute.web.Execute;
66  import org.lastaflute.web.response.ActionResponse;
67  import org.lastaflute.web.response.HtmlResponse;
68  import org.lastaflute.web.response.StreamResponse;
69  import org.lastaflute.web.ruts.process.ActionRuntime;
70  import org.lastaflute.web.validation.exception.ValidationErrorException;
71  import org.slf4j.Logger;
72  import org.slf4j.LoggerFactory;
73  import org.xml.sax.InputSource;
74  
75  import com.fasterxml.jackson.core.type.TypeReference;
76  import com.fasterxml.jackson.databind.ObjectMapper;
77  
78  /**
79   * @author shinsuke
80   */
81  public class AdminBackupAction extends FessAdminAction {
82  
83      private static final Logger logger = LoggerFactory.getLogger(AdminBackupAction.class);
84  
85      public static final String NDJSON_EXTENTION = ".ndjson";
86  
87      private static final DateTimeFormatter ISO_8601_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
88  
89      @Resource
90      private AsyncManager asyncManager;
91  
92      @Resource
93      private WebConfigBhv webConfigBhv;
94  
95      @Resource
96      private FileConfigBhv fileConfigBhv;
97  
98      @Resource
99      private LabelTypeBhv labelTypeBhv;
100 
101     @Override
102     protected void setupHtmlData(final ActionRuntime runtime) {
103         super.setupHtmlData(runtime);
104         runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameBackup()));
105     }
106 
107     @Execute
108     public HtmlResponse index() {
109         saveToken();
110         return asListHtml();
111     }
112 
113     @Execute
114     public HtmlResponse upload(final UploadForm form) {
115         validate(form, messages -> {}, () -> asListHtml());
116         verifyToken(() -> asListHtml());
117         final String fileName = form.bulkFile.getFileName();
118         File tempFile = null;
119         try {
120             tempFile = File.createTempFile("fess_restore_", ".tmp");
121             try (final InputStream in = form.bulkFile.getInputStream(); final OutputStream out = new FileOutputStream(tempFile)) {
122                 CopyUtil.copy(in, out);
123             }
124             asyncImport(fileName, tempFile);
125         } catch (final ValidationErrorException e) {
126             throw e;
127         } catch (final Exception e) {
128             logger.warn("Failed to import " + fileName, e);
129         }
130         saveInfo(messages -> messages.addSuccessBulkProcessStarted(GLOBAL));
131         return redirect(getClass()); // no-op
132     }
133 
134     protected void asyncImport(final String fileName, final File tempFile) {
135         final int fileType;
136         if (fileName.startsWith("system") && fileName.endsWith(".properties")) {
137             fileType = 1;
138         } else if (fileName.startsWith("gsa") && fileName.endsWith(".xml")) {
139             fileType = 2;
140         } else if (fileName.endsWith(".bulk")) {
141             fileType = 3;
142         } else {
143             throwValidationError(messages -> messages.addErrorsFileIsNotSupported(GLOBAL, fileName), () -> {
144                 return asListHtml();
145             });
146             return;
147         }
148 
149         asyncManager.async(() -> {
150             if (fileType == 1) {
151                 try (final InputStream in = new FileInputStream(tempFile)) {
152                     ComponentUtil.getSystemProperties().load(in);
153                 } catch (final IOException e) {
154                     logger.warn("Failed to process system.properties file: " + fileName, e);
155                 } finally {
156                     if (tempFile != null && !tempFile.delete()) {
157                         logger.warn("Failed to delete " + tempFile.getAbsolutePath());
158                     }
159                 }
160             } else if (fileType == 2) {
161                 final GsaConfigParser configParser = ComponentUtil.getComponent(GsaConfigParser.class);
162                 try (final InputStream in = new FileInputStream(tempFile)) {
163                     configParser.parse(new InputSource(in));
164                 } catch (final IOException e) {
165                     logger.warn("Failed to process gsa.xml file: " + fileName, e);
166                 } finally {
167                     if (tempFile != null && !tempFile.delete()) {
168                         logger.warn("Failed to delete " + tempFile.getAbsolutePath());
169                     }
170                 }
171                 configParser.getWebConfig().ifPresent(c -> webConfigBhv.insert(c));
172                 configParser.getFileConfig().ifPresent(c -> fileConfigBhv.insert(c));
173                 labelTypeBhv.batchInsert(Arrays.stream(configParser.getLabelTypes()).collect(Collectors.toList()));
174             } else if (fileType == 3) {
175                 final ObjectMapper mapper = new ObjectMapper();
176                 try (CurlResponse response =
177                         ComponentUtil
178                                 .getCurlHelper()
179                                 .post("/_bulk")
180                                 .onConnect(
181                                         (req, con) -> {
182                                             con.setDoOutput(true);
183                                             try (final BufferedReader br =
184                                                     new BufferedReader(new InputStreamReader(new FileInputStream(tempFile)));
185                                                     final BufferedWriter bw =
186                                                             new BufferedWriter(new OutputStreamWriter(con.getOutputStream(),
187                                                                     Constants.CHARSET_UTF_8))) {
188                                                 String line;
189                                                 while ((line = br.readLine()) != null) {
190                                                     if (StringUtil.isNotBlank(line)) {
191                                                         final Map<String, Map<String, String>> dataObj;
192                                                         if (line.contains("_type")) {
193                                                             dataObj = parseObject(mapper, line);
194                                                         } else {
195                                                             dataObj = null;
196                                                         }
197                                                         if (dataObj != null) {
198                                                             final Map<String, String> indexObj = dataObj.get("index");
199                                                             if (indexObj != null && indexObj.containsKey("_type")) {
200                                                                 indexObj.remove("_type");
201                                                                 bw.write(mapper.writeValueAsString(dataObj));
202                                                             } else {
203                                                                 bw.write(line);
204                                                             }
205                                                         } else {
206                                                             bw.write(line);
207                                                         }
208                                                     }
209                                                     bw.write("\n");
210                                                 }
211                                                 bw.flush();
212                                             } catch (IOException e) {
213                                                 throw new IORuntimeException(e);
214                                             }
215                                         }).execute()) {
216                     if (logger.isDebugEnabled()) {
217                         logger.debug("Bulk Response:\n" + response.getContentAsString());
218                     }
219                     systemHelper.reloadConfiguration();
220                 } catch (final Exception e) {
221                     logger.warn("Failed to process bulk file: " + fileName, e);
222                 } finally {
223                     if (tempFile != null && !tempFile.delete()) {
224                         logger.warn("Failed to delete " + tempFile.getAbsolutePath());
225                     }
226                 }
227             }
228         });
229     }
230 
231     private Map<String, Map<String, String>> parseObject(final ObjectMapper mapper, String line) {
232         try {
233             final Map<String, Map<String, String>> dataObj = mapper.readValue(line, new TypeReference<Map<String, Map<String, String>>>() {
234             });
235             return dataObj;
236         } catch (Exception e) {
237             if (logger.isDebugEnabled()) {
238                 logger.debug("Failed to parse " + line, e);
239             }
240             return null;
241         }
242     }
243 
244     @Execute
245     public ActionResponse download(final String id) {
246         if (stream(fessConfig.getIndexBackupAllTargets()).get(stream -> stream.anyMatch(s -> s.equals(id)))) {
247             if (id.equals("system.properties")) {
248                 return asStream(id).contentTypeOctetStream().stream(out -> {
249                     try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
250                         ComponentUtil.getSystemProperties().store(baos, id);
251                         try (final InputStream in = new ByteArrayInputStream(baos.toByteArray())) {
252                             out.write(in);
253                         }
254                     }
255                 });
256             } else if (id.endsWith(NDJSON_EXTENTION)) {
257                 final String name = id.substring(0, id.length() - NDJSON_EXTENTION.length());
258                 if ("search_log".equals(name)) {
259                     return writeNdjsonResponse(id, getSearchLogNdjsonWriteCall());
260                 } else if ("user_info".equals(name)) {
261                     return writeNdjsonResponse(id, getUserInfoNdjsonWriteCall());
262                 } else if ("click_log".equals(name)) {
263                     return writeNdjsonResponse(id, getClickLogNdjsonWriteCall());
264                 } else if ("favorite_log".equals(name)) {
265                     return writeNdjsonResponse(id, getFavoriteLogNdjsonWriteCall());
266                 }
267             } else {
268                 final String index;
269                 final String filename;
270                 if (id.endsWith(".bulk")) {
271                     index = id.substring(0, id.length() - 5);
272                     filename = id;
273                 } else {
274                     index = id;
275                     filename = id + ".bulk";
276                 }
277                 return asStream(filename).contentTypeOctetStream().stream(
278                         out -> {
279                             try (CurlResponse response =
280                                     ComponentUtil.getCurlHelper().get("/" + index + "/_data").param("format", "json")
281                                             .param("scroll", fessConfig.getIndexScrollSearchTimeout()).execute()) {
282                                 out.write(response.getContentAsStream());
283                             }
284                         });
285             }
286         }
287         throwValidationError(messages -> messages.addErrorsCouldNotFindBackupIndex(GLOBAL), () -> {
288             return asListHtml();
289         });
290         return redirect(getClass()); // no-op
291     }
292 
293     private StreamResponse writeNdjsonResponse(final String id, final Consumer<Writer> writeCall) {
294         return asStream(id)//
295                 .header("Pragma", "no-cache")//
296                 .header("Cache-Control", "no-cache")//
297                 .header("Expires", "Thu, 01 Dec 1994 16:00:00 GMT")//
298                 .header("Content-Type", "application/x-ndjson")//
299                 .stream(out -> {
300                     try (final Writer writer = new BufferedWriter(new OutputStreamWriter(out.stream(), Constants.CHARSET_UTF_8))) {
301                         writeCall.accept(writer);
302                         writer.flush();
303                     } catch (final Exception e) {
304                         logger.warn("Failed to write " + id + " to response.", e);
305                     }
306                 });
307     }
308 
309     private static StringBuilder appendJson(final String field, final Object value, final StringBuilder buf) {
310         buf.append('"').append(StringEscapeUtils.escapeJson(field)).append('"').append(':');
311         if (value == null) {
312             buf.append("null");
313         } else if (value instanceof LocalDateTime) {
314             final String format =
315                     ((LocalDateTime) value).atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC")).format(ISO_8601_FORMATTER);
316             buf.append('"').append(StringEscapeUtils.escapeJson(format)).append('"');
317         } else if (value instanceof String[]) {
318             final String json =
319                     Arrays.stream((String[]) value).map(s -> "\"" + StringEscapeUtils.escapeJson(s) + "\"")
320                             .collect(Collectors.joining(","));
321             buf.append('[').append(json).append(']');
322         } else if (value instanceof List) {
323             final String json =
324                     ((List<?>) value).stream().map(s -> "\"" + StringEscapeUtils.escapeJson(s.toString()) + "\"")
325                             .collect(Collectors.joining(","));
326             buf.append('[').append(json).append(']');
327         } else if (value instanceof Map) {
328             buf.append('{');
329             final String json = ((Map<?, ?>) value).entrySet().stream().map(e -> {
330                 final StringBuilder tempBuf = new StringBuilder();
331                 appendJson(e.getKey().toString(), e.getValue(), tempBuf);
332                 return tempBuf.toString();
333             }).collect(Collectors.joining(","));
334             buf.append(json);
335             buf.append('}');
336         } else if (value instanceof Long || value instanceof Integer) {
337             buf.append(((Number) value).longValue());
338         } else if (value instanceof Number) {
339             buf.append(((Number) value).doubleValue());
340         } else {
341             buf.append('"').append(StringEscapeUtils.escapeJson(value.toString())).append('"');
342         }
343         return buf;
344     }
345 
346     public static Consumer<Writer> getSearchLogNdjsonWriteCall() {
347         return writer -> {
348             final SearchLogBhv bhv = ComponentUtil.getComponent(SearchLogBhv.class);
349             bhv.selectCursor(
350                     cb -> {
351                         cb.query().matchAll();
352                         cb.query().addOrderBy_RequestedAt_Asc();
353                     },
354                     entity -> {
355                         final StringBuilder buf = new StringBuilder();
356                         buf.append('{');
357                         appendJson("id", entity.getId(), buf).append(',');
358                         appendJson("query-id", entity.getQueryId(), buf).append(',');
359                         appendJson("user-info-id", entity.getUserInfoId(), buf).append(',');
360                         appendJson("user-session-id", entity.getUserSessionId(), buf).append(',');
361                         appendJson("user", entity.getUser(), buf).append(',');
362                         appendJson("search-word", entity.getSearchWord(), buf).append(',');
363                         appendJson("hit-count", entity.getHitCount(), buf).append(',');
364                         appendJson("query-page-size", entity.getQueryPageSize(), buf).append(',');
365                         appendJson("query-offset", entity.getQueryOffset(), buf).append(',');
366                         appendJson("referer", entity.getReferer(), buf).append(',');
367                         appendJson("languages", entity.getLanguages(), buf).append(',');
368                         appendJson("roles", entity.getRoles(), buf).append(',');
369                         appendJson("user-agent", entity.getUserAgent(), buf).append(',');
370                         appendJson("client-ip", entity.getClientIp(), buf).append(',');
371                         appendJson("access-type", entity.getAccessType(), buf).append(',');
372                         appendJson("query-time", entity.getQueryTime(), buf).append(',');
373                         appendJson("response-time", entity.getResponseTime(), buf).append(',');
374                         appendJson("requested-at", entity.getRequestedAt(), buf).append(',');
375                         final Map<String, List<String>> searchFieldMap =
376                                 entity.getSearchFieldLogList()
377                                         .stream()
378                                         .collect(
379                                                 Collectors.groupingBy(Pair::getFirst,
380                                                         Collectors.mapping(Pair::getSecond, Collectors.toList())));
381                         appendJson("search-field", searchFieldMap, buf);
382                         buf.append('}');
383                         buf.append('\n');
384                         try {
385                             writer.write(buf.toString());
386                         } catch (final IOException e) {
387                             throw new IORuntimeException(e);
388                         }
389                     });
390         };
391     }
392 
393     public static Consumer<Writer> getUserInfoNdjsonWriteCall() {
394         return writer -> {
395             final UserInfoBhv bhv = ComponentUtil.getComponent(UserInfoBhv.class);
396             bhv.selectCursor(cb -> {
397                 cb.query().matchAll();
398                 cb.query().addOrderBy_CreatedAt_Asc();
399             }, entity -> {
400                 final StringBuilder buf = new StringBuilder();
401                 buf.append('{');
402                 appendJson("id", entity.getId(), buf).append(',');
403                 appendJson("created-at", entity.getCreatedAt(), buf).append(',');
404                 appendJson("updated-at", entity.getUpdatedAt(), buf);
405                 buf.append('}');
406                 buf.append('\n');
407                 try {
408                     writer.write(buf.toString());
409                 } catch (final IOException e) {
410                     throw new IORuntimeException(e);
411                 }
412             });
413         };
414     }
415 
416     public static Consumer<Writer> getFavoriteLogNdjsonWriteCall() {
417         return writer -> {
418             final FavoriteLogBhv bhv = ComponentUtil.getComponent(FavoriteLogBhv.class);
419             bhv.selectCursor(cb -> {
420                 cb.query().matchAll();
421                 cb.query().addOrderBy_CreatedAt_Asc();
422             }, entity -> {
423                 final StringBuilder buf = new StringBuilder();
424                 buf.append('{');
425                 appendJson("id", entity.getId(), buf).append(',');
426                 appendJson("created-at", entity.getCreatedAt(), buf).append(',');
427                 appendJson("query-id", entity.getQueryId(), buf).append(',');
428                 appendJson("user-info-id", entity.getUserInfoId(), buf).append(',');
429                 appendJson("doc-id", entity.getDocId(), buf).append(',');
430                 appendJson("url", entity.getUrl(), buf);
431                 buf.append('}');
432                 buf.append('\n');
433                 try {
434                     writer.write(buf.toString());
435                 } catch (final IOException e) {
436                     throw new IORuntimeException(e);
437                 }
438             });
439         };
440     }
441 
442     public static Consumer<Writer> getClickLogNdjsonWriteCall() {
443         return writer -> {
444             final ClickLogBhv bhv = ComponentUtil.getComponent(ClickLogBhv.class);
445             bhv.selectCursor(cb -> {
446                 cb.query().matchAll();
447                 cb.query().addOrderBy_RequestedAt_Asc();
448             }, entity -> {
449                 final StringBuilder buf = new StringBuilder();
450                 buf.append('{');
451                 appendJson("id", entity.getId(), buf).append(',');
452                 appendJson("query-id", entity.getQueryId(), buf).append(',');
453                 appendJson("user-session-id", entity.getUserSessionId(), buf).append(',');
454                 appendJson("doc-id", entity.getDocId(), buf).append(',');
455                 appendJson("url", entity.getUrl(), buf).append(',');
456                 appendJson("order", entity.getOrder(), buf).append(',');
457                 appendJson("query-requested-at", entity.getQueryRequestedAt(), buf).append(',');
458                 appendJson("requested-at", entity.getRequestedAt(), buf);
459                 buf.append('}');
460                 buf.append('\n');
461                 try {
462                     writer.write(buf.toString());
463                 } catch (final IOException e) {
464                     throw new IORuntimeException(e);
465                 }
466             });
467         };
468     }
469 
470     public static List<Map<String, String>> getBackupItems() {
471         final FessConfig fessConfig = ComponentUtil.getFessConfig();
472         return stream(fessConfig.getIndexBackupAllTargets()).get(stream -> stream.map(name -> {
473             final Map<String, String> map = new HashMap<>();
474             map.put("id", name);
475             map.put("name", name);
476             return map;
477         }).collect(Collectors.toList()));
478     }
479 
480     private HtmlResponse asListHtml() {
481         return asHtml(path_AdminBackup_AdminBackupJsp).useForm(UploadForm.class).renderWith(
482                 data -> RenderDataUtil.register(data, "backupItems", getBackupItems()));
483     }
484 
485 }