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;
24 import java.io.PrintWriter;
25 import java.nio.file.Path;
26 import java.security.KeyManagementException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
33 import javax.net.ssl.HostnameVerifier;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.SSLSession;
37 import javax.net.ssl.TrustManager;
38 import javax.net.ssl.X509TrustManager;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
42 import org.json.JSONObject;
43 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
44 import org.openecomp.policy.common.logging.flexlogger.Logger;
45 import org.openecomp.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
46 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
47 import org.openecomp.policy.rest.dao.CommonClassDao;
48 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
49 import org.openecomp.policy.rest.jpa.Attribute;
50 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
51 import org.openecomp.policy.rest.jpa.ClosedLoopD2Services;
52 import org.openecomp.policy.rest.jpa.ClosedLoopSite;
53 import org.openecomp.policy.rest.jpa.DCAEuuid;
54 import org.openecomp.policy.rest.jpa.DecisionSettings;
55 import org.openecomp.policy.rest.jpa.DescriptiveScope;
56 import org.openecomp.policy.rest.jpa.EcompName;
57 import org.openecomp.policy.rest.jpa.EnforcingType;
58 import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
59 import org.openecomp.policy.rest.jpa.MicroServiceLocation;
60 import org.openecomp.policy.rest.jpa.MicroServiceModels;
61 import org.openecomp.policy.rest.jpa.PEPOptions;
62 import org.openecomp.policy.rest.jpa.RiskType;
63 import org.openecomp.policy.rest.jpa.SafePolicyWarning;
64 import org.openecomp.policy.rest.jpa.TermList;
65 import org.openecomp.policy.rest.jpa.VNFType;
66 import org.openecomp.policy.rest.jpa.VSCLAction;
67 import org.openecomp.policy.rest.jpa.VarbindDictionary;
68 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
69 import org.springframework.stereotype.Controller;
70 import org.springframework.web.bind.annotation.RequestMapping;
71 import org.springframework.web.servlet.ModelAndView;
73 import com.fasterxml.jackson.databind.DeserializationFeature;
74 import com.fasterxml.jackson.databind.JsonNode;
75 import com.fasterxml.jackson.databind.ObjectMapper;
78 @RequestMapping({"/"})
79 public class PolicyElasticSearchController{
81 private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class);
82 private volatile HashMap<Path, String> filteredPolicies = new HashMap<Path, String>();
83 private List<JSONObject> policyNames = null;
86 attribute, ecompName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, enforcer, fwTerm, msDCAEUUID, msConfigName, msLocation, msModels,
87 psGroupPolicy, safeRisk, safePolicyWarning
90 public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
91 private static final long serialVersionUID = 1L;
93 //For AND and OR logical connector AND=0 and OR=1
94 private int connectorSelected;
96 public static CommonClassDao commonClassDao;
98 public PolicyElasticSearchController(CommonClassDao commonClassDao) {
99 PolicyElasticSearchController.commonClassDao = commonClassDao;
102 public PolicyElasticSearchController() {}
104 public static void TurnOffCertsCheck() {
106 // Create a trust manager that does not validate certificate chains
107 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
108 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
112 public void checkClientTrusted(X509Certificate[] certs,
116 public void checkServerTrusted(X509Certificate[] certs,
121 // Install all-trusting trust manager
124 ctx = SSLContext.getInstance("SSL");
125 ctx.init(null, trustAllCerts, new java.security.SecureRandom());
126 HttpsURLConnection.setDefaultSSLSocketFactory(ctx
127 .getSocketFactory());
128 } catch (NoSuchAlgorithmException | KeyManagementException e) {
129 LOGGER.error("SSL Security Error: " + e);
132 // Create all-trusting host name verifier
133 HostnameVerifier allHostsValid = new HostnameVerifier() {
134 public boolean verify(String hostname, SSLSession session) {
139 // Install the all-trusting host verifier
140 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
143 protected void clSearchBody(String clPolicyType, String bodyField, String bodyValue,
144 ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) {
145 if (LOGGER.isDebugEnabled())
146 LOGGER.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue);
148 final ArrayList<String> clBodyField_s = new ArrayList<String>();
149 final ArrayList<String> clBodyValue_s = new ArrayList<String>();
151 if (clPolicyType == null || clPolicyType.isEmpty()) {
152 clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField);
153 clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField);
154 clBodyValue_s.add(bodyValue);
156 clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField);
157 clBodyValue_s.add(bodyValue);
159 filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s));
162 protected void clSearchFilter(String clType, String clField, String clValue,
163 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) {
164 if (LOGGER.isDebugEnabled())
165 LOGGER.debug("ENTER: " + clType + ":" + clField + ":" + clValue);
167 ArrayList<String> clSearchField_s = new ArrayList<String>();
168 clSearchField_s.add("Policy.Body." + clType + "_Body." + clField);
170 ArrayList<String> clSearchValue_s = new ArrayList<String>();
171 clSearchValue_s.add(clValue);
173 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s));
176 public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
177 if (type == null || type.isEmpty())
178 return PolicyIndexType.all;
180 return PolicyIndexType.valueOf(type);
183 public boolean updateElk(PolicyRestAdapter policyData) {
184 boolean success = true;
186 success = ElkConnector.singleton.update(policyData);
188 if (LOGGER.isWarnEnabled()) {
189 LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName());
192 if (LOGGER.isInfoEnabled()) {
193 LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName());
196 } catch (Exception e) {
197 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
203 public boolean deleteElk(PolicyRestAdapter policyData) {
204 boolean success = true;
206 success = ElkConnector.singleton.delete(policyData);
208 if (LOGGER.isWarnEnabled()) {
209 LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName());
212 if (LOGGER.isInfoEnabled()) {
213 LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName());
216 } catch (Exception e) {
217 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e);
223 @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
224 public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
226 ObjectMapper mapper = new ObjectMapper();
227 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
228 JsonNode root = mapper.readTree(request.getReader());
229 String dictionaryType = root.get("type").textValue();
230 Mode mode = Mode.valueOf(dictionaryType);
232 @SuppressWarnings("unused")
236 Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
237 value = attributedata.getXacmlId();
238 msg = searchElkDatabase("pholder",value);
241 EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class);
242 value = ecompName.getEcompName();
243 msg = searchElkDatabase("pholder",value);
246 ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
247 value = actionPolicyDict.getAttributeName();
248 msg = searchElkDatabase("pholder",value);
251 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
252 value = bRMSParamTemplate.getRuleName();
253 msg = searchElkDatabase("BRMSParamTemplate AND " + value);
256 PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class);
257 value = pEPOptions.getPepName();
258 msg = searchElkDatabase("pepName",value);
261 ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
262 value = closedLoopSite.getSiteName();
263 msg = searchElkDatabase("siteNames",value);
266 ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
267 value = closedLoopD2Services.getServiceName();
268 msg = searchElkDatabase("d2Services",value);
271 VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
272 value = varbindDictionary.getVarbindName();
273 msg = searchElkDatabase("triggerSignaturesUsedForUI.signatures",value);
276 VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class);
277 value = vNFType.getVnftype();
278 msg = searchElkDatabase("vnfType",value);
281 VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class);
282 value = vsclAction.getVsclaction();
283 msg = searchElkDatabase("actions",value);
286 DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
287 value = decisionSettings.getXacmlId();
288 msg = searchElkDatabase("pholder",value);
291 EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class);
292 value = enforcingType.getEnforcingType();
293 msg = searchElkDatabase("pholder",value);
296 TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class);
297 value = term.getTermName();
298 msg = searchElkDatabase("firewallRuleList.ruleName",value);
301 DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
302 value = dcaeUUID.getName();
303 msg = searchElkDatabase("uuid",value);
306 MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
307 value = mslocation.getName();
308 msg = searchElkDatabase("location",value);
311 MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
312 value = msModels.getModelName();
313 msg = searchElkDatabase("configName",value);
316 GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
317 value = groupPoilicy.getGroupName();
318 msg = searchElkDatabase("PolicyScope",value);
321 RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class);
322 value = riskType.getRiskName();
323 msg = searchElkDatabase("Risk Type",value);
325 case safePolicyWarning :
326 SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
327 value = safePolicy.getName();
328 msg = searchElkDatabase("Safe Warning",value);
332 response.setCharacterEncoding("UTF-8");
333 response.setContentType("application / json");
334 request.setCharacterEncoding("UTF-8");
336 PrintWriter out = response.getWriter();
337 JSONObject j = new JSONObject("{result: " + policyNames + "}");
338 out.write(j.toString());
341 response.setCharacterEncoding("UTF-8");
342 request.setCharacterEncoding("UTF-8");
343 PrintWriter out = response.getWriter();
344 out.write(e.getMessage());
349 //Search Elk database
350 public String searchElkDatabase(String value){
351 String policyType = "";
352 String searchText = value;
353 ArrayList<PolicyLocator> locators;
354 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
356 locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0);
357 } catch (Exception ise) {
358 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
359 value = "$notSuccess%";
362 policyNames = new ArrayList<JSONObject>();
363 for (PolicyLocator p: locators) {
364 String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName + "." +p.version + ".xml";
365 LOGGER.debug(dbPolicyName);
366 JSONObject el = new JSONObject();
367 el.put("name", dbPolicyName);
370 if(!locators.isEmpty()){
377 //Search the Elk database
378 public String searchElkDatabase(String key, String value){
379 String policyType = "";
380 String searchText = key+":"+value;
381 ArrayList<PolicyLocator> locators;
382 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
383 LOGGER.debug("Parameter value is"+value);
385 String clSearchKey=null;
388 LOGGER.debug("Filter value is"+clSearchKey);
390 ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>();
392 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchKey);
393 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey);
394 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchKey);
395 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchKey);
396 //clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey);
398 String clSearchValue=null;
401 LOGGER.debug("Search value is"+clSearchValue);
403 ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
404 clSearchBoxFilterValue_s.add(clSearchValue);
406 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s));
409 locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0);
410 LOGGER.debug("No Exceptions");
411 for (PolicyLocator l: locators) {
412 LOGGER.debug(l.policyName);
414 LOGGER.debug("After for");
415 } catch (Exception ise) {
416 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage());
417 //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database ");
418 LOGGER.debug("Exceptions");
419 value = "$notSuccess%";
422 policyNames = new ArrayList<JSONObject>();
423 for (PolicyLocator p: locators) {
424 String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName + ".xml";
425 LOGGER.debug(dbPolicyName);
426 JSONObject el = new JSONObject();
427 el.put("name", dbPolicyName);
430 if(!locators.isEmpty()){
432 LOGGER.debug("Success");
438 //For AutoPush of policy using descriptive Scope.
439 //Returns string either "UnMatched" or "Matched" or "Search Unavailable".
440 public String searchDescriptiveScope(String scopeName, String policyNameToCheck) {
441 String searchText=null;
442 String status="UnMatched";
443 ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s =
444 new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>();
445 //Finding the descriptive scope search tag.
446 LOGGER.warn("Entry into DS");
447 DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", scopeName);
449 searchText=dsSearch.getSearch();
450 LOGGER.warn("Search text is " + searchText);
451 if (LOGGER.isDebugEnabled()) {
452 LOGGER.debug("DescriptiveScope Search String is " +searchText );
456 if(searchText.contains(":"))
458 String connector="AND";
460 for (String retval: searchText.split(connector)){
462 int index= retval.indexOf(':');
463 String filterKey=null;
464 String filterValue=null;
466 filterKey=retval.substring(0,index).trim();
467 filterValue= retval.substring(index+1).trim();
469 LOGGER.debug("Key is "+filterKey+" and value is "+filterValue);
470 String clSearchBoxFilter=filterKey;
472 ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>();
474 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter);
475 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter);
476 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter);
477 clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter);
480 ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>();
481 clSearchBoxFilterValue_s.add(filterValue);
483 filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s));
487 ArrayList<PolicyLocator> locators=null;
489 LOGGER.warn("Before calling search");
490 locators = ElkConnector.singleton.policyLocators(ElkConnector.PolicyIndexType.all,
491 searchText, filter_s,connectorSelected);
492 LOGGER.warn("After calling search");
493 } catch (Exception ise) {
494 //AdminNotification.warn("Search is unavailable: " + ise.getMessage());
495 status= "Search Unavailable";
496 LOGGER.warn("Search is unavailable");
498 synchronized(filteredPolicies) {
499 if (locators.isEmpty()) {
500 LOGGER.debug("No match has been found");
501 //AdminNotification.warn("No match has been found");
505 for (PolicyLocator p: locators) {
506 LOGGER.debug("Second String "+policyNameToCheck);
507 if(p.policyName.contains(policyNameToCheck))
510 LOGGER.warn("Policies matched");
515 LOGGER.warn("Policies Unmatched");
526 private String query;
527 private String policyType;
528 private String descriptiveScope;
529 private String closedLooppolicyType;
530 private String ecompName;
531 private String d2Service;
532 private String vnfType;
533 private String policyStatus;
534 private String vproAction;
535 private String serviceType;
536 private String bindTextSearch;
537 public String getQuery() {
540 public void setQuery(String query) {
543 public String getPolicyType() {
546 public void setPolicyType(String policyType) {
547 this.policyType = policyType;
549 public String getDescriptiveScope() {
550 return descriptiveScope;
552 public void setDescriptiveScope(String descriptiveScope) {
553 this.descriptiveScope = descriptiveScope;
555 public String getClosedLooppolicyType() {
556 return closedLooppolicyType;
558 public void setClosedLooppolicyType(String closedLooppolicyType) {
559 this.closedLooppolicyType = closedLooppolicyType;
561 public String getEcompName() {
564 public void setEcompName(String ecompName) {
565 this.ecompName = ecompName;
567 public String getD2Service() {
570 public void setD2Service(String d2Service) {
571 this.d2Service = d2Service;
573 public String getVnfType() {
576 public void setVnfType(String vnfType) {
577 this.vnfType = vnfType;
579 public String getPolicyStatus() {
582 public void setPolicyStatus(String policyStatus) {
583 this.policyStatus = policyStatus;
585 public String getVproAction() {
588 public void setVproAction(String vproAction) {
589 this.vproAction = vproAction;
591 public String getServiceType() {
594 public void setServiceType(String serviceType) {
595 this.serviceType = serviceType;
597 public String getBindTextSearch() {
598 return bindTextSearch;
600 public void setBindTextSearch(String bindTextSearch) {
601 this.bindTextSearch = bindTextSearch;