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