18b7e2fb7bb2769cf2a6acb869b2449202eba767
[dcaegen2/services.git] /
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DATALAKE
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
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
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=========================================================
19 */
20
21 package org.onap.datalake.feeder.service.db;
22
23 import java.io.IOException;
24 import java.util.List;
25
26 import javax.annotation.PostConstruct;
27 import javax.annotation.PreDestroy;
28
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;
54
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.context.annotation.Scope;
57 import org.springframework.stereotype.Service;
58
59 /**
60  * Elasticsearch Service for table creation, data submission, as well as data pre-processing. 
61  * 
62  * @author Guobiao Mo
63  *
64  */
65 @Service
66 @Scope("prototype")
67 public class ElasticsearchService implements DbStoreService {
68
69         private final Logger log = LoggerFactory.getLogger(this.getClass());
70         
71         private Db elasticsearch;
72
73         @Autowired
74         private ApplicationConfiguration config;
75
76         private RestHighLevelClient client;
77         ActionListener<BulkResponse> listener;
78         
79         public ElasticsearchService(Db db) {
80                 elasticsearch = db;
81         }
82         
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
85         @PostConstruct
86         @Override
87         public void init() {
88                 String elasticsearchHost = elasticsearch.getHost();
89
90                 // Initialize the Connection
91                 client = new RestHighLevelClient(RestClient.builder(new HttpHost(elasticsearchHost, 9200, "http"), new HttpHost(elasticsearchHost, 9201, "http")));
92
93                 log.info("Connected to Elasticsearch Host {}", elasticsearchHost);
94
95                 listener = new ActionListener<BulkResponse>() {
96                         @Override
97                         public void onResponse(BulkResponse bulkResponse) {
98                                 if(bulkResponse.hasFailures()) {
99                                         log.debug(bulkResponse.buildFailureMessage());
100                                 }
101                         }
102
103                         @Override
104                         public void onFailure(Exception e) {
105                                 log.error(e.getMessage());
106                         }
107                 };
108         }
109
110         @PreDestroy
111         public void cleanUp() throws IOException {
112                 config.getShutdownLock().readLock().lock();
113
114                 try {
115                         log.info("cleanUp() closing Elasticsearch client.");
116                         client.close();
117                 } catch (IOException e) {
118                         log.error("client.close() at cleanUp.", e);
119                 } finally {
120                         config.getShutdownLock().readLock().unlock();
121                 }
122         }
123
124         public void ensureTableExist(String topic) throws IOException {
125                 String topicLower = topic.toLowerCase();
126
127                 GetIndexRequest request = new GetIndexRequest(topicLower);
128
129                 boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
130                 if (!exists) {
131                         //TODO submit mapping template
132                         CreateIndexRequest createIndexRequest = new CreateIndexRequest(topicLower);
133                         CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
134                         log.info("{} : created {}", createIndexResponse.index(), createIndexResponse.isAcknowledged());
135                 }
136         }
137
138         //TTL is not supported in Elasticsearch 5.0 and later, what can we do? FIXME
139         @Override
140         public void saveJsons(EffectiveTopic effectiveTopic, List<JSONObject> jsons) {
141                 
142                 BulkRequest request = new BulkRequest();
143
144                 for (JSONObject json : jsons) {
145                         if (effectiveTopic.getTopic().isCorrelateClearedMessage()) {
146                                 boolean found = correlateClearedMessage(effectiveTopic.getTopic(), json);
147                                 if (found) {
148                                         continue;
149                                 }
150                         }                       
151                         
152                         String id = effectiveTopic.getTopic().getMessageId(json); //id can be null
153                         
154                         request.add(new IndexRequest(effectiveTopic.getName().toLowerCase(), config.getElasticsearchType(), id).source(json.toString(), XContentType.JSON));
155                 }
156
157                 log.debug("saving text to effectiveTopic = {}, batch count = {} ", effectiveTopic, jsons.size());
158
159                 if (config.isAsync()) {
160                         client.bulkAsync(request, RequestOptions.DEFAULT, listener);
161                 } else {
162                         try {
163                                 BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
164                                 if(bulkResponse.hasFailures()) {
165                                         log.debug(bulkResponse.buildFailureMessage());
166                                 }
167                         } catch (IOException e) {
168                                 log.error(effectiveTopic.getName(), e);
169                         }
170                 }
171                 
172         }
173         
174         /**
175          *
176          * @param topic
177          * @param json
178          * @return boolean
179          *
180          *         Because of query by id, The search API cannot be used for query. The
181          *         search API can only query all data or based on the fields in the
182          *         source. So use the get API, three parameters: index, type, document
183          *         id
184          */
185         private boolean correlateClearedMessage(Topic topic, JSONObject json) {
186                 boolean found = false;
187                 String eName = null;
188
189                 try {
190                         eName = json.query("/event/commonEventHeader/eventName").toString();
191
192                         if (StringUtils.isNotBlank(eName) && eName.endsWith("Cleared")) {
193
194                                 String name = eName.substring(0, eName.length() - 7);
195                                 String reportingEntityName = json.query("/event/commonEventHeader/reportingEntityName").toString();
196                                 String specificProblem = json.query("/event/faultFields/specificProblem").toString();
197
198                                 String id = String.join("^", name, reportingEntityName, specificProblem);//example: id = "aaaa^cccc^bbbbb"
199                                 String index = topic.getName().toLowerCase();
200
201                                 //get
202                                 GetRequest getRequest = new GetRequest(index, config.getElasticsearchType(), id);
203
204                                 GetResponse getResponse = null;
205                                 try {
206                                         getResponse = client.get(getRequest, RequestOptions.DEFAULT);
207                                         if (getResponse != null) {
208
209                                                 if (getResponse.isExists()) {
210                                                         String sourceAsString = getResponse.getSourceAsString();
211                                                         JSONObject jsonObject = new JSONObject(sourceAsString);
212                                                         jsonObject.getJSONObject("event").getJSONObject("faultFields").put("vfStatus", "closed");
213                                                         String jsonString = jsonObject.toString();
214
215                                                         //update
216                                                         IndexRequest request = new IndexRequest(index, config.getElasticsearchType(), id);
217                                                         request.source(jsonString, XContentType.JSON);
218                                                         IndexResponse indexResponse = null;
219                                                         try {
220                                                                 indexResponse = client.index(request, RequestOptions.DEFAULT);
221                                                                 found = true;
222                                                         } catch (IOException e) {
223                                                                 log.error("save failure");
224                                                         }
225                                                 } else {
226                                                         log.error("The getResponse was not exists");
227                                                 }
228
229                                         } else {
230                                                 log.error("The document for this id was not found");
231                                         }
232
233                                 } catch (ElasticsearchException e) {
234                                         if (e.status() == RestStatus.NOT_FOUND) {
235                                                 log.error("The document for this id was not found");
236                                         }
237                                         if (e.status() == RestStatus.CONFLICT) {
238                                                 log.error("Version conflict");
239                                         }
240                                         log.error("Get document exception", e);
241                                 } catch (IOException e) {
242                                         log.error(topic.getName(), e);
243                                 }
244
245                         }
246
247                 } catch (Exception e) {
248                         log.error("error", e);
249                 }
250
251                 return found;
252         }
253
254 }