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