15e1faa0414b0c903475d805c0f66fe126288503
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / handler / DeleteHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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 package org.openecomp.policy.pap.xacml.rest.handler;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.sql.Connection;
25 import java.sql.DriverManager;
26 import java.sql.ResultSet;
27 import java.sql.SQLException;
28 import java.sql.Statement;
29 import java.util.List;
30
31 import javax.persistence.EntityManager;
32 import javax.persistence.Query;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
37 import org.openecomp.policy.common.logging.eelf.MessageCodes;
38 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
39 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
40 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
41 import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
42 import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy;
43 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
46 import org.openecomp.policy.rest.jpa.PolicyEntity;
47 import org.openecomp.policy.rest.jpa.PolicyVersion;
48 import org.openecomp.policy.utils.PolicyUtils;
49 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
50 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
51 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
52 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
53
54 import com.att.research.xacml.api.pap.PAPException;
55 import com.att.research.xacml.api.pap.PDPPolicy;
56 import com.att.research.xacml.util.XACMLProperties;
57
58 public class DeleteHandler {
59
60         private EcompPDPGroup newgroup;
61         
62         private static String papDbDriver = null;
63         private static String papDbUrl = null;
64         private static String papDbUser = null;
65         private static String papDbPassword = null;
66
67         public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws Exception {
68                 // get the request content into a String
69                 String json = null;
70                 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
71                 scanner.useDelimiter("\\A");
72                 json =  scanner.hasNext() ? scanner.next() : "";
73                 scanner.close();
74                 PolicyLogger.info("JSON request from API: " + json);
75                 // convert Object sent as JSON into local object
76                 StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class);
77                 String policyName = policy.getPolicyName();
78                 Boolean policyVersionDeleted = false;
79                 String removeXMLExtension;
80                 int currentVersion;
81                 String removeVersionExtension;
82                 String splitPolicyName = null;
83                 String[] split = null;
84                 String status = "error";
85                 PolicyEntity policyEntity = null;
86                 JPAUtils jpaUtils = null;
87
88                 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
89                 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
90                 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
91                 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
92                 Connection con = null;
93                 
94                 try {
95                         jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
96                 } catch (Exception e) {
97                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
98                         response.addHeader("error", "jpautils");
99                         response.addHeader("operation", "delete");
100                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
101                         return;
102                 }
103                 if (jpaUtils.dbLockdownIgnoreErrors()) {
104                         PolicyLogger.warn("Policies are locked down");
105                         response.addHeader("operation", "delete");
106                         response.addHeader("lockdown", "true");
107                         response.setStatus(HttpServletResponse.SC_ACCEPTED);
108                         return;
109                 }
110                 EntityManager em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
111                 Query policyEntityQuery = null;
112                 try{
113                         if(policyName.endsWith(".xml")){
114                                 removeXMLExtension = policyName.replace(".xml", "");
115                                 currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1));
116                                 removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf("."));
117                                 boolean queryCheck = true;
118                                 if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
119                                         if(policyName.contains("Config_")){
120                                                 splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_");
121                                         }else if(policyName.contains("Action_")){
122                                                 splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_");
123                                         }else if(policyName.contains("Decision_")){
124                                                 splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_");
125                                         }
126                                         split = splitPolicyName.split(":");
127                                         policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope");
128                                 }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
129                                         if(policyName.contains("Config_")){
130                                                 splitPolicyName = policyName.replace(".Config_", ":Config_");
131                                         }else if(policyName.contains("Action_")){
132                                                 splitPolicyName = policyName.replace(".Action_", ":Action_");
133                                         }else if(policyName.contains("Decision_")){
134                                                 splitPolicyName = policyName.replace(".Decision_", ":Decision_");
135                                         }
136                                         split = splitPolicyName.split(":");
137                                         queryCheck = false;
138                                         policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope");
139                                 }
140                                 
141                                 if(queryCheck){
142                                         policyEntityQuery.setParameter("pName", "%"+split[1]+"%");
143                                 }else{
144                                         policyEntityQuery.setParameter("pName", split[1]);
145                                 }
146                                 
147                                 policyEntityQuery.setParameter("pScope", split[0]);
148                                 List<?> peResult = policyEntityQuery.getResultList();
149                                 if(!peResult.isEmpty()){
150                                         Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
151                                         getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator));
152                                         List<?> pvResult = getPolicyVersion.getResultList();
153                                         PolicyVersion pVersion = (PolicyVersion) pvResult.get(0);
154                                         int highestVersion = 0; 
155                                         em.getTransaction().begin();
156                                         Class.forName(papDbDriver);
157                                         con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
158                                         
159                                         if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
160                                                 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
161                                                 if(!groupCheck){
162                                                         for(Object peData : peResult){
163                                                                 policyEntity = (PolicyEntity) peData;
164                                                                 status = deletePolicyEntityData(em, policyEntity);
165                                                         }
166                                                 }else{
167                                                         status = "PolicyInPDP";
168                                                 }
169                                                 if(status.equals("error")){
170                                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
171                                                         response.addHeader("error", "unknown");
172                                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
173                                                         return;
174                                                 }else if(status.equals("PolicyInPDP")){
175                                                         PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
176                                                         response.addHeader("error", "unknown");
177                                                         response.setStatus(HttpServletResponse.SC_CONFLICT);
178                                                         return;
179                                                 }else{
180                                                         try{
181                                                                 policyVersionDeleted = true;
182                                                                 em.remove(pVersion);
183                                                         }catch(Exception e){
184                                                                 policyVersionDeleted = false;
185                                                         }
186                                                 }
187                                         }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){
188                                                 boolean groupCheck = checkPolicyGroupEntity(em, con, peResult);
189                                                 if(!groupCheck){
190                                                         policyEntity = (PolicyEntity) peResult.get(0);
191                                                         status = deletePolicyEntityData(em, policyEntity);
192                                                 }else{
193                                                         status = "PolicyInPDP";
194                                                 }
195                                                 
196                                                 if(status.equals("error")){
197                                                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database.");
198                                                         response.addHeader("error", "unknown");
199                                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
200                                                         return;
201                                                 }else if(status.equals("PolicyInPDP")){
202                                                         PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups.");
203                                                         response.addHeader("error", "unknown");
204                                                         response.setStatus(HttpServletResponse.SC_CONFLICT);
205                                                         return;
206                                                 }else{
207                                                         if(currentVersion > 1){
208                                                                 if(!peResult.isEmpty()){
209                                                                         for(Object object : peResult){
210                                                                                 policyEntity = (PolicyEntity) object;
211                                                                                 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
212                                                                                 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
213                                                                                 if(policyEntityVersion > highestVersion){
214                                                                                         highestVersion = policyEntityVersion;
215                                                                                 }
216                                                                         }
217                                                                 }
218                                                                 pVersion.setActiveVersion(highestVersion);
219                                                                 pVersion.setHigherVersion(highestVersion);
220                                                                 try{
221                                                                         policyVersionDeleted = true;
222                                                                         em.persist(pVersion);
223                                                                 }catch(Exception e){
224                                                                         policyVersionDeleted = false;
225                                                                 }
226                                                         }else{
227                                                                 try{
228                                                                         policyVersionDeleted = true;
229                                                                         em.remove(pVersion);
230                                                                 }catch(Exception e){
231                                                                         policyVersionDeleted = false;
232                                                                 }
233                                                         }
234                                                 }
235                                         }
236                                 }else{
237                                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");
238                                         response.addHeader("error", "unknown");
239                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
240                                         return;
241                                 }
242                         }
243                         em.getTransaction().commit();
244                 }catch(Exception e){
245                         em.getTransaction().rollback();
246                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
247                         response.addHeader("error", "deleteDB");
248                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
249                         return;
250                 } finally {
251                         em.close();
252                         con.close();
253                 }
254
255                 if (policyVersionDeleted) {
256                         response.setStatus(HttpServletResponse.SC_OK);
257                         response.addHeader("successMapKey", "success");
258                         response.addHeader("operation", "delete");
259                         return;                         
260                 } else {
261                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");
262                         response.addHeader("error", "unknown");
263                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
264                         return;
265                 }
266         }
267         
268         public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{
269                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
270                 PolicyRestAdapter policyData = new PolicyRestAdapter();
271                 String policyName = policyEntity.getPolicyName();
272                 try{
273                         if(policyName.contains("Config_")){
274                                 em.remove(policyEntity.getConfigurationData());
275                         }else if(policyName.contains("Action_")){
276                                 em.remove(policyEntity.getActionBodyEntity());
277                         }
278                         String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
279                         policyData.setNewFileName(searchPolicyName);
280                         controller.deleteElk(policyData);
281                         em.remove(policyEntity);
282                 }catch(Exception e){
283                         return "error";
284                 }
285                 return "success";
286         }
287         
288         public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List<?> peResult) throws SQLException{
289                 for(Object peData : peResult){
290                         PolicyEntity policyEntity = (PolicyEntity) peData;
291                         Statement st = null;
292                         ResultSet rs = null;
293                         st = con.createStatement();
294                         rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'");
295                         boolean gEntityList = rs.next();
296                         rs.close();
297                         if(gEntityList){
298                                 return true;
299                         }
300                 }
301                 return false;
302         }
303
304         public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws IOException {
305                 String policyName = request.getParameter("policyName");
306                 String groupId = request.getParameter("groupId");
307                 String responseString = null;
308                 // for PUT operations the group may or may not need to exist before the operation can be done
309                 EcompPDPGroup group = null;
310                 try {
311                         group = XACMLPapServlet.getPAPEngine().getGroup(groupId);
312                 } catch (PAPException e) {
313                         PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e);
314                 }
315                 if (group == null) {
316                         String message = "Unknown groupId '" + groupId + "'";
317                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
318                         loggingContext.transactionEnded();
319                         PolicyLogger.audit("Transaction Failed - See Error.log");
320                         response.addHeader("error", "UnknownGroup");
321                         response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
322                         return;
323                 } else {
324                         loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
325                         if (policyName.contains("xml")) {
326                                 PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue.");
327                         } else {
328                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
329                                                 + "policyName must be the full name of the file to be deleted including version and extension";
330                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
331                                                 + "policyName must be the full name of the file to be deleted including version and extension");
332                                 response.addHeader("error", message);
333                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
334                                 return;
335                         }
336                         RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
337                         PDPPolicy policy =  group.getPolicy(policyName);
338                         if (policy != null) {
339                                 
340                                 if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
341                                         if (preSafetyCheck(policy)) {
342                                                 PolicyLogger.debug("Precheck Successful.");
343                                         }
344                                 }
345                                 
346                                 removePolicy.prepareToRemove(policy);
347                                 EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
348                                 responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
349                         } else {
350                                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
351                                 PolicyLogger.error(message);
352                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
353                                 response.addHeader("error", message);
354                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
355                                 return;
356                         }                       
357                 }
358                 if (responseString.equals("success")) {
359                         PolicyLogger.info("Policy successfully deleted!");
360                         PolicyLogger.audit("Policy successfully deleted!");
361                         response.setStatus(HttpServletResponse.SC_OK);
362                         response.addHeader("successMapKey", "success");
363                         response.addHeader("operation", "delete");
364                         return;         
365                 } else if (responseString.equals("No Group")) {
366                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
367                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
368                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
369                         response.addHeader("error", "groupUpdate");
370                         response.addHeader("message", message);
371                         return; 
372                 } else if (responseString.equals("DB Error")) {
373                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
374                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
375                         response.addHeader("error", "deleteDB");
376                         return;
377                 } else {
378                         PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");
379                         response.addHeader("error", "unknown");
380                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
381                         return;
382                 }
383         }
384
385         private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
386                 PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
387                 String response = null;
388                 loggingContext.setServiceName("API:PAP.DeleteHandler");
389                 EcompPDPGroup existingGroup = null;
390                 try {
391                         existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId());
392                 } catch (PAPException e1) {
393                         PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1);
394                 }
395                 if (group == null || ! (group instanceof StdPDPGroup) || ! (group.getId().equals(existingGroup.getId()))) {
396                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup.getId() + " objectFromJSON="+group);
397                         loggingContext.transactionEnded();
398                         PolicyLogger.audit("Transaction Failed - See Error.log");
399                         response = "No Group";
400                         return response;
401                 }
402                 // The Path on the PAP side is not carried on the RESTful interface with the AC
403                 // (because it is local to the PAP)
404                 // so we need to fill that in before submitting the group for update
405                 ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
406                 try{
407                         acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
408                 } catch(Exception e){
409                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
410                                         +"group="+existingGroup.getId());
411                         response = "DB Error";
412                         return response;
413                 }
414                 try {
415                         XACMLPapServlet.getPAPEngine().updateGroup(group);
416                 } catch (PAPException e) {
417                         PolicyLogger.error("Exception occured While Updating PDP Groups"+e);
418                         response = "error in updateGroup method";
419                 }
420                 PolicyLogger.debug("Group '" + group.getId() + "' updated");
421                 acPutTransaction.commitTransaction();
422                 // Group changed, which might include changing the policies
423                 try {
424                         newgroup = existingGroup;
425                 }  catch (Exception e) {
426                         PolicyLogger.error("Exception occured in Group Change Method"+e);
427                         response = "error in groupChanged method";
428                 }
429                 if (response==null){
430                         response = "success";
431                         PolicyLogger.audit("Policy successfully deleted!");
432                         PolicyLogger.audit("Transaction Ended Successfully");
433                 }
434                 loggingContext.transactionEnded();
435                 PolicyLogger.audit("Transaction Ended");
436                 return response;
437         }
438         
439         public EcompPDPGroup getDeletedGroup(){
440                 return newgroup;
441         }
442         
443         public boolean preSafetyCheck(PDPPolicy policy) {
444                 return true;
445         }
446         
447         public static DeleteHandler getInstance() {
448                 try {
449                         Class<?> deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName()));
450                         DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance(); 
451                         return instance;
452                 } catch (Exception e) {
453                         PolicyLogger.error(e.getMessage());
454                 }
455                 return null;
456         }
457
458 }