Policy TestSuite Enabled
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / openecomp / policy / controller / DashboardController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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
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.openecomp.policy.controller;
22
23
24 import java.io.IOException;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34 import javax.management.AttributeNotFoundException;
35 import javax.management.InstanceNotFoundException;
36 import javax.management.MBeanException;
37 import javax.management.MalformedObjectNameException;
38 import javax.management.ObjectName;
39 import javax.management.ReflectionException;
40 import javax.management.remote.JMXConnector;
41 import javax.management.remote.JMXConnectorFactory;
42 import javax.management.remote.JMXServiceURL;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45
46 import org.json.JSONObject;
47 import org.openecomp.policy.dao.SystemLogDbDao;
48 import org.openecomp.policy.model.PDPGroupContainer;
49 import org.openecomp.policy.rest.XACMLRestProperties;
50 import org.openecomp.policy.rest.dao.CommonClassDao;
51 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
52 import org.openecomp.portalsdk.core.web.support.JsonMessage;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.MediaType;
55 import org.springframework.stereotype.Controller;
56 import org.springframework.web.bind.annotation.RequestMapping;
57
58 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
59 import org.openecomp.policy.common.logging.flexlogger.Logger;
60 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
61 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
62 import org.openecomp.policy.xacml.api.pap.EcompPDP;
63 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
64
65 import com.att.research.xacml.api.pap.PAPException;
66 import com.att.research.xacml.api.pap.PDP;
67 import com.att.research.xacml.api.pap.PDPGroup;
68 import com.att.research.xacml.api.pap.PDPPolicy;
69 import com.att.research.xacml.util.XACMLProperties;
70 import com.fasterxml.jackson.annotation.PropertyAccessor;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72
73 @Controller
74 @RequestMapping({"/"})
75 public class DashboardController  extends RestrictedBaseController{
76         private static final Logger logger = FlexLogger.getLogger(DashboardController.class);
77         @Autowired
78         SystemLogDbDao systemDAO;
79         
80         @Autowired
81         CommonClassDao commonClassDao;
82         
83         private int pdpCount;
84         private PDPGroupContainer pdpConatiner;
85         private ArrayList<Object> pdpStatusData;
86         private ArrayList<Object> papStatusData;
87         private ArrayList<Object> policyActivityData;
88         
89
90         
91         @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
92         public void getData(HttpServletRequest request, HttpServletResponse response){
93                 try{
94                         Map<String, Object> model = new HashMap<String, Object>();
95                         ObjectMapper mapper = new ObjectMapper();
96                         model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
97                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
98                         JSONObject j = new JSONObject(msg);
99                         response.getWriter().write(j.toString());
100                 }
101                 catch (Exception e){
102                         logger.error("Exception Occured"+e);
103                 }
104         }
105         
106         @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
107         public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){
108                 try{
109                         Map<String, Object> model = new HashMap<String, Object>();
110                         ObjectMapper mapper = new ObjectMapper();
111                         model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
112                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
113                         JSONObject j = new JSONObject(msg);
114                         response.getWriter().write(j.toString());
115                 }
116                 catch (Exception e){
117                         logger.error("Exception Occured"+e);
118                 }
119         }
120         
121         @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
122         public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){
123                 try{
124                         Map<String, Object> model = new HashMap<String, Object>();
125                         ObjectMapper mapper = new ObjectMapper();
126                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
127                         addPAPToTable();
128                         model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
129                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
130                         JSONObject j = new JSONObject(msg);
131                         response.getWriter().write(j.toString());
132                 }
133                 catch (Exception e){
134                         logger.error("Exception Occured"+e);
135                 }
136         }
137         
138         @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
139         public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){
140                 try{
141                         Map<String, Object> model = new HashMap<String, Object>();
142                         ObjectMapper mapper = new ObjectMapper();
143                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
144                         this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
145                         addPDPToTable();
146                         model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
147                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
148                         JSONObject j = new JSONObject(msg);
149                         response.getWriter().write(j.toString());
150                 }
151                 catch (Exception e){
152                         logger.error("Exception Occured"+e);
153                 }
154         }
155         
156         @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
157         public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){
158                 try{
159                         Map<String, Object> model = new HashMap<String, Object>();
160                         ObjectMapper mapper = new ObjectMapper();
161                         mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
162                         this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
163                         addPolicyToTable();
164                         model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
165                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
166                         JSONObject j = new JSONObject(msg);
167                         response.getWriter().write(j.toString());
168                 }
169                 catch (Exception e){
170                         logger.error("Exception Occured"+e);
171                 }
172         }
173         
174         /*
175          * Add the PAP information to the PAP Table
176          */
177         public void addPAPToTable(){
178                 papStatusData = new ArrayList<Object>();
179                 String papStatus = null;
180                 try {
181                         Set<EcompPDPGroup> groups = PolicyController.getPapEngine().getEcompPDPGroups();
182                         if (groups == null) {
183                                 papStatus = "UNKNOWN";
184                                 throw new PAPException("PAP not running");              
185                         }else {
186                                 papStatus = "IS_OK";
187                         }
188                 } catch (PAPException | NullPointerException e1) {
189                         papStatus = "CANNOT_CONNECT";
190                         logger.error("Error getting PAP status, PAP not responding to requests");
191                 }
192                 String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
193                 JSONObject object = new JSONObject();
194                 object.put("system", papURL);
195                 object.put("status", papStatus);
196                 List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity");
197                 object.put("noOfPolicy", data.size());
198                 object.put("noOfConnectedTrap", pdpCount);
199                 papStatusData.add(0, object);
200         }
201         
202         /**
203          * Add PDP Information to the PDP Table
204          *  
205          */
206         public void addPDPToTable(){    
207                 pdpCount = 0;
208                 pdpStatusData = new ArrayList<Object>();
209                 long naCount;
210                 long denyCount = 0;
211                 long permitCount = 0;
212                 for (PDPGroup group : this.pdpConatiner.getGroups()){   
213                         for (PDP pdp : group.getPdps()){
214                                 naCount = -1;
215                                 if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){
216                                         String pdpIpAddress = parseIPSystem(pdp.getId());
217                                         int port = ((EcompPDP) pdp).getJmxPort();
218                                         if (port != 0)
219                                         logger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
220                                         naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA");
221                                         permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit");
222                                         denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny");
223                                 }
224                                 if (naCount == -1){
225                                         JSONObject object = new JSONObject();
226                                         object.put("id", pdp.getId());
227                                         object.put("name", pdp.getName());
228                                         object.put("groupname", group.getName());
229                                         object.put("status", pdp.getStatus().getStatus().toString());
230                                         object.put("description", pdp.getDescription());
231                                         object.put("permitCount", "NA");
232                                         object.put("denyCount", "NA");
233                                         object.put("naCount", "NA");
234                                         pdpStatusData.add(object);
235                                 }else{  
236                                         JSONObject object = new JSONObject();
237                                         object.put("id", pdp.getId());
238                                         object.put("name", pdp.getName());
239                                         object.put("groupname", group.getName());
240                                         object.put("status", pdp.getStatus().getStatus().toString());
241                                         object.put("description", pdp.getDescription());
242                                         object.put("permitCount", permitCount);
243                                         object.put("denyCount", denyCount);
244                                         object.put("naCount", naCount);
245                                         pdpStatusData.add(object);
246                                 }
247                                 pdpCount++;
248                         }
249                 }
250         }
251         
252         private static String parseIPSystem(String line) {      
253                 Pattern pattern = Pattern.compile("://(.+?):");
254                 Matcher ip = pattern.matcher(line);
255                 if (ip.find())
256                 {
257                         return ip.group(1);
258                 } 
259                 return null;
260         }
261         
262         /*
263          * Contact JMX Connector Sever and return the value of the given jmxAttribute
264          */
265         @SuppressWarnings({ "rawtypes", "unchecked" })
266         private long getRequestCounts(String host, int port, String jmxAttribute) {
267                 
268                 logger.debug("Create an RMI connector client and connect it to the JMX connector server");
269                 HashMap map = new HashMap();
270                 map = null;
271                 JMXConnector jmxConnection;
272                 try {
273                         jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
274                         jmxConnection.connect();
275                         Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
276                         jmxConnection.close();
277                         logger.debug("pdpEvaluationNA value retreived: " + o);
278                         return (long) o;
279                 } catch (MalformedURLException e) {
280                         logger.error("MalformedURLException for JMX connection");
281                 } catch (IOException e) {
282                         logger.error("Error in reteriving" + jmxAttribute + " from JMX connection");
283                 } catch (AttributeNotFoundException e) {                
284                         logger.error("AttributeNotFoundException  " + jmxAttribute +  " for JMX connection");
285                 } catch (InstanceNotFoundException e) {
286                         logger.error("InstanceNotFoundException " + host + " for JMX connection");
287                 } catch (MalformedObjectNameException e) {
288                         logger.error("MalformedObjectNameException for JMX connection");
289                 } catch (MBeanException e) {
290                         logger.error("MBeanException for JMX connection");
291                         logger.error("Exception Occured"+e);
292                 } catch (ReflectionException e) {
293                         logger.error("ReflectionException for JMX connection");
294                 }
295                 
296                 return -1;
297         }
298         
299         private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{
300             return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
301         }
302         
303         
304         /*
305          * Add the information to the Policy Table
306          */
307         private void addPolicyToTable() {
308                 policyActivityData = new ArrayList<Object>();
309                 int i = 1;
310                 String policyID = null;
311                 int policyFireCount = 0;
312                 Map<String, String> policyMap = new HashMap<>();
313                 Object policyList = null;
314                 //get list of policy 
315                 
316                 for (PDPGroup group : this.pdpConatiner.getGroups()){   
317                         for (PDPPolicy policy : group.getPolicies()){
318                                 try{
319                                         policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId());
320                                 }catch(Exception e){
321                                         logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e);
322                                 }
323                         }
324                         
325                         for (PDP pdp : group.getPdps()){                
326                                         // Add rows to the Policy Table
327                                 policyList = null;
328                                 if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){
329                                         String pdpIpAddress = parseIPSystem(pdp.getId());
330                                         policyList = getPolicy(pdpIpAddress, ((EcompPDP) pdp).getJmxPort(), "policyCount");
331                                 }
332                                 if (policyList != null && policyList.toString().length() > 3){
333                                                 String[]  splitPolicy = policyList.toString().split(",");
334                                                 for (String policyKeyValue : splitPolicy){      
335                                                         policyID = urnPolicyID(policyKeyValue); 
336                                                         policyFireCount = countPolicyID(policyKeyValue);        
337                                                         if (policyID != null ){
338                                                                 if (policyMap.containsKey(policyID)){
339                                                                         JSONObject object = new JSONObject();
340                                                                         object.put("policyId", policyMap.get(policyID));
341                                                                         object.put("fireCount", policyFireCount);
342                                                                         object.put("system", pdp.getId());
343                                                                         policyActivityData.add(i, object);      
344                                                                         i++;
345                                                                 }
346                                                         }
347                                                 }
348                                 }else {
349                                         if (policyList != null){
350                                                 JSONObject object = new JSONObject();
351                                                 object.put("policyId", "Unable to retrieve policy information");
352                                                 object.put("fireCount", "NA");
353                                                 object.put("system", pdp.getId());
354                                                 policyActivityData.add(i, object);
355                                                 i++;
356                                         }else{
357                                                 JSONObject object = new JSONObject();
358                                                 object.put("policyId", "Unable to access PDP JMX Server");
359                                                 object.put("fireCount", "NA");
360                                                 object.put("system", pdp.getId());
361                                                 policyActivityData.add(i, object);
362                                                 i++;
363                                         }
364                                 }                                                       
365         
366                         }
367                 }
368         }
369         
370         /*
371          * Contact JMX Connector Sever and return the list of {policy id , count}
372          */
373         @SuppressWarnings({ "rawtypes", "unchecked" })
374         private Object getPolicy(String host, int port, String jmxAttribute){
375                 logger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
376                 HashMap map = new HashMap();
377                 map = null;
378                 JMXConnector jmxConnection;
379                 try {
380                         jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map);
381                         jmxConnection.connect();
382                         Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
383                         jmxConnection.close();
384                         logger.debug("policyMap value retreived: " + o);
385                         return  o;
386                 } catch (MalformedURLException e) {
387                         logger.error("MalformedURLException for JMX connection");
388                 } catch (IOException e) {
389                         logger.error("AttributeNotFoundException for policyMap" );
390                 } catch (AttributeNotFoundException e) {                
391                         logger.error("AttributeNotFoundException for JMX connection");
392                 } catch (InstanceNotFoundException e) {
393                         logger.error("InstanceNotFoundException " + host + " for JMX connection");
394                 } catch (MalformedObjectNameException e) {
395                         logger.error("MalformedObjectNameException for JMX connection");
396                 } catch (MBeanException e) {
397                         logger.error("MBeanException for JMX connection");
398                         logger.error("Exception Occured"+e);
399                 } catch (ReflectionException e) {
400                         logger.error("ReflectionException for JMX connection");
401                 }
402                 
403                 return null;
404         
405         }
406         
407         private static String urnPolicyID(String line){
408                 String[]  splitLine = line.toString().split("=");       
409                 String removeSpaces = splitLine[0].replaceAll("\\s+", "");
410                 return removeSpaces.replace("{", "");
411         }
412         
413         private static Integer countPolicyID(String line){
414                 String[]  splitLine = line.toString().split("=");
415                 String sCount = splitLine[1].replace("}", "");
416                 int intCount = Integer.parseInt(sCount);
417                 return intCount;
418         }
419         
420 }