2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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=========================================================
20 package org.openecomp.policy.pap.xacml.rest.elk.client;
22 import java.io.IOException;
24 import java.util.Map.Entry;
26 import org.elasticsearch.index.query.QueryBuilders;
27 import org.elasticsearch.index.query.QueryStringQueryBuilder;
28 import org.elasticsearch.search.builder.SearchSourceBuilder;
29 import org.json.JSONObject;
30 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
31 import org.openecomp.policy.common.logging.flexlogger.Logger;
32 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
33 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
35 import io.searchbox.action.Action;
36 import io.searchbox.client.JestClient;
37 import io.searchbox.client.JestClientFactory;
38 import io.searchbox.client.JestResult;
39 import io.searchbox.client.config.HttpClientConfig;
40 import io.searchbox.core.Delete;
41 import io.searchbox.core.Index;
42 import io.searchbox.core.Search;
43 import io.searchbox.core.Search.Builder;
44 import io.searchbox.indices.IndicesExists;
45 import io.searchbox.indices.type.TypeExist;
46 import io.searchbox.params.Parameters;
48 public class ElkConnectorImpl implements ElkConnector{
50 private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class);
52 protected final JestClientFactory jestFactory = new JestClientFactory();
53 protected final JestClient jestClient;
54 protected static int QUERY_MAXRECORDS = 1000;
56 public ElkConnectorImpl() {
57 if (LOGGER.isDebugEnabled()){
58 LOGGER.debug("ENTER: -");
60 HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
61 jestFactory.setHttpClientConfig(jestClientConfig);
62 jestClient = jestFactory.getObject();
65 protected boolean isType(PolicyIndexType type) throws IOException {
66 if (LOGGER.isDebugEnabled()){
67 LOGGER.debug("ENTER: -");
71 Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
72 JestResult result = jestClient.execute(typeQuery);
74 if (LOGGER.isInfoEnabled()) {
75 LOGGER.info("JSON:" + result.getJsonString());
76 LOGGER.info("ERROR:" + result.getErrorMessage());
77 LOGGER.info("PATH:" + result.getPathToResult());
78 LOGGER.info(result.getJsonObject());
80 return result.isSucceeded();
81 } catch (IOException e) {
82 LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e);
87 protected boolean isIndex() throws IOException {
89 Action<JestResult> indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build();
91 JestResult result = jestClient.execute(indexQuery);
92 if (LOGGER.isInfoEnabled()) {
93 LOGGER.info("JSON:" + result.getJsonString());
94 LOGGER.info("ERROR:" + result.getErrorMessage());
95 LOGGER.info("PATH:" + result.getPathToResult());
96 LOGGER.info(result.getJsonObject());
98 return result.isSucceeded();
99 } catch (IOException e) {
100 LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e);
106 public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException {
107 if (LOGGER.isTraceEnabled()){
108 LOGGER.trace("ENTER: " + text);
111 if (text == null || text.isEmpty()) {
112 throw new IllegalArgumentException("No search string provided");
115 QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*");
116 SearchSourceBuilder searchSourceBuilder =
117 new SearchSourceBuilder().query(mQ);
119 Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).
120 addIndex(ELK_INDEX_POLICY).
121 setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS);
123 if (type == null || type == PolicyIndexType.all) {
124 for (PolicyIndexType pT: PolicyIndexType.values()) {
125 if (pT != PolicyIndexType.all) {
126 searchBuilder.addType(pT.toString());
130 searchBuilder.addType(type.toString());
133 Search search = searchBuilder.build();
136 result = jestClient.execute(search);
137 } catch (IOException ioe) {
138 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" +
139 search + ": " + ioe.getMessage(), ioe);
140 throw new IllegalStateException(ioe);
143 if (result.isSucceeded()) {
144 if (LOGGER.isInfoEnabled()){
145 LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " +
146 result.getPathToResult() + ":" + System.lineSeparator() +
147 result.getJsonString());
150 /* Unsuccessful search */
151 if (LOGGER.isWarnEnabled()){
152 LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
153 result.getResponseCode() + ": " +
154 search.getURI() + ":" +
155 result.getPathToResult() + ":" +
156 result.getJsonString() + ":" +
157 result.getErrorMessage());
160 String errorMessage = result.getErrorMessage();
161 if (errorMessage != null && !errorMessage.isEmpty()) {
162 String xMessage = errorMessage;
163 if (errorMessage.contains("TokenMgrError")) {
164 int indexError = errorMessage.lastIndexOf("TokenMgrError");
165 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
166 } else if (errorMessage.contains("QueryParsingException")) {
167 int indexError = errorMessage.lastIndexOf("QueryParsingException");
168 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
169 } else if (errorMessage.contains("JsonParseException")) {
170 int indexError = errorMessage.lastIndexOf("JsonParseException");
171 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
172 } else if (errorMessage.contains("Parse Failure")) {
173 int indexError = errorMessage.lastIndexOf("Parse Failure");
174 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
175 } else if (errorMessage.contains("SearchParseException")) {
176 int indexError = errorMessage.lastIndexOf("SearchParseException");
177 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
179 xMessage = result.getErrorMessage();
181 throw new IllegalStateException(xMessage);
190 public JestResult search(PolicyIndexType type, String text,
191 Map<String, String> filter_s)
192 throws IllegalStateException, IllegalArgumentException {
193 if (LOGGER.isTraceEnabled()){
194 LOGGER.trace("ENTER: " + text);
197 if (filter_s == null || filter_s.size() == 0) {
198 return search(type, text);
201 String matches_s = "";
203 " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" +
208 String match_params = "";
209 for(Entry<String, String> entry : filter_s.entrySet()){
210 String key = entry.getKey();
211 String value = entry.getValue();
212 if(filter_s.size() == 1){
213 match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }";
215 match_params = match_params + "match\" : { \""+key+"\" : \""+value+"\" } ,";
218 if(match_params.endsWith(",")){
219 match_params = match_params.substring(0, match_params.length()-1);
222 matches_s = matches_s + "{\n" + match_params + "\n}" ;
224 boolean query = false;
225 String query_String = "";
228 query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}";
232 matches_s = matches_s + "," + query_String + "]\n}\n}\n}";
234 matches_s = matches_s + "]\n}\n}\n}";
237 Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY);
239 if (type == null || type == PolicyIndexType.all) {
240 for (PolicyIndexType pT: PolicyIndexType.values()) {
241 if (pT != PolicyIndexType.all) {
242 searchBuilder.addType(pT.toString());
246 searchBuilder.addType(type.toString());
249 Search search = searchBuilder.build();
253 result = jestClient.execute(search);
254 } catch (IOException ioe) {
255 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" +
256 search + ": " + ioe.getMessage(), ioe);
257 throw new IllegalStateException(ioe);
260 if (result.isSucceeded()) {
261 if (LOGGER.isInfoEnabled()){
262 LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " +
263 result.getPathToResult() + ":" + System.lineSeparator() +
264 result.getJsonString());
267 /* Unsuccessful search */
268 if (LOGGER.isWarnEnabled()){
269 LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" +
270 result.getResponseCode() + ": " +
271 search.getURI() + ":" +
272 result.getPathToResult() + ":" +
273 result.getJsonString() + ":" +
274 result.getErrorMessage());
277 String errorMessage = result.getErrorMessage();
278 if (errorMessage != null && !errorMessage.isEmpty()) {
279 String xMessage = errorMessage;
280 if (errorMessage.contains("TokenMgrError")) {
281 int indexError = errorMessage.lastIndexOf("TokenMgrError");
282 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
283 } else if (errorMessage.contains("QueryParsingException")) {
284 int indexError = errorMessage.lastIndexOf("QueryParsingException");
285 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
286 } else if (errorMessage.contains("JsonParseException")) {
287 int indexError = errorMessage.lastIndexOf("JsonParseException");
288 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
289 } else if (errorMessage.contains("Parse Failure")) {
290 int indexError = errorMessage.lastIndexOf("Parse Failure");
291 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
292 } else if (errorMessage.contains("SearchParseException")) {
293 int indexError = errorMessage.lastIndexOf("SearchParseException");
294 xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
296 xMessage = result.getErrorMessage();
298 throw new IllegalStateException(xMessage);
305 public boolean put(PolicyRestAdapter policyData)
306 throws IOException, IllegalStateException {
307 if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER");
309 PolicyIndexType indexType;
311 String policyName = policyData.getNewFileName();
312 if(policyName.contains("Config_")){
313 policyName = policyName.replace(".Config_", ":Config_");
314 }else if(policyName.contains("Action_")){
315 policyName = policyName.replace(".Action_", ":Action_");
316 }else if(policyName.contains("Decision_")){
317 policyName = policyName.replace(".Decision_", ":Decision_");
320 String[] splitPolicyName = policyName.split(":");
321 indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
322 } catch (IllegalArgumentException e) {
323 throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage());
325 PolicyElasticData elasticData = new PolicyElasticData(policyData);
326 JSONObject jsonObj = new JSONObject(elasticData);
327 Index elkPut = new Index.Builder(jsonObj.toString()).
328 index(ELK_INDEX_POLICY).
329 type(indexType.name()).
330 id(elasticData.getPolicyName()).
334 JestResult result = jestClient.execute(elkPut);
336 if (result.isSucceeded()) {
337 if (LOGGER.isInfoEnabled())
338 LOGGER.info("OK: PUT operation of " + "->" + ": " +
339 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
340 result.getPathToResult() + "]" + System.lineSeparator() +
341 result.getJsonString());
343 if (LOGGER.isWarnEnabled())
344 LOGGER.warn("FAILURE: PUT operation of "+ "->" + ": " +
345 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
346 result.getPathToResult() + "]" + System.lineSeparator() +
347 result.getJsonString());
351 return result.isSucceeded();
355 public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException {
356 PolicyIndexType indexType = null;
359 String policyName = policyData.getNewFileName();
360 if(policyName.contains("Config_")){
361 policyName = policyName.replace(".Config_", ":Config_");
362 }else if(policyName.contains("Action_")){
363 policyName = policyName.replace(".Action_", ":Action_");
364 }else if(policyName.contains("Decision_")){
365 policyName = policyName.replace(".Decision_", ":Decision_");
368 String[] splitPolicyName = policyName.split(":");
369 indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]);
370 if (!isType(indexType)) {
371 throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY +
372 " Type: " + indexType +
373 " is not configured");
375 PolicyElasticData elasticData = new PolicyElasticData(policyData);
376 Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY).
377 type(indexType.name()).build();
378 result = jestClient.execute(deleteRequest);
379 } catch (IllegalArgumentException | IOException e) {
380 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" +
381 indexType + ": null" + ":" + policyData.getNewFileName() + ": " +
383 throw new IllegalStateException(e);
386 if (result.isSucceeded()) {
387 if (LOGGER.isInfoEnabled())
388 LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
389 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
390 result.getPathToResult() + "]" + System.lineSeparator() +
391 result.getJsonString());
393 if (LOGGER.isWarnEnabled())
394 LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " +
395 "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" +
396 result.getPathToResult() + "]" + System.lineSeparator() +
397 result.getJsonString());
400 return result.isSucceeded();
404 public boolean update(PolicyRestAdapter policyData) throws IllegalStateException {
405 if (LOGGER.isDebugEnabled()){
406 LOGGER.debug("ENTER");
409 boolean success = put(policyData);
411 } catch (Exception e) {
412 LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e);
413 throw new IllegalStateException(e);