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.util;
17  
18  import java.io.File;
19  import java.util.function.Consumer;
20  
21  import org.codelibs.core.exception.ResourceNotFoundRuntimeException;
22  import org.codelibs.core.io.FileUtil;
23  import org.codelibs.curl.CurlResponse;
24  import org.codelibs.fess.mylasta.direction.FessConfig;
25  import org.elasticsearch.action.ActionListener;
26  import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
27  import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
28  import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData;
29  import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
30  import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
31  import org.elasticsearch.action.index.IndexRequest;
32  import org.elasticsearch.action.support.master.AcknowledgedResponse;
33  import org.elasticsearch.client.Client;
34  import org.elasticsearch.client.IndicesAdminClient;
35  import org.elasticsearch.cluster.metadata.MappingMetaData;
36  import org.elasticsearch.common.collect.ImmutableOpenMap;
37  import org.elasticsearch.common.xcontent.XContentType;
38  import org.slf4j.Logger;
39  import org.slf4j.LoggerFactory;
40  
41  public final class UpgradeUtil {
42      private static final Logger logger = LoggerFactory.getLogger(UpgradeUtil.class);
43  
44      private UpgradeUtil() {
45      }
46  
47      public static boolean uploadResource(final String indexConfigPath, final String indexName, final String path) {
48          final String filePath = indexConfigPath + "/" + indexName + "/" + path;
49          try {
50              final String source = FileUtil.readUTF8(filePath);
51              try (CurlResponse response = ComponentUtil.getCurlHelper().post("/_configsync/file").param("path", path).body(source).execute()) {
52                  if (response.getHttpStatusCode() == 200) {
53                      logger.info("Register " + path + " to " + indexName);
54                      return true;
55                  } else {
56                      logger.warn("Invalid request for " + path);
57                  }
58              }
59          } catch (final Exception e) {
60              logger.warn("Failed to register " + filePath, e);
61          }
62          return false;
63      }
64  
65      public static boolean createAlias(final IndicesAdminClient indicesClient, final String indexConfigPath, final String indexName,
66              final String aliasName) {
67          final FessConfig fessConfig = ComponentUtil.getFessConfig();
68          final String aliasConfigPath = indexConfigPath + "/" + indexName + "/alias/" + aliasName + ".json";
69          try {
70              final File aliasConfigFile = org.codelibs.core.io.ResourceUtil.getResourceAsFile(aliasConfigPath);
71              if (aliasConfigFile.exists()) {
72                  final String source = FileUtil.readUTF8(aliasConfigFile);
73                  final AcknowledgedResponse response =
74                          indicesClient.prepareAliases().addAlias(indexName, aliasName, source).execute()
75                                  .actionGet(fessConfig.getIndexIndicesTimeout());
76                  if (response.isAcknowledged()) {
77                      logger.info("Created " + aliasName + " alias for " + indexName);
78                      return true;
79                  } else if (logger.isDebugEnabled()) {
80                      logger.debug("Failed to create " + aliasName + " alias for " + indexName);
81                  }
82              }
83          } catch (final ResourceNotFoundRuntimeException e) {
84              // ignore
85          } catch (final Exception e) {
86              logger.warn(aliasConfigPath + " is not found.", e);
87          }
88          return false;
89      }
90  
91      public static boolean addMapping(final IndicesAdminClient indicesClient, final String index, final String type,
92              final String indexResourcePath) {
93          final FessConfig fessConfig = ComponentUtil.getFessConfig();
94          final GetMappingsResponse getMappingsResponse =
95                  indicesClient.prepareGetMappings(index).execute().actionGet(fessConfig.getIndexIndicesTimeout());
96          final ImmutableOpenMap<String, MappingMetaData> indexMappings = getMappingsResponse.mappings().get(index);
97          if (indexMappings == null || !indexMappings.containsKey(type)) {
98              String source = null;
99              final String mappingFile = indexResourcePath + "/" + type + ".json";
100             try {
101                 source = FileUtil.readUTF8(mappingFile);
102             } catch (final Exception e) {
103                 logger.warn(mappingFile + " is not found.", e);
104             }
105             try {
106                 final AcknowledgedResponse putMappingResponse =
107                         indicesClient.preparePutMapping(index).setSource(source, XContentType.JSON).execute()
108                                 .actionGet(fessConfig.getIndexIndicesTimeout());
109                 if (putMappingResponse.isAcknowledged()) {
110                     logger.info("Created " + index + "/" + type + " mapping.");
111                     return true;
112                 } else {
113                     logger.warn("Failed to create " + index + "/" + type + " mapping.");
114                 }
115                 // TODO bulk
116             } catch (final Exception e) {
117                 logger.warn("Failed to create " + index + "/" + type + " mapping.", e);
118             }
119         }
120         return false;
121     }
122 
123     public static boolean addFieldMapping(final IndicesAdminClient indicesClient, final String index, final String type,
124             final String field, final String source) {
125         final GetFieldMappingsResponse gfmResponse =
126                 indicesClient.prepareGetFieldMappings(index).addTypes(type).setFields(field).execute().actionGet();
127         final FieldMappingMetaData fieldMappings = gfmResponse.fieldMappings(index, type, field);
128         if (fieldMappings == null || fieldMappings.isNull()) {
129             try {
130                 final AcknowledgedResponse pmResponse =
131                         indicesClient.preparePutMapping(index).setSource(source, XContentType.JSON).execute().actionGet();
132                 if (!pmResponse.isAcknowledged()) {
133                     logger.warn("Failed to add " + field + " to " + index + "/" + type);
134                 } else {
135                     return true;
136                 }
137             } catch (final Exception e) {
138                 logger.warn("Failed to add " + field + " to " + index + "/" + type, e);
139             }
140         }
141         return false;
142     }
143 
144     public static boolean putMapping(final IndicesAdminClient indicesClient, final String index, final String source) {
145         return putMapping(indicesClient, index, null, source);
146     }
147 
148     public static boolean putMapping(final IndicesAdminClient indicesClient, final String index, final String type, final String source) {
149         try {
150             final PutMappingRequestBuilder builder = indicesClient.preparePutMapping(index).setSource(source, XContentType.JSON);
151             final AcknowledgedResponse pmResponse = builder.execute().actionGet();
152             if (!pmResponse.isAcknowledged()) {
153                 logger.warn("Failed to update " + index + " settings.");
154             } else {
155                 return true;
156             }
157         } catch (final Exception e) {
158             logger.warn("Failed to update " + index + " settings.", e);
159         }
160 
161         return false;
162     }
163 
164     public static boolean addData(final Client fessEsClient, final String index, final String id, final String source) {
165         try {
166             final IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, XContentType.JSON);
167             fessEsClient.index(indexRequest).actionGet();
168             return true;
169         } catch (final Exception e) {
170             logger.warn("Failed to add " + id + " to " + index, e);
171         }
172         return false;
173     }
174 
175     public static boolean existsIndex(final IndicesAdminClient indicesClient, final String index, final boolean expandWildcardsOpen,
176             final boolean expandWildcardsClosed) {
177         final FessConfig fessConfig = ComponentUtil.getFessConfig();
178         try {
179             final IndicesExistsResponse response =
180                     indicesClient.prepareExists(index).setExpandWildcardsClosed(expandWildcardsClosed)
181                             .setExpandWildcardsOpen(expandWildcardsOpen).execute().actionGet(fessConfig.getIndexSearchTimeout());
182             return response.isExists();
183         } catch (final Exception e) {
184             // ignore
185         }
186         return false;
187     }
188 
189     public static void deleteIndex(final IndicesAdminClient indicesClient, final String index, final Consumer<AcknowledgedResponse> comsumer) {
190         indicesClient.prepareDelete(index).execute(new ActionListener<AcknowledgedResponse>() {
191 
192             @Override
193             public void onResponse(final AcknowledgedResponse response) {
194                 logger.info("Deleted " + index + " index.");
195                 comsumer.accept(response);
196             }
197 
198             @Override
199             public void onFailure(final Exception e) {
200                 logger.warn("Failed to delete " + index + " index.", e);
201             }
202         });
203     }
204 }