2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright 2019 China Mobile
6 *=================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.datalake.feeder.service.db;
23 import java.io.IOException;
24 import java.util.List;
26 import javax.annotation.PostConstruct;
27 import javax.annotation.PreDestroy;
29 import org.apache.commons.lang3.StringUtils;
30 import org.apache.http.HttpHost;
31 import org.elasticsearch.ElasticsearchException;
32 import org.elasticsearch.action.ActionListener;
33 import org.elasticsearch.action.get.GetRequest;
34 import org.elasticsearch.action.get.GetResponse;
35 import org.elasticsearch.action.index.IndexResponse;
36 import org.elasticsearch.client.indices.CreateIndexRequest;
37 import org.elasticsearch.client.indices.CreateIndexResponse;
38 import org.elasticsearch.client.indices.GetIndexRequest;
39 import org.elasticsearch.action.bulk.BulkRequest;
40 import org.elasticsearch.action.bulk.BulkResponse;
41 import org.elasticsearch.action.index.IndexRequest;
42 import org.elasticsearch.client.RequestOptions;
43 import org.elasticsearch.client.RestClient;
44 import org.elasticsearch.client.RestHighLevelClient;
45 import org.elasticsearch.common.xcontent.XContentType;
46 import org.elasticsearch.rest.RestStatus;
47 import org.json.JSONObject;
48 import org.onap.datalake.feeder.config.ApplicationConfiguration;
49 import org.onap.datalake.feeder.domain.Db;
50 import org.onap.datalake.feeder.domain.EffectiveTopic;
51 import org.onap.datalake.feeder.domain.Topic;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.context.annotation.Scope;
57 import org.springframework.stereotype.Service;
60 * Elasticsearch Service for table creation, data submission, as well as data pre-processing.
67 public class ElasticsearchService implements DbStoreService {
69 private final Logger log = LoggerFactory.getLogger(this.getClass());
71 private Db elasticsearch;
74 private ApplicationConfiguration config;
76 private RestHighLevelClient client;
77 ActionListener<BulkResponse> listener;
79 public ElasticsearchService(Db db) {
83 //ES Encrypted communication https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_encrypted_communication.html#_encrypted_communication
84 //Basic authentication https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_basic_authentication.html
87 String elasticsearchHost = elasticsearch.getHost();
89 // Initialize the Connection
90 client = new RestHighLevelClient(RestClient.builder(new HttpHost(elasticsearchHost, 9200, "http"), new HttpHost(elasticsearchHost, 9201, "http")));
92 log.info("Connected to Elasticsearch Host {}", elasticsearchHost);
94 listener = new ActionListener<BulkResponse>() {
96 public void onResponse(BulkResponse bulkResponse) {
97 if(bulkResponse.hasFailures()) {
98 log.debug(bulkResponse.buildFailureMessage());
103 public void onFailure(Exception e) {
104 log.error(e.getMessage());
110 public void cleanUp() throws IOException {
111 config.getShutdownLock().readLock().lock();
114 log.info("cleanUp() closing Elasticsearch client.");
116 } catch (IOException e) {
117 log.error("client.close() at cleanUp.", e);
119 config.getShutdownLock().readLock().unlock();
123 public void ensureTableExist(String topic) throws IOException {
124 String topicLower = topic.toLowerCase();
126 GetIndexRequest request = new GetIndexRequest(topicLower);
128 boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
130 //TODO submit mapping template
131 CreateIndexRequest createIndexRequest = new CreateIndexRequest(topicLower);
132 CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
133 log.info("{} : created {}", createIndexResponse.index(), createIndexResponse.isAcknowledged());
137 //TTL is not supported in Elasticsearch 5.0 and later, what can we do? FIXME
139 public void saveJsons(EffectiveTopic effectiveTopic, List<JSONObject> jsons) {
141 BulkRequest request = new BulkRequest();
143 for (JSONObject json : jsons) {
144 if (effectiveTopic.getTopic().isCorrelateClearedMessage()) {
145 boolean found = correlateClearedMessage(effectiveTopic.getTopic(), json);
151 String id = effectiveTopic.getTopic().getMessageId(json); //id can be null
153 request.add(new IndexRequest(effectiveTopic.getName().toLowerCase(), config.getElasticsearchType(), id).source(json.toString(), XContentType.JSON));
156 log.debug("saving text to effectiveTopic = {}, batch count = {} ", effectiveTopic, jsons.size());
158 if (config.isAsync()) {
159 client.bulkAsync(request, RequestOptions.DEFAULT, listener);
162 BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
163 if(bulkResponse.hasFailures()) {
164 log.debug(bulkResponse.buildFailureMessage());
166 } catch (IOException e) {
167 log.error(effectiveTopic.getName(), e);
179 * Because of query by id, The search API cannot be used for query. The
180 * search API can only query all data or based on the fields in the
181 * source. So use the get API, three parameters: index, type, document
184 private boolean correlateClearedMessage(Topic topic, JSONObject json) {
185 boolean found = false;
189 eName = json.query("/event/commonEventHeader/eventName").toString();
191 if (StringUtils.isNotBlank(eName) && eName.endsWith("Cleared")) {
193 String name = eName.substring(0, eName.length() - 7);
194 String reportingEntityName = json.query("/event/commonEventHeader/reportingEntityName").toString();
195 String specificProblem = json.query("/event/faultFields/specificProblem").toString();
197 String id = String.join("^", name, reportingEntityName, specificProblem);//example: id = "aaaa^cccc^bbbbb"
198 String index = topic.getName().toLowerCase();
201 GetRequest getRequest = new GetRequest(index, config.getElasticsearchType(), id);
203 GetResponse getResponse = null;
205 getResponse = client.get(getRequest, RequestOptions.DEFAULT);
206 if (getResponse != null) {
208 if (getResponse.isExists()) {
209 String sourceAsString = getResponse.getSourceAsString();
210 JSONObject jsonObject = new JSONObject(sourceAsString);
211 jsonObject.getJSONObject("event").getJSONObject("faultFields").put("vfStatus", "closed");
212 String jsonString = jsonObject.toString();
215 IndexRequest request = new IndexRequest(index, config.getElasticsearchType(), id);
216 request.source(jsonString, XContentType.JSON);
217 IndexResponse indexResponse = null;
219 indexResponse = client.index(request, RequestOptions.DEFAULT);
221 } catch (IOException e) {
222 log.error("save failure");
225 log.error("The getResponse was not exists");
229 log.error("The document for this id was not found");
232 } catch (ElasticsearchException e) {
233 if (e.status() == RestStatus.NOT_FOUND) {
234 log.error("The document for this id was not found");
236 if (e.status() == RestStatus.CONFLICT) {
237 log.error("Version conflict");
239 log.error("Get document exception", e);
240 } catch (IOException e) {
241 log.error(topic.getName(), e);
246 } catch (Exception e) {
247 log.error("error", e);