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