2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.policy.pap.xacml.rest;
23 import java.io.BufferedWriter;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.OutputStreamWriter;
31 import java.io.UnsupportedEncodingException;
32 import java.io.Writer;
33 import java.net.ConnectException;
34 import java.net.HttpURLConnection;
35 import java.net.InetAddress;
36 import java.net.MalformedURLException;
37 import java.net.SocketTimeoutException;
40 import java.net.URLDecoder;
41 import java.net.UnknownHostException;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.nio.file.Paths;
45 import java.sql.Timestamp;
46 import java.util.ArrayList;
47 import java.util.Calendar;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Properties;
55 import java.util.UUID;
56 import java.util.concurrent.CopyOnWriteArrayList;
58 import javax.persistence.EntityManager;
59 import javax.persistence.Persistence;
60 import javax.persistence.Query;
61 import javax.persistence.EntityManagerFactory;
62 import javax.servlet.Servlet;
63 import javax.servlet.ServletConfig;
64 import javax.servlet.ServletException;
65 import javax.servlet.annotation.WebInitParam;
66 import javax.servlet.annotation.WebServlet;
67 import javax.servlet.http.HttpServlet;
68 import javax.servlet.http.HttpServletRequest;
69 import javax.servlet.http.HttpServletResponse;
70 import javax.xml.parsers.DocumentBuilder;
71 import javax.xml.parsers.DocumentBuilderFactory;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
76 import org.apache.commons.io.FilenameUtils;
77 import org.apache.commons.io.IOUtils;
78 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
79 import org.openecomp.policy.pap.xacml.rest.components.ActionPolicy;
80 import org.openecomp.policy.pap.xacml.rest.components.AutoPushPolicy;
81 import org.openecomp.policy.pap.xacml.rest.components.ClosedLoopPolicy;
82 import org.openecomp.policy.pap.xacml.rest.components.ConfigPolicy;
83 import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsParamPolicy;
84 import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsRawPolicy;
85 import org.openecomp.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics;
86 import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroSerivceModel;
87 import org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy;
88 import org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy;
89 import org.openecomp.policy.pap.xacml.rest.components.MicroServiceConfigPolicy;
90 import org.openecomp.policy.pap.xacml.rest.components.Policy;
91 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao;
92 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
93 import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy;
94 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
95 import org.openecomp.policy.pap.xacml.restAuth.CheckPDP;
96 import org.openecomp.policy.rest.XACMLRest;
97 import org.openecomp.policy.rest.XACMLRestProperties;
98 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
99 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
100 import org.openecomp.policy.rest.jpa.MicroServiceModels;
101 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
102 import org.openecomp.policy.rest.jpa.PolicyScore;
103 import org.openecomp.policy.rest.jpa.PolicyVersion;
104 import org.openecomp.policy.rest.jpa.UserInfo;
105 import org.w3c.dom.Document;
106 import org.w3c.dom.Element;
107 import org.w3c.dom.Node;
108 import org.w3c.dom.NodeList;
110 import javax.persistence.PersistenceException;
112 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
113 import org.openecomp.policy.common.logging.ECOMPLoggingUtils;
114 import org.openecomp.policy.common.logging.eelf.MessageCodes;
115 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
117 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
118 import org.openecomp.policy.xacml.api.pap.ECOMPPapEngineFactory;
119 import org.openecomp.policy.xacml.api.pap.EcompPDP;
120 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
121 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
123 import com.att.research.xacml.api.pap.PAPException;
124 //import com.att.research.xacml.api.pap.PDP;
125 //import com.att.research.xacml.api.pap.PDPGroup;
126 import com.att.research.xacml.api.pap.PDPPolicy;
127 import com.att.research.xacml.api.pap.PDPStatus;
128 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
129 import org.openecomp.policy.xacml.std.pap.StdPDP;
130 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
131 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
132 import org.openecomp.policy.xacml.std.pap.StdPDPStatus;
133 import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
134 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
136 import com.att.research.xacml.util.FactoryException;
137 import com.att.research.xacml.util.XACMLProperties;
138 import com.fasterxml.jackson.core.JsonParseException;
139 import com.fasterxml.jackson.databind.JsonMappingException;
140 import com.fasterxml.jackson.databind.ObjectMapper;
141 import com.google.common.base.Joiner;
142 import com.google.common.base.Splitter;
143 import org.openecomp.policy.common.im.AdministrativeStateException;
144 import org.openecomp.policy.common.im.ForwardProgressException;
147 import org.openecomp.policy.common.im.IntegrityMonitor;
148 import org.openecomp.policy.common.im.IntegrityMonitorProperties;
149 import org.openecomp.policy.common.im.StandbyStatusException;
151 import org.openecomp.policy.common.ia.IntegrityAudit;
152 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
153 import org.openecomp.policy.common.logging.flexlogger.Logger;
157 * Servlet implementation class XacmlPapServlet
162 description = "Implements the XACML PAP RESTful API.",
163 urlPatterns = { "/" },
166 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
169 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
170 private static final long serialVersionUID = 1L;
171 private static final Logger logger = FlexLogger.getLogger(XACMLPapServlet.class);
173 private static String CONFIG_HOME = getConfigHome();
174 private static String ACTION_HOME = getActionHome();
176 // audit (transaction) logger
177 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
179 private IntegrityMonitor im;
180 private IntegrityAudit ia;
184 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
186 private PAPPolicyEngine papEngine = null;
188 * This PAP instance's own URL.
190 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
192 private static String papURL = null;
195 * These are the parameters needed for DB access from the PAP
197 public static String papDbDriver = null;
198 public static String papDbUrl = null;
199 public static String papDbUser = null;
200 public static String papDbPassword = null;
201 private static Integer papTransWait = null;
202 private static Integer papTransTimeout = null;
203 private static Integer papAuditTimeout = null;
204 private static Boolean papAuditFlag = null;
205 private static Boolean papFileSystemAudit = null;
206 private static Boolean autoPushFlag = false;
207 private static String papResourceName = null;
208 private static Integer fpMonitorInterval = null;
209 private static Integer failedCounterThreshold = null;
210 private static Integer testTransInterval = null;
211 private static Integer writeFpcInterval = null;
212 private static String papSiteName=null;
213 private static String papNodeType=null;
214 private static String papDependencyGroups = null;
215 private String storedRequestId = null;
216 private static int papIntegrityAuditPeriodSeconds = -1;
217 private static String[] papDependencyGroupsFlatArray = null;
219 //The entity manager factory for JPA access
220 private EntityManagerFactory emf;
222 //Persistence Unit for JPA
223 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
224 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
228 * List of Admin Console URLs.
229 * Used to send notifications when configuration changes.
231 * The CopyOnWriteArrayList *should* protect from concurrency errors.
232 * This list is seldom changed but often read, so the costs of this approach make sense.
234 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<String>();
236 // Mike M 11/24 Client Headers.
237 private static final String ENVIRONMENT_HEADER = "Environment";
238 private static String environment = null;
241 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
242 * this servlet starts. Its configurable by the admin.
244 private Thread initiateThread = null;
247 // The heartbeat thread.
249 private static Heartbeat heartbeat = null;
250 private static Thread heartbeatThread = null;
252 private ECOMPLoggingContext baseLoggingContext = null;
254 private PolicyDBDao policyDBDao;
255 private AutoPushPolicy autoPushPolicy;
257 * @see HttpServlet#HttpServlet()
259 public XACMLPapServlet() {
265 private static String pdpFile = null;
266 public static String getPDPFile(){
267 return XACMLPapServlet.pdpFile;
271 * @see Servlet#init(ServletConfig)
273 public void init(ServletConfig config) throws ServletException {
280 baseLoggingContext = new ECOMPLoggingContext();
281 // fixed data that will be the same in all logging output goes here
283 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
284 baseLoggingContext.setServer(hostname);
285 } catch (UnknownHostException e) {
286 logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging");
292 XACMLRest.xacmlInit(config);
294 // Load the properties
296 XACMLRest.loadXacmlProperties(null, null);
299 * Retrieve the property values for db access and audits from the xacml.pap.properties
301 //Null string occurs when a property is not present
303 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
304 if(papDbDriver == null){
305 throw new PAPException("papDbDriver is null");
309 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
313 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
314 if(papDbUrl == null){
315 throw new PAPException("papDbUrl is null");
317 } catch(Exception e){
318 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
322 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
323 if(papDbUser == null){
324 throw new PAPException("papDbUser is null");
327 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
331 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
332 if(papDbPassword == null){
333 throw new PAPException("papDbPassword is null");
336 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
340 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
342 //Integer will throw an exception of anything is missing or unrecognized
343 papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
344 papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
345 papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
347 //Boolean will default to false if anything is missing or unrecognized
348 papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
349 papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
352 autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG));
353 // if Auto push then Load with properties.
357 file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE);
358 if(file.endsWith(".properties")){
359 autoPushPolicy = new AutoPushPolicy(file);
361 throw new Exception();
364 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE );
365 logger.info("Overriding the autoPushFlag to False...");
366 autoPushFlag = false;
371 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
372 if(papResourceName == null){
373 throw new PAPException("papResourceName is null");
376 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
381 papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
382 if(papSiteName == null){
383 throw new PAPException("papSiteName is null");
386 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
390 papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
391 if(papNodeType == null){
392 throw new PAPException("papNodeType is null");
395 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
399 papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
400 if(papDependencyGroups == null){
401 throw new PAPException("papDependencyGroups is null");
403 //Now we have flattened the array into a simple comma-separated list
404 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
406 //clean up the entries
407 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
408 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
411 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
412 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
414 //nothing to do. The parameter is optional
417 String msg = "integrity_audit_period_seconds ";
418 logger.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
419 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
423 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
427 //Integer will throw an exception of anything is missing or unrecognized
428 fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
429 failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
430 testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
431 writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
433 logger.debug("\n\n\n**************************************"
434 + "\n**************************************"
436 + "\n papDbDriver = " + papDbDriver
437 + "\n papDbUrl = " + papDbUrl
438 + "\n papDbUser = " + papDbUser
439 + "\n papDbPassword = " + papDbPassword
440 + "\n papTransWait = " + papTransWait
441 + "\n papTransTimeout = " + papTransTimeout
442 + "\n papAuditTimeout = " + papAuditTimeout
443 + "\n papAuditFlag = " + papAuditFlag
444 + "\n papFileSystemAudit = " + papFileSystemAudit
445 + "\n autoPushFlag = " + autoPushFlag
446 + "\n papResourceName = " + papResourceName
447 + "\n fpMonitorInterval = " + fpMonitorInterval
448 + "\n failedCounterThreshold = " + failedCounterThreshold
449 + "\n testTransInterval = " + testTransInterval
450 + "\n writeFpcInterval = " + writeFpcInterval
451 + "\n papSiteName = " + papSiteName
452 + "\n papNodeType = " + papNodeType
453 + "\n papDependencyGroupsList = " + papDependencyGroups
454 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
455 + "\n\n**************************************"
456 + "\n**************************************");
459 // Pull custom persistence settings
462 Properties properties;
464 properties = XACMLProperties.getProperties();//XACMLRestProperties.getProperties();
465 logger.debug("\n\n\n**************************************"
466 + "\n**************************************"
468 + "properties = " + properties
469 + "\n\n**************************************");
471 } catch (IOException e) {
472 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
473 + "XACMLProperties.getProperties()");
474 throw new ServletException(e.getMessage(), e.getCause());
477 // Create an IntegrityMonitor
478 im = IntegrityMonitor.getInstance(papResourceName,properties);
480 // Create an IntegrityAudit
481 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
482 ia.startAuditThread();
485 // Create the entity manager factory
487 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
489 // Did it get created?
492 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
494 throw new ServletException("Unable to create Entity Manager Factory");
497 // we are about to call the PDPs and give them their configuration.
498 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
500 XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
502 * Create the PolicyDBDao singleton
504 //Create the policyDBDao
505 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
506 boolean performFileToDatabaseAudit = false;
507 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
508 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG))){
509 //get an AuditTransaction to lock out all other transactions
510 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
511 policyDBDao.auditLocalFileSystem();
512 //release the transaction lock
515 performFileToDatabaseAudit = true;
522 // Load our PAP engine, first create a factory
524 ECOMPPapEngineFactory factory = ECOMPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
526 // The factory knows how to go about creating a PAP Engine
528 this.papEngine = (PAPPolicyEngine) factory.newEngine();
529 PolicyDBDaoTransaction addNewGroup = null;
532 if(((org.openecomp.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){
533 addNewGroup = policyDBDao.getNewTransaction();
534 EcompPDPGroup group = papEngine.getDefaultGroup();
535 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
536 addNewGroup.commitTransaction();
537 addNewGroup = policyDBDao.getNewTransaction();
538 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
539 addNewGroup.commitTransaction();
542 } catch(Exception e){
543 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database");
544 if(addNewGroup != null){
545 addNewGroup.rollbackTransaction();
549 policyDBDao.setPapEngine((PAPPolicyEngine) this.papEngine);
552 if(performFileToDatabaseAudit){
553 //get an AuditTransaction to lock out all other transactions
554 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
555 policyDBDao.auditLocalDatabase((PAPPolicyEngine) this.papEngine);
556 //release the transaction lock
561 // PDPId File location
563 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
564 if (XACMLPapServlet.pdpFile == null) {
565 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE +
566 " The PDP Id Authentication File Property is not valid: "
567 + XACMLRestProperties.PROP_PDP_IDFILE);
568 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
571 // Sanity check that a URL was defined somewhere, its essential.
573 // How to check that its valid? We can validate the form, but since we are in the init() method we
574 // are not fully loaded yet so we really couldn't ping ourself to see if the URL will work. One
575 // will have to look for errors in the PDP logs to determine if they are failing to initiate a
576 // request to this servlet.
578 if (XACMLPapServlet.papURL == null) {
580 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
583 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
584 // to all its known PDP nodes.
586 // Note: parseBoolean will return false if there is no property defined. This is fine for a default.
588 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
589 this.initiateThread = new Thread(this);
590 this.initiateThread.start();
593 // After startup, the PAP does Heartbeats to each of the PDPs periodically
595 XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) this.papEngine);
596 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
597 XACMLPapServlet.heartbeatThread.start();
598 } catch (FactoryException | PAPException e) {
599 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
600 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
601 } catch (Exception e) {
602 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
603 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e); }
607 * Thread used only during PAP startup to initiate change messages to all known PDPs.
608 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
613 // send the current configuration to all the PDPs that we know about
620 * @see Servlet#destroy()
622 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
623 * For now we assume that we do care.
625 public void destroy() {
627 // Make sure our threads are destroyed
629 if (XACMLPapServlet.heartbeatThread != null) {
631 // stop the heartbeat
634 if (XACMLPapServlet.heartbeat != null) {
635 XACMLPapServlet.heartbeat.terminate();
637 XACMLPapServlet.heartbeatThread.interrupt();
638 XACMLPapServlet.heartbeatThread.join();
639 } catch (InterruptedException e) {
640 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
643 if (this.initiateThread != null) {
645 this.initiateThread.interrupt();
646 this.initiateThread.join();
647 } catch (InterruptedException e) {
648 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
656 * - PDP nodes to register themselves with the PAP, and
657 * - Admin Console to make changes in the PDP Groups.
659 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
661 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
662 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
664 loggingContext.transactionStarted();
665 loggingContext.setServiceName("PAP.post"); // we may set a more specific value later
666 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
667 UUID requestID = UUID.randomUUID();
668 loggingContext.setRequestID(requestID.toString());
669 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
671 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
673 // dummy metric.log example posted below as proof of concept
674 loggingContext.metricStarted();
675 loggingContext.metricEnded();
676 PolicyLogger.metrics("Metric example posted here - 1 of 2");
677 loggingContext.metricStarted();
678 loggingContext.metricEnded();
679 PolicyLogger.metrics("Metric example posted here - 2 of 2");
680 // dummy metric.log example posted above as proof of concept
681 PolicyDBDaoTransaction pdpTransaction = null;
683 //This im.startTransaction() covers all Post transactions
685 im.startTransaction();
686 } catch (AdministrativeStateException ae){
687 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
688 + " state of " + im.getStateManager().getAdminState()
689 + "\n Exception Message: " + ae.getMessage();
690 logger.info(message);
691 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
692 loggingContext.transactionEnded();
694 PolicyLogger.audit("Transaction Failed - See Error.log");
696 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
698 }catch (StandbyStatusException se) {
699 se.printStackTrace();
700 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
701 + " of " + im.getStateManager().getStandbyStatus()
702 + "\n Exception Message: " + se.getMessage();
703 logger.info(message);
704 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
705 loggingContext.transactionEnded();
707 PolicyLogger.audit("Transaction Failed - See Error.log");
709 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
715 XACMLRest.dumpRequest(request);
717 // since getParameter reads the content string, explicitly get the content before doing that.
718 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
719 request.getInputStream();
722 String groupId = request.getParameter("groupId");
723 String apiflag = request.getParameter("apiflag");
725 if (groupId != null) {
726 // Is this from the Admin Console or API?
728 if (apiflag.equalsIgnoreCase("api")) {
729 // this is from the API so we need to check the client credentials before processing the request
730 if(authorizeRequest(request)){
731 doACPost(request, response, groupId, loggingContext);
732 // Mike B - ended loggingContext transacton & added EELF 'Success' EELF Audit.log message
733 loggingContext.transactionEnded();
734 PolicyLogger.audit("Transaction Ended Successfully");
738 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
739 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
740 loggingContext.transactionEnded();
742 PolicyLogger.audit("Transaction Failed - See Error.log");
744 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
751 // this is from the Admin Console, so handle separately
752 doACPost(request, response, groupId, loggingContext);
753 loggingContext.transactionEnded();
754 PolicyLogger.audit("Transaction Ended Successfully");
762 // Request is from a PDP.
763 // It is coming up and asking for its config
765 loggingContext.setServiceName("PDP:PAP.register");
771 String id = this.getPDPID(request);
772 String jmxport = this.getPDPJMX(request);
773 //logger.info("doPost from: " + id);
774 logger.info("Request(doPost) from PDP coming up: " + id);
776 // Get the PDP Object
778 EcompPDP pdp = this.papEngine.getPDP(id);
783 logger.info("Unknown PDP: " + id);
784 // PDP ID Check is performed Here.
785 if(CheckPDP.validateID(id)){
786 pdpTransaction = policyDBDao.getNewTransaction();
788 //this.papEngine.newPDP(id, this.papEngine.getDefaultGroup(), id, "Registered on first startup");
789 pdpTransaction.addPdpToGroup(id, this.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
790 this.papEngine.newPDP(id, this.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
791 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) {
792 pdpTransaction.rollbackTransaction();
793 String message = "Failed to create new PDP for id: " + id;
794 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
795 loggingContext.transactionEnded();
797 PolicyLogger.audit("Transaction Failed - See Error.log");
799 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
800 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
804 // get the PDP we just created
805 pdp = this.papEngine.getPDP(id);
807 if(pdpTransaction != null){
808 pdpTransaction.rollbackTransaction();
810 String message = "Failed to create new PDP for id: " + id;
811 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
812 loggingContext.transactionEnded();
814 PolicyLogger.audit("Transaction Failed - See Error.log");
815 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
820 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
821 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
822 loggingContext.transactionEnded();
823 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
824 PolicyLogger.audit("Transaction Failed - See Error.log");
828 // get the PDP we just created
829 pdp = this.papEngine.getPDP(id);
831 if(pdpTransaction != null){
832 pdpTransaction.rollbackTransaction();
834 String message = "Failed to create new PDP for id: " + id;
835 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
836 loggingContext.transactionEnded();
837 PolicyLogger.audit("Transaction Failed - See Error.log");
838 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
843 pdpTransaction.commitTransaction();
844 } catch(Exception e){
845 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
849 if (jmxport != null && jmxport != ""){
850 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
854 // Get the PDP's Group
856 EcompPDPGroup group = this.papEngine.getPDPGroup((EcompPDP) pdp);
858 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
859 loggingContext.transactionEnded();
860 PolicyLogger.audit("Transaction Failed - See Error.log");
861 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
866 // Determine what group the PDP node is in and get
867 // its policy/pip properties.
869 Properties policies = group.getPolicyProperties();
870 Properties pipconfig = group.getPipConfigProperties();
872 // Get the current policy/pip configuration that the PDP has
874 Properties pdpProperties = new Properties();
875 pdpProperties.load(request.getInputStream());
876 logger.info("PDP Current Properties: " + pdpProperties.toString());
877 logger.info("Policies: " + (policies != null ? policies.toString() : "null"));
878 logger.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
880 // Validate the node's properties
882 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
884 // Send back current configuration
886 if (isCurrent == false) {
888 // Tell the PDP we are sending back the current policies/pip config
890 logger.info("PDP configuration NOT current.");
891 if (policies != null) {
893 // Put URL's into the properties in case the PDP needs to
896 this.populatePolicyURL(request.getRequestURL(), policies);
898 // Copy the properties to the output stream
900 policies.store(response.getOutputStream(), "");
902 if (pipconfig != null) {
904 // Copy the properties to the output stream
906 pipconfig.store(response.getOutputStream(), "");
909 // We are good - and we are sending them information
911 response.setStatus(HttpServletResponse.SC_OK);
913 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
916 // Tell them they are good
918 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
920 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
924 // tell the AC that something changed
927 loggingContext.transactionEnded();
928 auditLogger.info("Success");
929 PolicyLogger.audit("Transaction Ended Successfully");
930 } catch (PAPException e) {
931 if(pdpTransaction != null){
932 pdpTransaction.rollbackTransaction();
934 logger.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
935 loggingContext.transactionEnded();
937 PolicyLogger.audit("Transaction Failed - See Error.log");
939 response.sendError(500, e.getMessage());
943 //Catch anything that fell through
944 loggingContext.transactionEnded();
945 PolicyLogger.audit("Transaction Ended");
950 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
952 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
953 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
954 loggingContext.transactionStarted();
955 loggingContext.setServiceName("PAP.get"); // we may set a more specific value later
956 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
957 UUID requestID = UUID.randomUUID();
958 loggingContext.setRequestID(requestID.toString());
959 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
961 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
963 // dummy metric.log example posted below as proof of concept
964 loggingContext.metricStarted();
965 loggingContext.metricEnded();
966 PolicyLogger.metrics("Metric example posted here - 1 of 2");
967 loggingContext.metricStarted();
968 loggingContext.metricEnded();
969 PolicyLogger.metrics("Metric example posted here - 2 of 2");
970 // dummy metric.log example posted above as proof of concept
972 XACMLRest.dumpRequest(request);
973 String pathInfo = request.getRequestURI();
974 logger.info("path info: " + pathInfo);
975 if (pathInfo != null){
976 //DO NOT do a im.startTransaction for the test request
977 if (pathInfo.equals("/pap/test")) {
978 logger.info("Test request received");
981 //If we make it this far, all is well
982 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
983 logger.info(message);
984 loggingContext.transactionEnded();
985 PolicyLogger.audit("Transaction Failed - See Error.log");
986 response.setStatus(HttpServletResponse.SC_OK);
988 }catch (ForwardProgressException fpe){
989 //No forward progress is being made
990 String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
991 + " Exception Message: " + fpe.getMessage();
992 logger.info(message);
993 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
994 loggingContext.transactionEnded();
996 PolicyLogger.audit("Transaction Failed - See Error.log");
997 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
999 }catch (AdministrativeStateException ase){
1000 //Administrative State is locked
1001 String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED "
1002 + " Exception Message: " + ase.getMessage();
1003 logger.info(message);
1004 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1005 loggingContext.transactionEnded();
1007 PolicyLogger.audit("Transaction Failed - See Error.log");
1008 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1010 }catch (StandbyStatusException sse){
1011 //Administrative State is locked
1012 String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE "
1013 + " Exception Message: " + sse.getMessage();
1014 logger.info(message);
1015 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1016 loggingContext.transactionEnded();
1018 PolicyLogger.audit("Transaction Failed - See Error.log");
1019 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1021 }catch (Exception e) {
1022 //A subsystem is not making progress, is locked, standby or is not responding
1023 String eMsg = e.getMessage();
1025 eMsg = "No Exception Message";
1027 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
1028 + " Exception Message: " + eMsg;
1029 logger.info(message);
1030 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1031 loggingContext.transactionEnded();
1033 PolicyLogger.audit("Transaction Failed - See Error.log");
1034 //Get the specific list of subsystems that failed
1035 String ssFailureList = null;
1036 for(String failedSS : papDependencyGroupsFlatArray){
1037 if(eMsg.contains(failedSS)){
1038 if(ssFailureList == null){
1039 ssFailureList = failedSS;
1041 ssFailureList = ssFailureList.concat(","+failedSS);
1045 if(ssFailureList == null){
1046 ssFailureList = "UnknownSubSystem";
1048 response.addHeader("X-ECOMP-SubsystemFailure", ssFailureList);
1049 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1055 //This im.startTransaction() covers all other Get transactions
1057 im.startTransaction();
1058 } catch (AdministrativeStateException ae){
1059 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
1060 + " state of " + im.getStateManager().getAdminState()
1061 + "\n Exception Message: " + ae.getMessage();
1062 logger.info(message);
1063 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1064 loggingContext.transactionEnded();
1066 PolicyLogger.audit("Transaction Failed - See Error.log");
1067 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1069 }catch (StandbyStatusException se) {
1070 se.printStackTrace();
1071 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
1072 + " of " + im.getStateManager().getStandbyStatus()
1073 + "\n Exception Message: " + se.getMessage();
1074 logger.info(message);
1075 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1076 loggingContext.transactionEnded();
1078 PolicyLogger.audit("Transaction Failed - See Error.log");
1079 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1084 // Request from the API to get the gitPath
1085 String apiflag = request.getParameter("apiflag");
1086 if (apiflag!=null) {
1087 if(authorizeRequest(request)){
1090 // Request from the API to get the gitPath
1091 if (apiflag.equalsIgnoreCase("gitPath")) {
1092 getGitPath(request, response);
1093 // Mike B - ended loggingContext transacton & added EELF 'Success' EELF Audit.log message
1094 loggingContext.transactionEnded();
1095 PolicyLogger.audit("Transaction Ended Successfully");
1096 im.endTransaction();
1100 // Request from the API to get the ActiveVersion from the PolicyVersion table
1101 if (apiflag.equalsIgnoreCase("version")){
1102 getActiveVersion(request, response);
1103 loggingContext.transactionEnded();
1104 PolicyLogger.audit("Transaction Ended Successfully");
1105 im.endTransaction();
1109 // Request from the API to get the URI from the gitpath
1110 if (apiflag.equalsIgnoreCase("uri")){
1111 getSelectedURI(request, response);
1112 loggingContext.transactionEnded();
1113 PolicyLogger.audit("Transaction Ended Successfully");
1114 im.endTransaction();
1119 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1120 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1121 loggingContext.transactionEnded();
1123 PolicyLogger.audit("Transaction Failed - See Error.log");
1124 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1125 im.endTransaction();
1132 // Is this from the Admin Console?
1133 String groupId = request.getParameter("groupId");
1134 if (groupId != null) {
1135 // this is from the Admin Console, so handle separately
1136 doACGet(request, response, groupId, loggingContext);
1137 loggingContext.transactionEnded();
1138 PolicyLogger.audit("Transaction Ended Successfully");
1139 im.endTransaction();
1146 String id = this.getPDPID(request);
1147 logger.info("doGet from: " + id);
1149 // Get the PDP Object
1151 EcompPDP pdp = this.papEngine.getPDP(id);
1157 // Check if request came from localhost
1159 if (request.getRemoteHost().equals("localhost") ||
1160 request.getRemoteHost().equals("127.0.0.1") ||
1161 request.getRemoteHost().equals(request.getLocalAddr())) {
1163 // Return status information - basically all the groups
1165 loggingContext.setServiceName("PAP.getGroups");
1166 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
1168 // convert response object to JSON and include in the response
1169 ObjectMapper mapper = new ObjectMapper();
1170 mapper.writeValue(response.getOutputStream(), groups);
1171 response.setHeader("content-type", "application/json");
1172 response.setStatus(HttpServletResponse.SC_OK);
1173 loggingContext.transactionEnded();
1174 PolicyLogger.audit("Transaction Ended Successfully");
1175 im.endTransaction();
1178 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
1179 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1180 loggingContext.transactionEnded();
1182 PolicyLogger.audit("Transaction Failed - See Error.log");
1183 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
1184 im.endTransaction();
1188 loggingContext.setServiceName("PAP.getPolicy");
1191 // Get the PDP's Group
1193 EcompPDPGroup group = this.papEngine.getPDPGroup((EcompPDP) pdp);
1194 if (group == null) {
1195 String message = "No group associated with pdp " + pdp.getId();
1196 logger.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
1197 loggingContext.transactionEnded();
1199 PolicyLogger.audit("Transaction Failed - See Error.log");
1200 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
1201 im.endTransaction();
1205 // Which policy do they want?
1207 String policyId = request.getParameter("id");
1208 if (policyId == null) {
1209 String message = "Did not specify an id for the policy";
1210 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
1211 loggingContext.transactionEnded();
1213 PolicyLogger.audit("Transaction Failed - See Error.log");
1214 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1215 im.endTransaction();
1218 PDPPolicy policy = group.getPolicy(policyId);
1219 if (policy == null) {
1220 String message = "Unknown policy: " + policyId;
1221 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
1222 loggingContext.transactionEnded();
1224 PolicyLogger.audit("Transaction Failed - See Error.log");
1225 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1226 im.endTransaction();
1232 logger.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
1233 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString() );
1234 try (InputStream is = policy.getStream(); OutputStream os = response.getOutputStream()) {
1236 // Send the policy back
1238 IOUtils.copy(is, os);
1240 response.setStatus(HttpServletResponse.SC_OK);
1241 loggingContext.transactionEnded();
1242 auditLogger.info("Success");
1243 PolicyLogger.audit("Transaction Ended Successfully");
1244 } catch (PAPException e) {
1245 String message = "Failed to open policy id " + policyId;
1246 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1247 loggingContext.transactionEnded();
1248 PolicyLogger.audit("Transaction Failed - See Error.log");
1249 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1251 } catch (PAPException e) {
1252 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
1253 loggingContext.transactionEnded();
1255 PolicyLogger.audit("Transaction Failed - See Error.log");
1256 response.sendError(500, e.getMessage());
1257 im.endTransaction();
1260 loggingContext.transactionEnded();
1261 PolicyLogger.audit("Transaction Ended");
1262 im.endTransaction();
1267 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1272 * @param loggingContext
1273 * @throws ServletException
1274 * @throws IOException
1276 private void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws IOException {
1277 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1281 // for PUT operations the group may or may not need to exist before the operation can be done
1282 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1284 // get the request content into a String
1287 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1288 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1289 scanner.useDelimiter("\\A");
1290 json = scanner.hasNext() ? scanner.next() : "";
1292 logger.info("JSON request from PolicyEngine API: " + json);
1294 // convert Object sent as JSON into local object
1295 ObjectMapper mapper = new ObjectMapper();
1297 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1299 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1301 Set<PDPPolicy> policies = new HashSet<PDPPolicy>();
1304 policies.add(policy);
1307 //Get the current policies from the Group and Add the new one
1308 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
1309 currentPoliciesInGroup = group.getPolicies();
1311 //If the selected policy is in the group we must remove it because the name is default
1312 Iterator<PDPPolicy> policyIterator = policies.iterator();
1313 logger.debug("policyIterator....." + policies);
1314 while (policyIterator.hasNext()) {
1315 PDPPolicy selPolicy = policyIterator.next();
1316 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
1317 if (existingPolicy.getId().equals(selPolicy.getId())) {
1318 group.removePolicyFromGroup(existingPolicy);
1319 logger.debug("Removing policy: " + existingPolicy);
1325 if(currentPoliciesInGroup!=null){
1326 policies.addAll(currentPoliciesInGroup);
1328 group.setPolicies(policies);
1330 // Assume that this is an update of an existing PDP Group
1331 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1334 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1335 } catch(Exception e){
1336 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1337 +"group="+group.getId());
1338 throw new PAPException(e.getMessage());
1341 papEngine.updateGroup(group);
1342 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1343 response.addHeader("operation", "push");
1344 response.addHeader("policyId", policy.getId());
1345 response.addHeader("groupId", groupId);
1346 if (logger.isDebugEnabled()) {
1347 logger.debug("Group '" + group.getId() + "' updated");
1350 acPutTransaction.commitTransaction();
1354 // Group changed, which might include changing the policies
1355 groupChanged(group);
1356 loggingContext.transactionEnded();
1357 auditLogger.info("Success");
1358 PolicyLogger.audit("Transaction Ended Successfully");
1360 } catch (PAPException e) {
1361 acPutTransaction.rollbackTransaction();
1362 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1363 loggingContext.transactionEnded();
1365 PolicyLogger.audit("Transaction Failed - See Error.log");
1367 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1368 response.sendError(500, e.getMessage());
1369 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1370 response.addHeader("error","addGroupError");
1371 response.addHeader("message", message);
1377 private void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
1378 //Setup EntityManager to communicate with the PolicyVersion table of the DB
1379 EntityManager em = null;
1380 em = (EntityManager) emf.createEntityManager();
1383 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + PERSISTENCE_UNIT);
1385 throw new Exception("Unable to create Entity Manager Factory");
1386 } catch (Exception e) {
1387 e.printStackTrace();
1391 String policyScope = request.getParameter("policyScope");
1392 String filePrefix = request.getParameter("filePrefix");
1393 String policyName = request.getParameter("policyName");
1395 String pvName = policyScope + File.separator + filePrefix + policyName;
1396 int activeVersion = 0;
1399 //Get the Active Version to use in the ID
1400 em.getTransaction().begin();
1401 Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
1402 query.setParameter("pname", pvName);
1404 @SuppressWarnings("rawtypes")
1405 List result = query.getResultList();
1406 PolicyVersion versionEntity = null;
1407 if (!result.isEmpty()) {
1408 versionEntity = (PolicyVersion) result.get(0);
1409 em.persist(versionEntity);
1410 activeVersion = versionEntity.getActiveVersion();
1411 em.getTransaction().commit();
1413 logger.debug("No PolicyVersion using policyName found");
1416 //clean up connection
1418 if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {
1419 response.setStatus(HttpServletResponse.SC_OK);
1420 response.addHeader("version", String.valueOf(activeVersion));
1422 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1428 private void getSelectedURI(HttpServletRequest request,
1429 HttpServletResponse response) {
1431 String gitPath = request.getParameter("gitPath");
1433 File file = new File(gitPath);
1435 logger.debug("The fileItem is : " + file.toString());
1437 URI selectedURI = file.toURI();
1439 String uri = selectedURI.toString();
1441 if (!uri.equalsIgnoreCase("")) {
1442 response.setStatus(HttpServletResponse.SC_OK);
1443 response.addHeader("selectedURI", uri);
1445 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1450 * getGitPath() method to get the gitPath using data from the JSON string
1451 * when deleting policies using doAPIDelete()
1453 private File getPolicyFile(String policyName){
1455 Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
1456 Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
1457 Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
1459 //getting the fullpath of the gitPath and convert to string
1460 String fullGitPath = gitPath.toAbsolutePath().toString();
1461 String finalGitPath = null;
1463 //creating the parentPath directory for the Admin Console use
1464 if(fullGitPath.contains("\\")){
1465 finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
1467 finalGitPath = fullGitPath.replace("pap", "console");
1470 finalGitPath += File.separator + policyName;
1472 File file = new File(finalGitPath);
1479 * getGitPath() method to get the gitPath using data from the http request
1480 * and send back in response when pushing policies
1482 private void getGitPath(HttpServletRequest request,
1483 HttpServletResponse response) {
1485 String policyScope = request.getParameter("policyScope");
1486 String filePrefix = request.getParameter("filePrefix");
1487 String policyName = request.getParameter("policyName");
1488 String activeVersion = request.getParameter("activeVersion");
1490 Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
1491 Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
1492 Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
1494 //getting the fullpath of the gitPath and convert to string
1495 String fullGitPath = gitPath.toAbsolutePath().toString();
1496 String finalGitPath = null;
1498 //creating the parentPath directory for the Admin Console use
1499 if(fullGitPath.contains("\\")){
1500 finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
1502 finalGitPath = fullGitPath.replace("pap", "console");
1505 finalGitPath += File.separator + policyScope + File.separator + filePrefix + policyName + "." + activeVersion + ".xml";
1506 File file = new File(finalGitPath);
1507 URI uri = file.toURI();
1510 // Extract XACML policy information
1512 Boolean isValid = false;
1513 String policyId = null;
1514 String description = null;
1515 String version = null;
1520 Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream());
1521 if (rootElement == null ||
1523 ! (rootElement instanceof PolicySetType) &&
1524 ! (rootElement instanceof PolicyType)
1526 logger.warn("No root policy element in URI: " + uri.toString() + " : " + rootElement);
1529 if (rootElement instanceof PolicySetType) {
1530 policyId = ((PolicySetType)rootElement).getPolicySetId();
1531 description = ((PolicySetType)rootElement).getDescription();
1533 version = ((PolicySetType)rootElement).getVersion();
1534 } else if (rootElement instanceof PolicyType) {
1535 policyId = ((PolicyType)rootElement).getPolicyId();
1536 description = ((PolicyType)rootElement).getDescription();
1537 version = ((PolicyType)rootElement).getVersion();
1540 PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName());
1543 } catch (Exception e) {
1544 logger.error("Exception Occured While Extracting Policy Information");
1547 if (!finalGitPath.equalsIgnoreCase("") || policyId!=null || description!=null || version!=null || isValid!=null) {
1548 response.setStatus(HttpServletResponse.SC_OK);
1549 response.addHeader("gitPath", finalGitPath);
1550 response.addHeader("policyId", policyId);
1551 response.addHeader("description", description);
1552 response.addHeader("version", version);
1553 response.addHeader("isValid", isValid.toString());
1555 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1561 * Given a version string consisting of integers with dots between them, convert it into an array of ints.
1565 * @throws NumberFormatException
1567 public static int[] versionStringToArray(String version) throws NumberFormatException {
1568 if (version == null || version.length() == 0) {
1571 String[] stringArray = version.split("\\.");
1572 int[] resultArray = new int[stringArray.length];
1573 for (int i = 0; i < stringArray.length; i++) {
1574 resultArray[i] = Integer.parseInt(stringArray[i]);
1579 protected String getPDPID(HttpServletRequest request) {
1580 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1581 if (pdpURL == null || pdpURL.isEmpty()) {
1583 // Should send back its port for identification
1585 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1591 protected String getPDPJMX(HttpServletRequest request) {
1592 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1593 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1595 // Should send back its port for identification
1597 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1602 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1603 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1604 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1605 if (localRootPolicies == null || localReferencedPolicies == null) {
1606 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1610 // Compare the policies and pipconfig properties to the pdpProperties
1614 // the policy properties includes only xacml.rootPolicies and
1615 // xacml.referencedPolicies without any .url entries
1617 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1618 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1619 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1620 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1621 pdpPipConfig.equals(pipconfig)) {
1623 // The PDP is current
1627 } catch (Exception e) {
1628 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1629 // or if there are policies that do not have a corresponding ".url" property.
1630 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1631 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1636 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1637 String lists[] = new String[2];
1638 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1639 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1640 for (String list : lists) {
1641 if (list != null && list.isEmpty() == false) {
1642 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1643 String url = urlPath + "?id=" + id;
1644 logger.info("Policy URL for " + id + ": " + url);
1645 policies.setProperty(id + ".url", url);
1653 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1655 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1656 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1657 storedRequestId = loggingContext.getRequestID();
1658 loggingContext.transactionStarted();
1659 loggingContext.setServiceName("PAP.put"); // we may set a more specific value later
1660 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1661 UUID requestID = UUID.randomUUID();
1662 loggingContext.setRequestID(requestID.toString());
1663 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
1665 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
1667 // dummy metric.log example posted below as proof of concept
1668 loggingContext.metricStarted();
1669 loggingContext.metricEnded();
1670 PolicyLogger.metrics("Metric example posted here - 1 of 2");
1671 loggingContext.metricStarted();
1672 loggingContext.metricEnded();
1673 PolicyLogger.metrics("Metric example posted here - 2 of 2");
1674 //This im.startTransaction() covers all Put transactions
1676 im.startTransaction();
1677 } catch (AdministrativeStateException ae){
1678 String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative"
1679 + " state of " + im.getStateManager().getAdminState()
1680 + "\n Exception Message: " + ae.getMessage();
1681 logger.info(message);
1682 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1683 loggingContext.transactionEnded();
1685 PolicyLogger.audit("Transaction Failed - See Error.log");
1686 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1688 }catch (StandbyStatusException se) {
1689 se.printStackTrace();
1690 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1691 + " of " + im.getStateManager().getStandbyStatus()
1692 + "\n Exception Message: " + se.getMessage();
1693 logger.info(message);
1694 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1695 loggingContext.transactionEnded();
1697 PolicyLogger.audit("Transaction Failed - See Error.log");
1698 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1702 XACMLRest.dumpRequest(request);
1705 // since getParameter reads the content string, explicitly get the content before doing that.
1706 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
1708 request.getInputStream();
1710 //need to check if request is from the API or Admin console
1711 String apiflag = request.getParameter("apiflag");
1713 //This would occur if a PolicyDBDao notification was received
1714 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1715 if(policyDBDaoRequestUrl != null){
1716 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1717 //String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1718 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1719 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1720 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1721 response.sendError(400, "entityid or entitytype not supplied");
1722 loggingContext.transactionEnded();
1723 PolicyLogger.audit("Transaction Ended Successfully");
1724 im.endTransaction();
1727 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1728 response.setStatus(200);
1729 loggingContext.transactionEnded();
1730 PolicyLogger.audit("Transaction Ended Successfully");
1731 im.endTransaction();
1735 //This would occur if we received a notification of a policy creation or update
1736 String policyToCreateUpdate = request.getParameter("policyToCreateUpdate");
1737 if(policyToCreateUpdate != null){
1738 if(logger.isDebugEnabled()){
1739 logger.debug("\nXACMLPapServlet.doPut() - before decoding"
1740 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
1744 policyToCreateUpdate = URLDecoder.decode(policyToCreateUpdate, "UTF-8");
1745 if(logger.isDebugEnabled()){
1746 logger.debug("\nXACMLPapServlet.doPut() - after decoding"
1747 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
1749 } catch(UnsupportedEncodingException e){
1750 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1751 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
1752 response.sendError(500,"policyToCreateUpdate encoding not supported"
1753 + "\nfailure with the following exception: " + e);
1754 loggingContext.transactionEnded();
1755 PolicyLogger.audit("Transaction Failed - See error.log");
1756 im.endTransaction();
1760 //send it to PolicyDBDao
1761 PolicyDBDaoTransaction createUpdateTransaction = policyDBDao.getNewTransaction();
1763 createUpdateTransaction.createPolicy(policyToCreateUpdate, "XACMLPapServlet.doPut");
1764 }catch(Exception e){
1765 createUpdateTransaction.rollbackTransaction();
1766 response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1767 + "\nfailure with the following exception: " + e);
1768 loggingContext.transactionEnded();
1769 PolicyLogger.audit("Transaction Failed - See error.log");
1770 im.endTransaction();
1773 createUpdateTransaction.commitTransaction();
1774 // Before sending Ok. Lets call AutoPush.
1776 Set<StdPDPGroup> changedGroups = autoPushPolicy.checkGroupsToPush(policyToCreateUpdate, this.papEngine);
1777 if(!changedGroups.isEmpty()){
1778 for(StdPDPGroup group: changedGroups){
1780 papEngine.updateGroup(group);
1781 if (logger.isDebugEnabled()) {
1782 logger.debug("Group '" + group.getId() + "' updated");
1785 // Group changed, which might include changing the policies
1786 groupChanged(group);
1787 }catch(Exception e){
1788 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Failed to Push policy. ");
1793 response.setStatus(HttpServletResponse.SC_OK);
1794 loggingContext.transactionEnded();
1795 PolicyLogger.audit("Transaction Ended Successfully");
1796 im.endTransaction();
1801 * Request for Micro Service Import
1803 String microServiceCreation = request.getParameter("importService");
1804 if (microServiceCreation != null) {
1805 if(authorizeRequest(request)){
1806 if (microServiceCreation.contains("MICROSERVICE")){
1807 doImportMicroServicePut(request, response);
1808 im.endTransaction();
1812 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1813 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1814 loggingContext.transactionEnded();
1815 PolicyLogger.audit("Transaction Failed - See Error.log");
1816 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1820 //This would occur if we received a notification of a policy rename from AC
1821 String oldPolicyName = request.getParameter("oldPolicyName");
1822 String newPolicyName = request.getParameter("newPolicyName");
1823 if(oldPolicyName != null && newPolicyName != null){
1824 if(logger.isDebugEnabled()){
1825 logger.debug("\nXACMLPapServlet.doPut() - before decoding"
1826 + "\npolicyToCreateUpdate = " + " ");
1830 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
1831 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
1832 if(logger.isDebugEnabled()){
1833 logger.debug("\nXACMLPapServlet.doPut() - after decoding"
1834 + "\npolicyToCreateUpdate = " + " ");
1836 } catch(UnsupportedEncodingException e){
1837 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1838 + "\npolicyToCreateUpdate = " + " ");
1839 response.sendError(500,"policyToCreateUpdate encoding not supported"
1840 + "\nfailure with the following exception: " + e);
1841 loggingContext.transactionEnded();
1842 PolicyLogger.audit("Transaction Failed - See error.log");
1843 im.endTransaction();
1846 //send it to PolicyDBDao
1847 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1849 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1850 }catch(Exception e){
1851 renameTransaction.rollbackTransaction();
1852 response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1853 + "\nfailure with the following exception: " + e);
1854 loggingContext.transactionEnded();
1855 PolicyLogger.audit("Transaction Failed - See error.log");
1856 im.endTransaction();
1859 renameTransaction.commitTransaction();
1860 response.setStatus(HttpServletResponse.SC_OK);
1861 loggingContext.transactionEnded();
1862 PolicyLogger.audit("Transaction Ended Successfully");
1863 im.endTransaction();
1869 // See if this is Admin Console registering itself with us
1871 String acURLString = request.getParameter("adminConsoleURL");
1872 if (acURLString != null) {
1873 loggingContext.setServiceName("AC:PAP.register");
1875 // remember this Admin Console for future updates
1877 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1878 adminConsoleURLStringList.add(acURLString);
1880 if (logger.isDebugEnabled()) {
1881 logger.debug("Admin Console registering with URL: " + acURLString);
1883 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1884 loggingContext.transactionEnded();
1885 auditLogger.info("Success");
1886 PolicyLogger.audit("Transaction Ended Successfully");
1887 im.endTransaction();
1892 * This is to update the PDP Group with the policy/policies being pushed
1893 * Part of a 2 step process to push policie to the PDP that can now be done
1894 * From both the Admin Console and the PolicyEngine API
1896 String groupId = request.getParameter("groupId");
1897 if (groupId != null) {
1899 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1900 updateGroupsFromAPI(request, response, groupId, loggingContext);
1901 loggingContext.transactionEnded();
1902 PolicyLogger.audit("Transaction Ended Successfully");
1903 im.endTransaction();
1908 // this is from the Admin Console, so handle separately
1910 doACPut(request, response, groupId, loggingContext);
1911 loggingContext.transactionEnded();
1912 PolicyLogger.audit("Transaction Ended Successfully");
1913 im.endTransaction();
1918 // Request is for policy validation and creation
1920 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1922 * this request is from the Admin Console
1924 loggingContext.transactionEnded();
1925 PolicyLogger.audit("Transaction Ended Successfully");
1926 doACPolicyPut(request, response);
1927 im.endTransaction();
1930 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1932 * this request is from the Policy Creation API
1934 // Authenticating the Request here.
1935 if(authorizeRequest(request)){
1936 loggingContext.transactionEnded();
1937 PolicyLogger.audit("Transaction Ended Successfully");
1938 doPolicyAPIPut(request, response);
1939 im.endTransaction();
1942 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1943 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1944 loggingContext.transactionEnded();
1946 PolicyLogger.audit("Transaction Failed - See Error.log");
1947 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1948 im.endTransaction();
1956 // We do not expect anything from anywhere else.
1957 // This method is here in case we ever need to support other operations.
1959 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1960 loggingContext.transactionEnded();
1962 PolicyLogger.audit("Transaction Failed - See Error.log");
1963 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1964 loggingContext.transactionEnded();
1965 PolicyLogger.audit("Transaction Failed - See error.log");
1966 im.endTransaction();
1970 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1972 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1973 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1974 loggingContext.transactionStarted();
1975 loggingContext.setServiceName("PAP.delete"); // we may set a more specific value later
1976 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1977 UUID requestID = UUID.randomUUID();
1978 loggingContext.setRequestID(requestID.toString());
1979 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1981 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1983 loggingContext.metricStarted();
1984 loggingContext.metricEnded();
1985 PolicyLogger.metrics("Metric example posted here - 1 of 2");
1986 loggingContext.metricStarted();
1987 loggingContext.metricEnded();
1988 PolicyLogger.metrics("Metric example posted here - 2 of 2");
1990 //This im.startTransaction() covers all Delete transactions
1992 im.startTransaction();
1993 } catch (AdministrativeStateException ae){
1994 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1995 + " state of " + im.getStateManager().getAdminState()
1996 + "\n Exception Message: " + ae.getMessage();
1997 logger.info(message);
1998 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1999 loggingContext.transactionEnded();
2001 PolicyLogger.audit("Transaction Failed - See Error.log");
2002 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2004 }catch (StandbyStatusException se) {
2005 se.printStackTrace();
2006 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
2007 + " of " + im.getStateManager().getStandbyStatus()
2008 + "\n Exception Message: " + se.getMessage();
2009 logger.info(message);
2010 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2011 loggingContext.transactionEnded();
2013 PolicyLogger.audit("Transaction Failed - See Error.log");
2015 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2019 XACMLRest.dumpRequest(request);
2021 String groupId = request.getParameter("groupId");
2022 String apiflag = request.getParameter("apiflag");
2024 if (groupId != null) {
2025 // Is this from the Admin Console or API?
2027 if (apiflag.equalsIgnoreCase("deletePapApi")) {
2028 // this is from the API so we need to check the client credentials before processing the request
2029 if(authorizeRequest(request)){
2030 doAPIDeleteFromPAP(request, response, loggingContext);
2033 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
2034 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
2035 loggingContext.transactionEnded();
2037 PolicyLogger.audit("Transaction Failed - See Error.log");
2038 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
2041 } else if (apiflag.equalsIgnoreCase("deletePdpApi")) {
2042 if(authorizeRequest(request)){
2043 doAPIDeleteFromPDP(request, response, loggingContext);
2046 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
2047 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
2048 loggingContext.transactionEnded();
2050 PolicyLogger.audit("Transaction Failed - See Error.log");
2051 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
2057 // this is from the Admin Console, so handle separately
2058 doACDelete(request, response, groupId, loggingContext);
2059 loggingContext.transactionEnded();
2060 PolicyLogger.audit("Transaction Ended Successfully");
2061 im.endTransaction();
2066 // We do not expect anything from anywhere else.
2067 // This method is here in case we ever need to support other operations.
2069 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
2070 loggingContext.transactionEnded();
2072 PolicyLogger.audit("Transaction Failed - See Error.log");
2074 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
2076 //Catch anything that fell through
2077 im.endTransaction();
2081 // Admin Console request handling
2085 * Requests from the Admin Console to GET info about the Groups and PDPs
2090 * @param loggingContext
2091 * @throws ServletException
2092 * @throws IOException
2094 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
2096 String parameterDefault = request.getParameter("default");
2097 String pdpId = request.getParameter("pdpId");
2098 String pdpGroup = request.getParameter("getPDPGroup");
2099 if ("".equals(groupId)) {
2100 // request IS from AC but does not identify a group by name
2101 if (parameterDefault != null) {
2102 // Request is for the Default group (whatever its id)
2103 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
2105 EcompPDPGroup group = papEngine.getDefaultGroup();
2107 // convert response object to JSON and include in the response
2108 ObjectMapper mapper = new ObjectMapper();
2109 mapper.writeValue(response.getOutputStream(), group);
2111 if (logger.isDebugEnabled()) {
2112 logger.debug("GET Default group req from '" + request.getRequestURL() + "'");
2114 response.setStatus(HttpServletResponse.SC_OK);
2115 response.setHeader("content-type", "application/json");
2116 response.getOutputStream().close();
2117 loggingContext.transactionEnded();
2118 auditLogger.info("Success");
2119 PolicyLogger.audit("Transaction Ended Successfully");
2122 } else if (pdpId != null) {
2123 // Request is related to a PDP
2124 if (pdpGroup == null) {
2125 // Request is for the PDP itself
2126 // Request is for the (unspecified) group containing a given PDP
2127 loggingContext.setServiceName("AC:PAP.getPDP");
2128 EcompPDP pdp = papEngine.getPDP(pdpId);
2130 // convert response object to JSON and include in the response
2131 ObjectMapper mapper = new ObjectMapper();
2132 mapper.writeValue(response.getOutputStream(), pdp);
2134 if (logger.isDebugEnabled()) {
2135 logger.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
2137 response.setStatus(HttpServletResponse.SC_OK);
2138 response.setHeader("content-type", "application/json");
2139 response.getOutputStream().close();
2140 loggingContext.transactionEnded();
2141 auditLogger.info("Success");
2142 PolicyLogger.audit("Transaction Ended Successfully");
2146 // Request is for the group containing a given PDP
2147 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
2148 EcompPDP pdp = papEngine.getPDP(pdpId);
2149 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
2151 // convert response object to JSON and include in the response
2152 ObjectMapper mapper = new ObjectMapper();
2153 mapper.writeValue(response.getOutputStream(), group);
2155 if (logger.isDebugEnabled()) {
2156 logger.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
2158 response.setStatus(HttpServletResponse.SC_OK);
2159 response.setHeader("content-type", "application/json");
2160 response.getOutputStream().close();
2161 loggingContext.transactionEnded();
2162 auditLogger.info("Success");
2163 PolicyLogger.audit("Transaction Ended Successfully");
2168 // request is for top-level properties about all groups
2169 loggingContext.setServiceName("AC:PAP.getAllGroups");
2170 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
2172 // convert response object to JSON and include in the response
2173 ObjectMapper mapper = new ObjectMapper();
2174 mapper.writeValue(response.getOutputStream(), groups);
2176 if (logger.isDebugEnabled()) {
2177 logger.debug("GET All groups req");
2179 response.setStatus(HttpServletResponse.SC_OK);
2180 response.setHeader("content-type", "application/json");
2181 response.getOutputStream().close();
2182 loggingContext.transactionEnded();
2183 auditLogger.info("Success");
2184 PolicyLogger.audit("Transaction Ended Successfully");
2189 // for all other GET operations the group must exist before the operation can be done
2190 EcompPDPGroup group = papEngine.getGroup(groupId);
2191 if (group == null) {
2192 String message = "Unknown groupId '" + groupId + "'";
2193 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2194 loggingContext.transactionEnded();
2196 PolicyLogger.audit("Transaction Failed - See Error.log");
2197 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
2202 // Figure out which request this is based on the parameters
2203 String policyId = request.getParameter("policyId");
2205 if (policyId != null) {
2206 // retrieve a policy
2207 loggingContext.setServiceName("AC:PAP.getPolicy");
2209 // convert response object to JSON and include in the response
2211 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
2212 loggingContext.transactionEnded();
2214 PolicyLogger.audit("Transaction Failed - See Error.log");
2216 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
2219 // No other parameters, so return the identified Group
2220 loggingContext.setServiceName("AC:PAP.getGroup");
2222 // convert response object to JSON and include in the response
2223 ObjectMapper mapper = new ObjectMapper();
2224 mapper.writeValue(response.getOutputStream(), group);
2226 if (logger.isDebugEnabled()) {
2227 logger.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
2229 response.setStatus(HttpServletResponse.SC_OK);
2230 response.setHeader("content-type", "application/json");
2231 response.getOutputStream().close();
2232 loggingContext.transactionEnded();
2233 auditLogger.info("Success");
2234 PolicyLogger.audit("Transaction Ended Successfully");
2239 // Currently there are no other GET calls from the AC.
2240 // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
2241 // Other GETs that could be called:
2242 // Specific Group (groupId=<groupId>)
2243 // A Policy (groupId=<groupId> policyId=<policyId>)
2244 // A PDP (groupId=<groupId> pdpId=<pdpId>)
2246 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
2247 loggingContext.transactionEnded();
2249 PolicyLogger.audit("Transaction Failed - See Error.log");
2251 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2252 } catch (PAPException e) {
2253 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
2254 loggingContext.transactionEnded();
2256 PolicyLogger.audit("Transaction Failed - See Error.log");
2257 response.sendError(500, e.getMessage());
2264 * Requests from the Admin Console for validating and creating policies
2269 * @throws JsonMappingException
2270 * @throws JsonParseException
2271 * @throws ServletException
2272 * @throws IOException
2274 private void doACPolicyPut(HttpServletRequest request,
2275 HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException {
2277 String operation = request.getParameter("operation");
2278 String policyType = request.getParameter("policyType");
2279 String apiflag = request.getParameter("apiflag");
2281 if ( policyType != null ) {
2282 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
2283 Policy newPolicy = null;
2284 // get the request content into a String
2286 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2287 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
2288 scanner.useDelimiter("\\A");
2289 json = scanner.hasNext() ? scanner.next() : "";
2291 logger.info("JSON request from AC: " + json);
2292 // convert Object sent as JSON into local object
2293 ObjectMapper mapper = new ObjectMapper();
2294 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
2296 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
2298 //Set policyAdapter values including parentPath (Common to all policy types)
2299 //Set values for policy adapter
2301 if (operation.equalsIgnoreCase("validate")) {
2302 policyAdapter.setPolicyName(policy.getPolicyName());
2303 policyAdapter.setConfigType(policy.getConfigType());
2304 policyAdapter.setConfigBodyData(policy.getConfigBodyData());
2306 policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
2308 } catch (Exception e1) {
2309 logger.error("Exception occured While Setting Values for Policy Adapter"+e1);
2311 // Calling Component class per policy type
2312 if (policyType.equalsIgnoreCase("Config")) {
2313 String configPolicyType = policy.getConfigPolicyType();
2314 if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Firewall Config")) {
2315 newPolicy = new FirewallConfigPolicy(policyAdapter);
2317 else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Raw")) {
2318 newPolicy = new CreateBrmsRawPolicy(policyAdapter);
2319 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Param")) {
2320 policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
2321 newPolicy = new CreateBrmsParamPolicy(policyAdapter);
2323 else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Base")) {
2324 newPolicy = new ConfigPolicy(policyAdapter);
2325 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_Fault")) {
2326 newPolicy = new ClosedLoopPolicy(policyAdapter);
2327 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_PM")) {
2328 newPolicy = new CreateClosedLoopPerformanceMetrics(policyAdapter);
2329 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("DCAE Micro Service")) {
2330 newPolicy = new MicroServiceConfigPolicy(policyAdapter);
2333 } else if (policyType.equalsIgnoreCase("Action")) {
2334 newPolicy = new ActionPolicy(policyAdapter);
2335 } else if (policyType.equalsIgnoreCase("Decision")) {
2336 newPolicy = new DecisionPolicy(policyAdapter);
2340 if (operation != null && operation.equalsIgnoreCase("validate")) {
2342 // validate the body data if applicable and return a response to the PAP-ADMIN (Config Base only)
2343 if (newPolicy.validateConfigForm()) {
2344 response.setStatus(HttpServletResponse.SC_OK);
2345 response.addHeader("isValidData", "true");
2347 response.setStatus(HttpServletResponse.SC_OK);
2348 response.addHeader("isValidData", "false");
2353 // Create or Update Policy
2354 if (operation != null && (operation.equalsIgnoreCase("create") || operation.equalsIgnoreCase("update"))) {
2356 // create the policy and return a response to the PAP-ADMIN
2357 PolicyDBDaoTransaction policyDBDaoTransaction = policyDBDao.getNewTransaction();
2359 Map<String, String> successMap;
2360 newPolicy.prepareToSave();
2361 policyDBDaoTransaction.createPolicy(newPolicy, "doACPolicyPut");
2362 successMap = newPolicy.savePolicies();
2363 if (successMap.containsKey("success")) {
2364 policyDBDaoTransaction.commitTransaction();
2365 response.setStatus(HttpServletResponse.SC_OK);
2366 response.addHeader("successMapKey", "success");
2367 response.addHeader("finalPolicyPath", policyAdapter.getFinalPolicyPath());
2369 policyDBDaoTransaction.rollbackTransaction();
2370 response.setStatus(HttpServletResponse.SC_OK);
2372 } catch (Exception e) {
2373 policyDBDaoTransaction.rollbackTransaction();
2374 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Could not save policy ");
2375 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2383 private void doPolicyAPIPut(HttpServletRequest request,
2384 HttpServletResponse response) throws IOException, ServletException {
2385 String operation = request.getParameter("operation");
2386 String policyType = request.getParameter("policyType");
2387 String apiflag = request.getParameter("apiflag");
2390 if ( policyType != null ) {
2391 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
2392 Policy newPolicy = null;
2394 // get the request content into a String
2397 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2398 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
2399 scanner.useDelimiter("\\A");
2400 json = scanner.hasNext() ? scanner.next() : "";
2402 logger.info("JSON request from API: " + json);
2404 // convert Object sent as JSON into local object
2405 ObjectMapper mapper = new ObjectMapper();
2407 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
2409 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
2411 //Set policyAdapter values including parentPath (Common to all policy types)
2413 policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
2414 } catch (Exception e1) {
2415 logger.error(XACMLErrorConstants.ERROR_UNKNOWN +
2416 "Could not set data to policy adapter ",e1);
2419 // Calling Component class per policy type
2420 if (policyType.equalsIgnoreCase("Config")) {
2421 String configPolicyType = policy.getConfigPolicyType();
2422 if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Firewall Config")) {
2424 newPolicy = new FirewallConfigPolicy(policyAdapter);
2427 else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Raw")) {
2429 newPolicy = new CreateBrmsRawPolicy(policyAdapter);
2431 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Param")) {
2433 policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
2434 //check for valid actionAttributes
2435 //Setup EntityManager to communicate with the PolicyVersion table of the DB
2436 EntityManager em = null;
2437 em = (EntityManager) emf.createEntityManager();
2439 Map<String,String> ruleAndUIValue=policyAdapter.getBrmsParamBody();
2440 String modelName= ruleAndUIValue.get("templateName");
2441 logger.info("Template name from API is: "+modelName);
2443 Query getModel = em.createNamedQuery("BRMSParamTemplate.findAll");
2444 List<?> modelList = getModel.getResultList();
2445 Boolean isValidService = false;
2446 for (Object id : modelList) {
2447 BRMSParamTemplate value = (BRMSParamTemplate)id;
2448 logger.info("Template value from dictionary is: "+value);
2449 if (modelName.equals(value.getRuleName())) {
2450 isValidService = true;
2457 if (isValidService) {
2458 newPolicy = new CreateBrmsParamPolicy(policyAdapter);
2460 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
2462 + " was not found in the dictionary.");
2463 response.addHeader("error", "missingTemplate");
2464 response.addHeader("modelName", modelName);
2465 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2469 else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Base")) {
2471 newPolicy = new ConfigPolicy(policyAdapter);
2473 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_Fault")) {
2475 newPolicy = new ClosedLoopPolicy(policyAdapter);
2477 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_PM")) {
2479 newPolicy = new CreateClosedLoopPerformanceMetrics(policyAdapter);
2481 }else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("DCAE Micro Service")) {
2483 //check for valid actionAttributes
2484 //Setup EntityManager to communicate with the PolicyVersion table of the DB
2485 EntityManager em = null;
2486 em = (EntityManager) emf.createEntityManager();
2488 String modelName = policy.getServiceType();
2489 String modelVersion = policy.getVersion();
2491 Query getModel = em.createNamedQuery("MicroServiceModels.findAll");
2492 List<?> modelList = getModel.getResultList();
2493 Boolean isValidService = false;
2494 for (Object id : modelList) {
2495 MicroServiceModels value = (MicroServiceModels)id;
2496 if (modelName.equals(value.getModelName()) && modelVersion.equals(value.getVersion())) {
2497 isValidService = true;
2504 if (isValidService) {
2505 newPolicy = new MicroServiceConfigPolicy(policyAdapter);
2507 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version. The Service Model, "
2508 + modelName + " of version " + modelVersion
2509 + " was not found in the dictionary.");
2510 response.addHeader("error", "serviceModelDB");
2511 response.addHeader("modelName", modelName);
2512 response.addHeader("modelVersion", modelVersion);
2513 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2519 } else if (policyType.equalsIgnoreCase("Action")) {
2521 //check for valid actionAttributes
2522 //Setup EntityManager to communicate with the PolicyVersion table of the DB
2523 EntityManager em = null;
2524 em = (EntityManager) emf.createEntityManager();
2526 String attributeName = policy.getActionAttribute();
2528 Query getActionAttributes = em.createNamedQuery("ActionPolicyDict.findAll");
2529 List<?> actionAttributesList = getActionAttributes.getResultList();
2530 Boolean isAttribute = false;
2531 for (Object id : actionAttributesList) {
2532 ActionPolicyDict value = (ActionPolicyDict)id;
2533 if (attributeName.equals(value.getAttributeName())) {
2542 newPolicy = new ActionPolicy(policyAdapter);
2544 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + attributeName + " in the ActionPolicyDict table.");
2545 response.addHeader("error", "actionPolicyDB");
2546 response.addHeader("actionAttribute", attributeName);
2547 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2551 } else if (policyType.equalsIgnoreCase("Decision")) {
2553 newPolicy = new DecisionPolicy(policyAdapter);
2557 // Create or Update Policy
2558 if (operation != null && (operation.equalsIgnoreCase("create") || operation.equalsIgnoreCase("update"))) {
2560 // create the policy and return a response to the PAP-ADMIN
2561 if (newPolicy.validateConfigForm()) {
2562 PolicyDBDaoTransaction policyDBDaoTransaction = policyDBDao.getNewTransaction();
2565 // added check for existing policy when new policy is created to
2566 // unique API error for "policy already exists"
2567 Boolean isNewPolicy = newPolicy.prepareToSave();
2569 policyDBDaoTransaction.createPolicy(newPolicy, "doPolicyAPIPut");
2571 Map<String, String> successMap = newPolicy.savePolicies();
2572 if (successMap.containsKey("success")) {
2574 EntityManager apiEm = null;
2575 apiEm = (EntityManager) emf.createEntityManager();
2577 // Did it get created?
2579 if (apiEm == null) {
2580 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + PERSISTENCE_UNIT);
2581 ServletException e = new ServletException("Unable to create Entity Manager Factory");
2582 e.printStackTrace();
2586 String finalPath = policyAdapter.getFinalPolicyPath();
2588 //Check the database entry if a scope is available in PolicyEditorScope table or not.
2589 //If not exists create a new entry.
2591 String dirName = finalPath.toString().substring(finalPath.toString().indexOf("repository")+11, finalPath.toString().lastIndexOf(File.separator));
2592 apiEm.getTransaction().begin();
2593 Query query = apiEm.createQuery("Select p from PolicyEditorScopes p where p.scopeName=:sname");
2594 query.setParameter("sname", dirName);
2596 @SuppressWarnings("rawtypes")
2597 List result = query.getResultList();
2598 if(result.isEmpty()){
2599 PolicyEditorScopes scopeEntity = new PolicyEditorScopes();
2600 scopeEntity.setScopeName(dirName);
2601 UserInfo user = new UserInfo();
2602 user.setUserLoginId("API");
2603 user.setUserName("API");
2604 scopeEntity.setUserCreatedBy(user);
2605 scopeEntity.setUserModifiedBy(user);
2607 apiEm.persist(scopeEntity);
2608 apiEm.getTransaction().commit();
2609 }catch(Exception e){
2610 PolicyLogger.error("Exception Occured while inserting a new Entry to PolicyEditorScopes table"+e);
2611 apiEm.getTransaction().rollback();
2616 PolicyLogger.info("Scope Already Exists in PolicyEditorScopes table, Hence Closing the Transaction");
2620 policyDBDaoTransaction.commitTransaction();
2621 response.setStatus(HttpServletResponse.SC_OK);
2622 response.addHeader("successMapKey", "success");
2623 response.addHeader("policyName", policyAdapter.getPolicyName());
2625 if (operation.equalsIgnoreCase("update")) {
2626 response.addHeader("operation", "update");
2628 response.addHeader("operation", "create");
2630 } else if (successMap.containsKey("EXISTS")) {
2631 policyDBDaoTransaction.rollbackTransaction();
2632 response.setStatus(HttpServletResponse.SC_CONFLICT);
2633 response.addHeader("error", "policyExists");
2634 response.addHeader("policyName", policyAdapter.getPolicyName());
2635 } else if (successMap.containsKey("fwdberror")) {
2636 policyDBDaoTransaction.rollbackTransaction();
2637 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2638 response.addHeader("error", "FWDBError");
2639 response.addHeader("policyName", policyAdapter.getPolicyName());
2641 policyDBDaoTransaction.rollbackTransaction();
2642 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
2643 response.addHeader("error", "error");
2645 } catch (Exception e) {
2646 policyDBDaoTransaction.rollbackTransaction();
2647 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW +
2648 "Could not save policy " + e;
2649 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Could not save policy");
2650 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
2651 response.addHeader("error", "savePolicy");
2652 response.addHeader("message", message);
2659 private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws Exception {
2660 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
2661 int highestVersion = 0;
2663 if (policy.getHighestVersion()!=null) {
2664 highestVersion = policy.getHighestVersion();
2667 EntityManager apiEm = null;
2668 apiEm = (EntityManager) emf.createEntityManager();
2671 // Did it get created?
2673 if (apiEm == null) {
2674 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE +
2675 " Error creating entity manager with persistence unit: "
2676 + PERSISTENCE_UNIT);
2677 throw new ServletException("Unable to create Entity Manager Factory");
2680 Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
2681 Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
2682 Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
2685 * Getting and Setting the parent path for Admin Console use when reading the policy files
2687 //domain chosen by the client to store the policy action files
2688 String domain = policy.getDomainDir();
2690 //adding the domain to the gitPath
2692 String gitPathString = gitPath.toString();
2694 if (gitPathString.contains("\\")) {
2695 path = Paths.get(gitPath + "\\" + policy.getDomainDir());
2697 path = Paths.get(gitPath + "/" + policy.getDomainDir());
2700 logger.debug("path is: " + path.toString());
2702 //getting the fullpath of the gitPath and convert to string
2703 String policyDir = path.toAbsolutePath().toString();
2704 String parentPath = null;
2706 //creating the parentPath directory for the Admin Console use
2708 if(policyDir.contains("\\"))
2710 parentPath = policyDir.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
2711 file = new File(parentPath);
2715 parentPath = policyDir.replace("pap", "console");
2716 file = new File(parentPath);
2720 //Get the policy file from the git repository
2721 String filePrefix = null;
2722 if (policyType.equalsIgnoreCase("Config")) {
2723 if (policy.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
2724 filePrefix = "Config_FW_";
2725 }else if (policy.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
2726 filePrefix = "Config_Fault_";
2727 }else if (policy.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
2728 filePrefix = "Config_PM_";
2729 }else if (policy.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
2730 filePrefix = "Config_MS_";
2731 } else if (policy.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) {
2732 filePrefix = "Config_BRMS_Raw_";
2733 } else if (policy.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) {
2734 filePrefix = "Config_BRMS_Param_";
2737 filePrefix = "Config_";
2739 } else if (policyType.equalsIgnoreCase("Action")) {
2740 filePrefix = "Action_";
2741 } else if (policyType.equalsIgnoreCase("Decision")) {
2742 filePrefix = "Decision_";
2746 String pvName = domain + File.separator + filePrefix + policy.getPolicyName();
2748 //create the directory if it does not exist
2749 Boolean fileDir=true;
2750 if (!file.exists()){
2751 fileDir = new File(parentPath).mkdirs();
2754 //set the parent path in the policy adapter
2756 logger.debug("Unable to create the policy directory");
2759 logger.debug("ParentPath is: " + parentPath.toString());
2760 policyAdapter.setParentPath(parentPath.toString());
2761 policyAdapter.setApiflag(apiflag);
2763 if (policy.isEditPolicy()) {
2765 if(apiflag.equalsIgnoreCase("api")) {
2767 //Get the Highest Version to Update
2768 apiEm.getTransaction().begin();
2769 Query query = apiEm.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
2770 query.setParameter("pname", pvName);
2772 @SuppressWarnings("rawtypes")
2773 List result = query.getResultList();
2774 PolicyVersion versionEntity = null;
2775 if (!result.isEmpty()) {
2776 versionEntity = (PolicyVersion) result.get(0);
2777 apiEm.persist(versionEntity);
2778 highestVersion = versionEntity.getHigherVersion();
2779 int activeVersion = versionEntity.getActiveVersion();
2781 Calendar calendar = Calendar.getInstance();
2782 Timestamp modifyDate = new Timestamp(calendar.getTime().getTime());
2784 //update table with highestVersion
2786 versionEntity.setHigherVersion(highestVersion+1);
2787 versionEntity.setActiveVersion(activeVersion+1);
2788 versionEntity.setCreatedBy("API");
2789 versionEntity.setModifiedBy("API");
2790 versionEntity.setModifiedDate(modifyDate);
2792 apiEm.getTransaction().commit();
2794 }catch(Exception e){
2795 apiEm.getTransaction().rollback();
2796 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
2801 logger.debug("\nNo PolicyVersion using policyName found");
2806 File policyFile = null;
2807 if(policy.getOldPolicyFileName() != null && policy.getOldPolicyFileName().endsWith("Draft.1")) {
2808 policyFile = new File(parentPath.toString() + File.separator + policy.getOldPolicyFileName() + ".xml");
2810 policyFile = new File(parentPath.toString() + File.separator + filePrefix + policy.getPolicyName() +"."+(highestVersion)+ ".xml");
2813 if (policyFile.exists()) {
2814 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
2815 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
2816 Document doc = dBuilder.parse(policyFile);
2818 doc.getDocumentElement().normalize();
2820 String version = doc.getDocumentElement().getAttribute("Version");
2822 NodeList rList = doc.getElementsByTagName("Rule");
2823 Node rNode = rList.item(0);
2824 Element rElement = (Element) rNode;
2826 String ruleID = null;
2828 ruleID = rElement.getAttribute("RuleId");
2830 ruleID = newRuleID();
2833 policyAdapter.setPolicyID(newPolicyID());
2834 policyAdapter.setRuleID(ruleID);
2835 policyAdapter.setVersion(version);
2838 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " The policy file at the path " + policyFile + " does not exist.");
2844 if (apiflag.equalsIgnoreCase("api")) {
2845 Calendar calendar = Calendar.getInstance();
2846 Timestamp createdDate = new Timestamp(calendar.getTime().getTime());
2848 apiEm.getTransaction().begin();
2849 Query query = apiEm.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
2850 query.setParameter("pname", pvName);
2852 @SuppressWarnings("rawtypes")
2853 List result = query.getResultList();
2855 if (result.isEmpty()) {
2858 PolicyVersion versionEntity = new PolicyVersion();
2859 apiEm.persist(versionEntity);
2860 versionEntity.setPolicyName(pvName);
2861 versionEntity.setHigherVersion(highestVersion);
2862 versionEntity.setActiveVersion(highestVersion);
2863 versionEntity.setCreatedBy("API");
2864 versionEntity.setModifiedBy("API");
2865 versionEntity.setCreatedDate(createdDate);
2866 versionEntity.setModifiedDate(createdDate);
2868 apiEm.getTransaction().commit();
2870 }catch(Exception e){
2871 apiEm.getTransaction().rollback();
2872 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
2879 policyAdapter.setPolicyID(newPolicyID());
2880 policyAdapter.setRuleID(newRuleID());
2885 * set policy adapter values for Building JSON object containing policy data
2887 //Common among policy types
2888 policyAdapter.setPolicyName(policy.getPolicyName());
2889 policyAdapter.setPolicyDescription(policy.getPolicyDescription());
2890 policyAdapter.setEcompName(policy.getEcompName()); //Config Base and Decision Policies
2891 policyAdapter.setHighestVersion(highestVersion);
2892 policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
2893 policyAdapter.setUserGitPath(gitPath.toString());
2894 policyAdapter.setPolicyType(policyType);
2895 policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes());
2896 policyAdapter.setEditPolicy(policy.isEditPolicy());
2897 policyAdapter.setEntityManagerFactory(getEmf());
2901 policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall
2902 policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
2903 policyAdapter.setConfigType(policy.getConfigType()); //Base
2904 policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop, and GoC
2905 policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
2906 policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
2907 policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
2908 policyAdapter.setUuid(policy.getUuid()); //Micro Service
2909 policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
2910 policyAdapter.setPriority(policy.getPriority()); //Micro Service
2911 policyAdapter.setPolicyScope(policy.getDomainDir());
2912 policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
2913 policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
2914 policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
2915 policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes
2917 //Action Policy Specific
2918 policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue
2919 policyAdapter.setActionPerformer(policy.getActionPerformer());
2920 policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
2921 policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
2922 policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
2923 policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());
2925 //Decision Policy Specific
2926 policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
2927 policyAdapter.setProviderComboBox(policy.getProviderComboBox());
2929 return policyAdapter;
2932 public String newPolicyID() {
2933 return Joiner.on(':').skipNulls().join((XACMLPapServlet.getDomain().startsWith("urn") ? null : "urn"),
2934 XACMLPapServlet.getDomain().replaceAll("[/\\\\.]", ":"),
2935 "xacml", "policy", "id", UUID.randomUUID());
2938 public String newRuleID() {
2939 return Joiner.on(':').skipNulls().join((XACMLPapServlet.getDomain().startsWith("urn") ? null : "urn"),
2940 XACMLPapServlet.getDomain().replaceAll("[/\\\\.]", ":"),
2941 "xacml", "rule", "id", UUID.randomUUID());
2944 public static String getDomain() {
2945 return XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DOMAIN, "urn");
2950 * Requests from the Admin Console for operations not on single specific objects
2955 * @param loggingContext
2956 * @throws ServletException
2957 * @throws IOException
2959 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
2960 PolicyDBDaoTransaction doACPostTransaction = null;
2963 String groupName = request.getParameter("groupName");
2964 String groupDescription = request.getParameter("groupDescription");
2965 String apiflag = request.getParameter("apiflag");
2967 if (groupName != null && groupDescription != null) {
2968 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
2969 loggingContext.setServiceName("AC:PAP.createGroup");
2971 String unescapedName = URLDecoder.decode(groupName, "UTF-8");
2972 String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
2973 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
2975 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
2976 papEngine.newGroup(unescapedName, unescapedDescription);
2977 newGroupTransaction.commitTransaction();
2978 } catch (Exception e) {
2979 newGroupTransaction.rollbackTransaction();
2980 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
2981 loggingContext.transactionEnded();
2983 PolicyLogger.audit("Transaction Failed - See Error.log");
2984 response.sendError(500, "Unable to create new group '" + groupId + "'");
2987 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2988 if (logger.isDebugEnabled()) {
2989 logger.debug("New Group '" + groupId + "' created");
2991 // tell the Admin Consoles there is a change
2993 // new group by definition has no PDPs, so no need to notify them of changes
2994 loggingContext.transactionEnded();
2995 PolicyLogger.audit("Transaction Failed - See Error.log");
2996 auditLogger.info("Success");
2997 PolicyLogger.audit("Transaction Ended Successfully");
3001 // for all remaining POST operations the group must exist before the operation can be done
3002 EcompPDPGroup group = papEngine.getGroup(groupId);
3003 if (group == null) {
3004 String message = "Unknown groupId '" + groupId + "'";
3005 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
3006 loggingContext.transactionEnded();
3008 PolicyLogger.audit("Transaction Failed - See Error.log");
3010 response.addHeader("error", "unknownGroupId");
3011 response.addHeader("operation", "push");
3012 response.addHeader("message", message);
3013 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
3015 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
3020 // determine the operation needed based on the parameters in the request
3021 if (request.getParameter("policyId") != null) {
3022 // Args: group=<groupId> policy=<policyId> <= copy file
3023 // copy a policy from the request contents into a file in the group's directory on this machine
3025 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
3027 loggingContext.setServiceName("AC:PAP.postPolicy");
3030 String policyId = request.getParameter("policyId");
3031 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
3033 InputStream is = null;
3034 if (apiflag != null){
3035 // get the request content into a String if the request is from API
3037 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
3038 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
3039 scanner.useDelimiter("\\A");
3040 json = scanner.hasNext() ? scanner.next() : "";
3042 logger.info("JSON request from API: " + json);
3044 // convert Object sent as JSON into local object
3045 ObjectMapper mapper = new ObjectMapper();
3047 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
3049 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
3051 is = new FileInputStream(new File(policy.getLocation()));
3053 is = request.getInputStream();
3057 addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
3058 ((StdPDPGroup) group).copyPolicyToFile(policyId, is);
3059 addPolicyToGroupTransaction.commitTransaction();
3061 } catch (Exception e) {
3062 addPolicyToGroupTransaction.rollbackTransaction();
3063 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
3064 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
3065 loggingContext.transactionEnded();
3067 PolicyLogger.audit("Transaction Failed - See Error.log");
3070 response.addHeader("error", "policyCopyError");
3071 response.addHeader("message", message);
3072 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3074 response.sendError(500, message);
3079 // policy file copied ok and the Group was updated on the PDP
3080 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3081 response.addHeader("operation", "push");
3082 response.addHeader("policyId", policyId);
3083 response.addHeader("groupId", groupId);
3084 if (logger.isDebugEnabled()) {
3085 logger.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
3088 loggingContext.transactionEnded();
3089 auditLogger.info("Success");
3090 PolicyLogger.audit("Transaction Ended Successfully");
3093 } else if (request.getParameter("default") != null) {
3094 // Args: group=<groupId> default=true <= make default
3095 // change the current default group to be the one identified in the request.
3096 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
3098 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
3099 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
3100 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
3102 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
3103 papEngine.SetDefaultGroup(group);
3104 setDefaultGroupTransaction.commitTransaction();
3105 } catch (Exception e) {
3106 setDefaultGroupTransaction.rollbackTransaction();
3107 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
3108 loggingContext.transactionEnded();
3110 PolicyLogger.audit("Transaction Failed - See Error.log");
3111 response.sendError(500, "Unable to set group '" + groupId + "' to default");
3115 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3116 if (logger.isDebugEnabled()) {
3117 logger.debug("Group '" + groupId + "' set to be default");
3119 // Notify the Admin Consoles that something changed
3120 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
3121 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
3123 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
3124 loggingContext.transactionEnded();
3125 auditLogger.info("Success");
3126 PolicyLogger.audit("Transaction Ended Successfully");
3129 } else if (request.getParameter("pdpId") != null) {
3130 doACPostTransaction = policyDBDao.getNewTransaction();
3131 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
3132 loggingContext.setServiceName("AC:PAP.movePDP");
3134 String pdpId = request.getParameter("pdpId");
3135 EcompPDP pdp = papEngine.getPDP(pdpId);
3137 EcompPDPGroup originalGroup = papEngine.getPDPGroup((EcompPDP) pdp);
3139 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
3140 }catch(Exception e){
3141 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
3142 " Error while moving pdp in the database: "
3143 +"pdp="+pdp.getId()+",to group="+group.getId());
3144 throw new PAPException(e.getMessage());
3146 papEngine.movePDP((EcompPDP) pdp, group);
3148 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3149 if (logger.isDebugEnabled()) {
3150 logger.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
3153 // update the status of both the original group and the new one
3154 ((StdPDPGroup)originalGroup).resetStatus();
3155 ((StdPDPGroup)group).resetStatus();
3157 // Notify the Admin Consoles that something changed
3158 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
3160 // Need to notify the PDP that it's config may have changed
3162 doACPostTransaction.commitTransaction();
3163 loggingContext.transactionEnded();
3164 auditLogger.info("Success");
3165 PolicyLogger.audit("Transaction Ended Successfully");
3170 } catch (PAPException e) {
3171 if(doACPostTransaction != null){
3172 doACPostTransaction.rollbackTransaction();
3174 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
3175 loggingContext.transactionEnded();
3177 PolicyLogger.audit("Transaction Failed - See Error.log");
3178 response.sendError(500, e.getMessage());
3184 * Requests from the Admin Console to create new items or update existing ones
3189 * @param loggingContext
3190 * @throws ServletException
3191 * @throws IOException
3193 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
3194 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
3198 // for PUT operations the group may or may not need to exist before the operation can be done
3199 EcompPDPGroup group = papEngine.getGroup(groupId);
3201 // determine the operation needed based on the parameters in the request
3203 // for remaining operations the group must exist before the operation can be done
3204 if (group == null) {
3205 String message = "Unknown groupId '" + groupId + "'";
3206 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
3207 loggingContext.transactionEnded();
3209 PolicyLogger.audit("Transaction Failed - See Error.log");
3210 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
3213 if (request.getParameter("policy") != null) {
3214 // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
3215 loggingContext.setServiceName("AC:PAP.putPolicy");
3216 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
3217 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3218 loggingContext.transactionEnded();
3219 PolicyLogger.audit("Transaction Failed - See Error.log");
3220 auditLogger.info("Success");
3221 PolicyLogger.audit("Transaction Ended Successfully");
3223 } else if (request.getParameter("pdpId") != null) {
3224 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
3226 String pdpId = request.getParameter("pdpId");
3227 if (papEngine.getPDP(pdpId) == null) {
3228 loggingContext.setServiceName("AC:PAP.createPDP");
3230 loggingContext.setServiceName("AC:PAP.updatePDP");
3233 // get the request content into a String
3235 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
3236 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
3237 scanner.useDelimiter("\\A");
3238 json = scanner.hasNext() ? scanner.next() : "";
3240 logger.info("JSON request from AC: " + json);
3242 // convert Object sent as JSON into local object
3243 ObjectMapper mapper = new ObjectMapper();
3245 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
3247 if (pdpId == null ||
3248 objectFromJSON == null ||
3249 ! (objectFromJSON instanceof StdPDP) ||
3250 ((StdPDP)objectFromJSON).getId() == null ||
3251 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
3252 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
3253 loggingContext.transactionEnded();
3255 PolicyLogger.audit("Transaction Failed - See Error.log");
3256 response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
3258 StdPDP pdp = (StdPDP) objectFromJSON;
3260 if (papEngine.getPDP(pdpId) == null) {
3261 // this is a request to create a new PDP object
3263 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
3264 } catch(Exception e){
3265 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
3266 +"pdp="+pdp.getId()+",to group="+group.getId());
3267 throw new PAPException(e.getMessage());
3269 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
3272 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
3273 } catch(Exception e){
3274 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
3275 +"pdp="+pdp.getId());
3276 throw new PAPException(e.getMessage());
3278 // this is a request to update the pdp
3279 papEngine.updatePDP(pdp);
3282 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3283 if (logger.isDebugEnabled()) {
3284 logger.debug("PDP '" + pdpId + "' created/updated");
3287 // adjust the group's state including the new PDP
3288 ((StdPDPGroup)group).resetStatus();
3290 // tell the Admin Consoles there is a change
3292 // this might affect the PDP, so notify it of the change
3294 acPutTransaction.commitTransaction();
3295 loggingContext.transactionEnded();
3296 auditLogger.info("Success");
3297 PolicyLogger.audit("Transaction Ended Successfully");
3299 } else if (request.getParameter("pipId") != null) {
3300 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
3301 loggingContext.setServiceName("AC:PAP.putPIP");
3302 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
3303 loggingContext.transactionEnded();
3305 PolicyLogger.audit("Transaction Failed - See Error.log");
3306 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
3309 // Assume that this is an update of an existing PDP Group
3310 // ARGS: group=<groupId> <= Update an Existing Group
3311 loggingContext.setServiceName("AC:PAP.updateGroup");
3313 // get the request content into a String
3315 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
3316 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
3317 scanner.useDelimiter("\\A");
3318 json = scanner.hasNext() ? scanner.next() : "";
3320 logger.info("JSON request from AC: " + json);
3322 // convert Object sent as JSON into local object
3323 ObjectMapper mapper = new ObjectMapper();
3325 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
3327 if (objectFromJSON == null ||
3328 ! (objectFromJSON instanceof StdPDPGroup) ||
3329 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
3330 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
3331 loggingContext.transactionEnded();
3333 PolicyLogger.audit("Transaction Failed - See Error.log");
3334 response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON);
3337 // The Path on the PAP side is not carried on the RESTful interface with the AC
3338 // (because it is local to the PAP)
3339 // so we need to fill that in before submitting the group for update
3340 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
3343 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
3344 } catch(Exception e){
3345 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
3346 +"group="+group.getId());
3347 throw new PAPException(e.getMessage());
3349 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
3352 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3353 if (logger.isDebugEnabled()) {
3354 logger.debug("Group '" + group.getId() + "' updated");
3356 acPutTransaction.commitTransaction();
3357 // tell the Admin Consoles there is a change
3359 // Group changed, which might include changing the policies
3360 groupChanged(group);
3362 loggingContext.transactionEnded();
3363 auditLogger.info("Success");
3364 PolicyLogger.audit("Transaction Ended Successfully");
3367 } catch (PAPException e) {
3368 acPutTransaction.rollbackTransaction();
3369 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
3370 loggingContext.transactionEnded();
3372 PolicyLogger.audit("Transaction Failed - See Error.log");
3373 response.sendError(500, e.getMessage());
3379 * Requests from the Admin Console to delete/remove items
3384 * @param loggingContext
3385 * @throws ServletException
3386 * @throws IOException
3388 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
3390 //This is temporary code to allow deletes to propagate to the database since delete is not implemented
3391 String isDeleteNotify = request.getParameter("isDeleteNotify");
3392 if(isDeleteNotify != null){
3393 String policyToDelete = request.getParameter("policyToDelete");
3395 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
3396 } catch(UnsupportedEncodingException e){
3397 PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8");
3398 response.sendError(500,"policyToDelete encoding not supported");
3401 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
3403 deleteTransaction.deletePolicy(policyToDelete);
3404 } catch(Exception e){
3405 deleteTransaction.rollbackTransaction();
3406 response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) "
3407 + "\nfailure with the following exception: " + e);
3410 deleteTransaction.commitTransaction();
3411 response.setStatus(HttpServletResponse.SC_OK);
3414 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
3416 // for all DELETE operations the group must exist before the operation can be done
3417 loggingContext.setServiceName("AC:PAP.delete");
3418 EcompPDPGroup group = papEngine.getGroup(groupId);
3419 if (group == null) {
3420 String message = "Unknown groupId '" + groupId + "'";
3421 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
3422 loggingContext.transactionEnded();
3424 PolicyLogger.audit("Transaction Failed - See Error.log");
3425 response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
3430 // determine the operation needed based on the parameters in the request
3431 if (request.getParameter("policy") != null) {
3432 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
3433 loggingContext.setServiceName("AC:PAP.deletePolicy");
3434 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
3435 //DATABASE so can policies not be deleted? or doesn't matter maybe as long as this gets called
3436 loggingContext.transactionEnded();
3438 PolicyLogger.audit("Transaction Failed - See Error.log");
3439 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
3441 } else if (request.getParameter("pdpId") != null) {
3442 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
3443 String pdpId = request.getParameter("pdpId");
3444 EcompPDP pdp = papEngine.getPDP(pdpId);
3447 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
3448 } catch(Exception e){
3449 throw new PAPException();
3451 papEngine.removePDP((EcompPDP) pdp);
3453 // adjust the status of the group, which may have changed when we removed this PDP
3454 ((StdPDPGroup)group).resetStatus();
3456 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3459 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
3461 removePdpOrGroupTransaction.commitTransaction();
3462 loggingContext.transactionEnded();
3463 auditLogger.info("Success");
3464 PolicyLogger.audit("Transaction Ended Successfully");
3466 } else if (request.getParameter("pipId") != null) {
3467 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
3469 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
3470 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
3471 loggingContext.transactionEnded();
3473 PolicyLogger.audit("Transaction Failed - See Error.log");
3474 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
3477 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
3478 String moveToGroupId = request.getParameter("movePDPsToGroupId");
3479 EcompPDPGroup moveToGroup = null;
3480 if (moveToGroupId != null) {
3481 moveToGroup = papEngine.getGroup(moveToGroupId);
3484 // get list of PDPs in the group being deleted so we can notify them that they got changed
3485 Set<EcompPDP> movedPDPs = new HashSet<EcompPDP>();
3486 movedPDPs.addAll(group.getEcompPdps());
3488 // do the move/remove
3490 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
3491 } catch(Exception e){
3492 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
3493 e.printStackTrace();
3494 throw new PAPException(e.getMessage());
3496 papEngine.removeGroup(group, moveToGroup);
3498 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
3500 // notify any PDPs in the removed set that their config may have changed
3501 for (EcompPDP pdp : movedPDPs) {
3504 removePdpOrGroupTransaction.commitTransaction();
3505 loggingContext.transactionEnded();
3506 auditLogger.info("Success");
3507 PolicyLogger.audit("Transaction Ended Successfully");
3511 } catch (PAPException e) {
3512 removePdpOrGroupTransaction.rollbackTransaction();
3513 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
3514 loggingContext.transactionEnded();
3516 PolicyLogger.audit("Transaction Failed - See Error.log");
3517 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Exception in request processing");
3518 response.sendError(500, e.getMessage());
3525 * Requests from the API to delete/remove items
3530 * @param loggingContext
3531 * @throws ServletException
3532 * @throws IOException
3534 private void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
3536 // get the request content into a String
3539 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
3540 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
3541 scanner.useDelimiter("\\A");
3542 json = scanner.hasNext() ? scanner.next() : "";
3544 logger.info("JSON request from API: " + json);
3546 // convert Object sent as JSON into local object
3547 ObjectMapper mapper = new ObjectMapper();
3549 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
3551 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
3553 String policyName = policy.getPolicyName();
3554 String fileSeparator = File.separator;
3555 policyName = policyName.replaceFirst("\\.", "\\"+fileSeparator);
3557 File file = getPolicyFile(policyName);
3558 String domain = getParentPathSubScopeDir(file);
3559 Boolean policyFileDeleted = false;
3560 Boolean configFileDeleted = false;
3561 Boolean policyVersionScoreDeleted = false;
3563 if (policy.getDeleteCondition().equalsIgnoreCase("All Versions")){
3565 //check for extension in policyName
3566 String removexmlExtension = null;
3567 String removeVersion = null;
3568 if (policyName.contains("xml")) {
3569 removexmlExtension = file.toString().substring(0, file.toString().lastIndexOf("."));
3570 removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));
3572 removeVersion = file.toString();
3575 File dirXML = new File(file.getParent());
3576 File[] listofXMLFiles = dirXML.listFiles();
3578 for (File files : listofXMLFiles) {
3579 //delete the xml files from the Repository
3580 if (files.isFile() && files.toString().contains(removeVersion)) {
3581 JPAUtils jpaUtils = null;
3583 jpaUtils = JPAUtils.getJPAUtilsInstance(emf);
3584 } catch (Exception e) {
3585 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
3586 e.printStackTrace();
3587 response.addHeader("error", "jpautils");
3588 response.addHeader("operation", "delete");
3589 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3593 if (jpaUtils.dbLockdownIgnoreErrors()) {
3594 logger.warn("Policies are locked down");
3595 response.addHeader("operation", "delete");
3596 response.addHeader("lockdown", "true");
3597 response.setStatus(HttpServletResponse.SC_ACCEPTED);
3601 //Propagates delete to the database
3602 Boolean deletedFromDB = notifyDBofDelete(files.toString());
3604 if (deletedFromDB) {
3605 logger.info("Policy deleted from the database. Continuing with file delete");
3607 PolicyLogger.error("Failed to delete Policy from database. Aborting file delete");
3608 response.addHeader("error", "deleteDB");
3609 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3613 if (files.delete()) {
3614 if (logger.isDebugEnabled()) {
3615 logger.debug("Deleted file: " + files.toString());
3617 policyFileDeleted = true;
3619 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE +
3620 "Cannot delete the policy file in specified location: " + files.getAbsolutePath());
3621 response.addHeader("error", "deleteFile");
3622 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
3626 // Get tomcat home directory for deleting config data
3627 logger.info("print the path:" +domain);
3628 String path = domain.replace('\\', '.');
3629 if(path.contains("/")){
3630 path = path.replace('/', '.');
3631 logger.info("print the path:" +path);
3633 String fileName = FilenameUtils.removeExtension(file.getName());
3634 String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf("."));
3635 String fileLocation = null;
3637 if(CONFIG_HOME == null){
3638 CONFIG_HOME = getConfigHome();
3640 if(ACTION_HOME == null){
3641 ACTION_HOME = getActionHome();
3645 if (fileName != null && fileName.contains("Config_")) {
3646 fileLocation = CONFIG_HOME;
3647 } else if (fileName != null && fileName.contains("Action_")) {
3648 fileLocation = ACTION_HOME;
3651 if (logger.isDebugEnabled()) {
3652 logger.debug("Attempting to rename file from the location: "+ fileLocation);
3655 if(!files.toString().contains("Decision_")){
3656 // Get the file from the saved location
3657 File dir = new File(fileLocation);
3658 File[] listOfFiles = dir.listFiles();
3660 for (File file1 : listOfFiles) {
3661 if (file1.isFile() && file1.getName().contains( path + removeVersionInFileName)) {
3663 if (file1.delete()) {
3664 if (logger.isDebugEnabled()) {
3665 logger.debug("Deleted file: " + file1.toString());
3667 configFileDeleted = true;
3669 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE +
3670 "Cannot delete the configuration or action body file in specified location: " + file1.getAbsolutePath());
3671 response.addHeader("error", "deleteConfig");
3672 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
3675 } catch (Exception e) {
3676 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Failed to Delete file");
3679 configFileDeleted = true;
3682 configFileDeleted = true;
3685 //Delete the Policy from Database Policy Version table
3686 if (policyFileDeleted && configFileDeleted) {
3687 String removeExtension = domain + removeVersionInFileName;
3688 EntityManager em = (EntityManager) emf.createEntityManager();
3690 Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
3691 Query getPolicyScore = em.createQuery("Select p from PolicyScore p where p.PolicyName=:pname");
3692 getPolicyVersion.setParameter("pname", removeExtension);
3693 getPolicyScore.setParameter("pname", removeExtension);
3695 @SuppressWarnings("rawtypes")
3696 List pvResult = getPolicyVersion.getResultList();
3697 @SuppressWarnings("rawtypes")
3698 List psResult = getPolicyScore.getResultList();
3702 em.getTransaction().begin();
3703 if (!pvResult.isEmpty()) {
3704 for (Object id : pvResult) {
3705 PolicyVersion versionEntity = (PolicyVersion)id;
3706 em.remove(versionEntity);
3709 logger.debug("No PolicyVersion record found in database.");
3712 if (!psResult.isEmpty()) {
3713 for (Object id : psResult) {
3714 PolicyScore scoreEntity = (PolicyScore)id;
3715 em.remove(scoreEntity);
3718 PolicyLogger.error("No PolicyScore record found in database.");
3720 em.getTransaction().commit();
3721 policyVersionScoreDeleted = true;
3722 }catch(Exception e){
3723 em.getTransaction().rollback();
3724 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
3725 response.addHeader("error", "deleteDB");
3726 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3734 //If Specific version is requested for delete
3735 } else if (policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
3736 String policyScoreName = domain + file.getName().toString();
3737 String policyVersionName = policyScoreName.substring(0, policyScoreName.indexOf("."));
3738 String versionExtension = policyScoreName.substring(policyScoreName.indexOf(".")+1);
3739 String removexmlExtension = file.toString().substring(0, file.toString().lastIndexOf("."));
3740 String getVersion = removexmlExtension.substring(removexmlExtension.indexOf(".")+1);
3741 String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));
3744 JPAUtils jpaUtils = null;
3746 jpaUtils = JPAUtils.getJPAUtilsInstance(emf);
3747 } catch (Exception e) {
3748 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
3749 e.printStackTrace();
3750 response.addHeader("error", "jpautils");
3751 response.addHeader("operation", "delete");
3752 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3756 if (jpaUtils.dbLockdownIgnoreErrors()) {
3757 logger.warn("Policies are locked down");
3758 response.addHeader("lockdown", "true");
3759 response.addHeader("operation", "delete");
3760 response.setStatus(HttpServletResponse.SC_ACCEPTED);
3764 //Propagates delete to the database
3765 Boolean deletedFromDB = notifyDBofDelete(file.toString());
3767 if (deletedFromDB) {
3768 logger.info("Policy deleted from the database. Continuing with file delete");
3770 PolicyLogger.error("Failed to delete Policy from database. Aborting file delete");
3771 response.addHeader("error", "deleteDB");
3772 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3776 if (file.delete()) {
3777 if (logger.isDebugEnabled()) {
3778 logger.debug("Deleted file: " + file.toString());
3780 policyFileDeleted = true;
3782 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE +
3783 "Cannot delete the policy file in specified location: " + file.getAbsolutePath());
3784 response.addHeader("error", "deleteFile");
3785 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
3789 // Get tomcat home directory for deleting config data
3790 logger.info("print the path:" +domain);
3791 String path = domain.replace('\\', '.');
3792 if(path.contains("/")){
3793 path = path.replace('/', '.');
3794 logger.info("print the path:" +path);
3796 String fileName = FilenameUtils.removeExtension(file.getName());
3797 String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf("."));
3798 String fileLocation = null;
3800 if(CONFIG_HOME == null){
3801 CONFIG_HOME = getConfigHome();
3803 if(ACTION_HOME == null){
3804 ACTION_HOME = getActionHome();
3808 if (fileName != null && fileName.contains("Config_")) {
3809 fileLocation = CONFIG_HOME;
3810 } else if (fileName != null && fileName.contains("Action_")) {
3811 fileLocation = ACTION_HOME;
3814 if (logger.isDebugEnabled()) {
3815 logger.debug("Attempting to rename file from the location: "+ fileLocation);
3818 if(!file.toString().contains("Decision_")){
3819 // Get the file from the saved location
3820 File dir = new File(fileLocation);
3821 File[] listOfFiles = dir.listFiles();
3823 for (File file1 : listOfFiles) {
3824 if (file1.isFile() && file1.getName().contains( path + fileName)) {
3826 if (file1.delete()) {
3827 if (logger.isDebugEnabled()) {
3828 logger.debug("Deleted file: " + file1.toString());
3830 configFileDeleted = true;
3832 logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE +
3833 "Cannot delete the configuration or action body file in specified location: " + file1.getAbsolutePath());
3834 response.addHeader("error", "deleteConfig");
3835 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
3838 } catch (Exception e) {
3839 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Failed to Delete file");
3842 configFileDeleted = true;
3845 configFileDeleted = true;
3848 //Delete the Policy from Database and set Active Version based on the deleted file.
3849 int highestVersion = 0;
3850 if (policyFileDeleted && configFileDeleted) {
3851 String removeExtension = domain + removeVersionInFileName;
3852 EntityManager em = (EntityManager) emf.createEntityManager();
3854 Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
3855 Query getPolicyScore = em.createQuery("Select p from PolicyScore p where p.PolicyName=:pname");
3856 getPolicyVersion.setParameter("pname", removeExtension);
3857 getPolicyScore.setParameter("pname", removeExtension);
3859 @SuppressWarnings("rawtypes")
3860 List pvResult = getPolicyVersion.getResultList();
3861 @SuppressWarnings("rawtypes")
3862 List psResult = getPolicyScore.getResultList();
3866 em.getTransaction().begin();
3867 if (!pvResult.isEmpty()) {
3868 PolicyVersion versionEntity = null;
3869 for (Object id : pvResult) {
3870 versionEntity = (PolicyVersion)id;
3871 if(versionEntity.getPolicyName().equals(removeExtension)){
3872 highestVersion = versionEntity.getHigherVersion();
3873 em.remove(versionEntity);
3878 int version = Integer.parseInt(getVersion);
3880 if(version == highestVersion) {
3881 for(i = highestVersion; i>=1; i--){
3882 highestVersion = highestVersion - 1;
3883 String dirXML = removeVersion + "." + highestVersion + ".xml";
3884 File filenew = new File(dirXML);
3886 if(filenew.exists()){
3893 versionEntity.setPolicyName(removeExtension);
3894 versionEntity.setHigherVersion(highestVersion);
3895 versionEntity.setActiveVersion(highestVersion);
3896 versionEntity.setModifiedBy("API");
3898 em.persist(versionEntity);
3901 logger.debug("No PolicyVersion record found in database.");
3904 if (!psResult.isEmpty()) {
3905 for (Object id : psResult) {
3906 PolicyScore scoreEntity = (PolicyScore)id;
3907 if(scoreEntity.getPolicyName().equals(policyVersionName) && scoreEntity.getVersionExtension().equals(versionExtension)){
3908 em.remove(scoreEntity);
3912 PolicyLogger.error("No PolicyScore record found in database.");
3914 em.getTransaction().commit();
3915 policyVersionScoreDeleted = true;
3916 }catch(Exception e){
3917 em.getTransaction().rollback();
3918 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
3919 response.addHeader("error", "deleteDB");
3920 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
3928 if (policyFileDeleted && configFileDeleted && policyVersionScoreDeleted) {
3929 response.setStatus(HttpServletResponse.SC_OK);
3930 response.addHeader("successMapKey", "success");
3931 response.addHeader("operation", "delete");
3934 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
3936 response.addHeader("error", "unknown");
3937 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
3943 private void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) {
3944 String importServiceCreation = request.getParameter("importService");;
3945 String fileName = request.getParameter("fileName");
3946 String version = request.getParameter("version");
3947 String serviceName = request.getParameter("serviceName");
3948 CreateNewMicroSerivceModel newMS = null;
3950 String randomID = UUID.randomUUID().toString();
3952 if ( importServiceCreation != null || fileName != null) {
3953 File extracDir = new File("ExtractDir");
3954 if (!extracDir.exists()){
3957 if (fileName.contains(".xmi")){
3958 // get the request content into a String
3961 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
3962 java.util.Scanner scanner;
3964 scanner = new java.util.Scanner(request.getInputStream());
3965 scanner.useDelimiter("\\A");
3966 xmi = scanner.hasNext() ? scanner.next() : "";
3968 } catch (IOException e1) {
3969 logger.error("Error in reading in file from API call");
3973 logger.info("XML request from API for import new Service");
3975 //Might need to seperate by , for more than one file.
3977 try (Writer writer = new BufferedWriter(new OutputStreamWriter(
3978 new FileOutputStream("ExtractDir" + File.separator + randomID+".xmi"), "utf-8"))) {
3980 } catch (IOException e) {
3981 logger.error("Error in reading in file from API call");
3986 InputStream inputStream = request.getInputStream() ;
3988 FileOutputStream outputStream = new FileOutputStream("ExtractDir" + File.separator + randomID+".zip");
3989 byte[] buffer = new byte[4096];
3990 int bytesRead = -1 ;
3991 while ((bytesRead = inputStream.read(buffer)) != -1) {
3992 outputStream.write(buffer, 0, bytesRead) ;
3995 outputStream.close() ;
3996 inputStream.close() ;
3998 } catch (IOException e) {
3999 logger.error("Error in reading in Zip File from API call");
4004 newMS = new CreateNewMicroSerivceModel(fileName, serviceName, "API IMPORT", version, randomID);
4005 Map<String, String> successMap = newMS.addValuesToNewModel();
4006 if (successMap.containsKey("success")) {
4008 successMap = newMS.saveImportService();
4012 // create the policy and return a response to the PAP-ADMIN
4013 if (successMap.containsKey("success")) {
4014 response.setStatus(HttpServletResponse.SC_OK);
4015 response.addHeader("successMapKey", "success");
4016 response.addHeader("operation", "import");
4017 response.addHeader("service", serviceName);
4018 } else if (successMap.containsKey("DBError")) {
4019 if (successMap.get("DBError").contains("EXISTS")){
4020 response.setStatus(HttpServletResponse.SC_CONFLICT);
4021 response.addHeader("service", serviceName);
4022 response.addHeader("error", "modelExistsDB");
4024 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
4025 response.addHeader("error", "importDB");
4027 response.addHeader("operation", "import");
4028 response.addHeader("service", serviceName);
4029 }else if (successMap.get("error").contains("MISSING")){
4030 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
4031 response.addHeader("error", "missing");
4032 response.addHeader("operation", "import");
4033 response.addHeader("service", serviceName);
4038 private void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
4040 String policyName = request.getParameter("policyName");
4041 String groupId = request.getParameter("groupId");
4042 String responseString = null;
4044 // for PUT operations the group may or may not need to exist before the operation can be done
4045 EcompPDPGroup group = null;
4047 group = papEngine.getGroup(groupId);
4048 } catch (PAPException e) {
4049 logger.error("Exception occured While PUT operation is performing for PDP Group"+e);
4052 if (group == null) {
4053 String message = "Unknown groupId '" + groupId + "'";
4054 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
4055 loggingContext.transactionEnded();
4057 PolicyLogger.audit("Transaction Failed - See Error.log");
4058 response.addHeader("error", "UnknownGroup");
4059 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
4063 loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");
4065 if (policyName.contains("xml")) {
4066 logger.debug("The full file name including the extension was provided for policyName.. continue.");
4068 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
4069 + "policyName must be the full name of the file to be deleted including version and extension";
4070 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
4071 + "policyName must be the full name of the file to be deleted including version and extension");
4072 response.addHeader("error", "invalidPolicyName");
4073 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
4076 RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);
4078 PDPPolicy policy = group.getPolicy(policyName);
4080 if (policy != null) {
4081 removePolicy.prepareToRemove(policy);
4082 EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
4083 responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
4085 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
4086 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
4087 response.addHeader("error", "noPolicyExist");
4088 response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
4093 if (responseString.equals("success")) {
4094 logger.info("Policy successfully deleted!");
4095 PolicyLogger.audit("Policy successfully deleted!");
4096 response.setStatus(HttpServletResponse.SC_OK);
4097 response.addHeader("successMapKey", "success");
4098 response.addHeader("operation", "delete");
4100 } else if (responseString.equals("No Group")) {
4101 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
4102 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
4103 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
4104 response.addHeader("error", "groupUpdate");
4105 response.addHeader("message", message);
4107 } else if (responseString.equals("DB Error")) {
4108 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
4109 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
4110 response.addHeader("error", "deleteDB");
4113 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
4114 response.addHeader("error", "unknown");
4115 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
4121 protected String getParentPathSubScopeDir(File file) {
4122 String domain1 = null;
4124 Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
4125 Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
4126 Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
4128 String policyDir = file.getAbsolutePath();
4129 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
4130 policyDir = policyDir.substring(startIndex, policyDir.length());
4131 if(policyDir.contains("Config_")){
4132 domain1 = policyDir.substring(0,policyDir.indexOf("Config_"));
4133 }else if(policyDir.contains("Action_")){
4134 domain1 = policyDir.substring(0,policyDir.indexOf("Action_"));
4136 domain1 = policyDir.substring(0,policyDir.indexOf("Decision_"));
4138 logger.info("print the main domain value"+policyDir);
4144 * method to delete the policy from the database and return notification when using API
4146 private Boolean notifyDBofDelete (String policyToDelete) {
4147 //String policyToDelete = request.getParameter("policyToDelete");
4149 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
4150 } catch(UnsupportedEncodingException e){
4151 PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8)");
4154 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
4156 deleteTransaction.deletePolicy(policyToDelete);
4157 } catch(Exception e){
4158 deleteTransaction.rollbackTransaction();
4161 deleteTransaction.commitTransaction();
4165 private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
4166 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
4168 String response = null;
4169 loggingContext.setServiceName("API:PAP.updateGroup");
4171 EcompPDPGroup existingGroup = null;
4173 existingGroup = papEngine.getGroup(group.getId());
4174 } catch (PAPException e1) {
4175 logger.error("Exception occured While Deleting Policy From PDP Group"+e1);
4178 if (group == null ||
4179 ! (group instanceof StdPDPGroup) ||
4180 ! (group.getId().equals(existingGroup.getId()))) {
4181 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup.getId() + " objectFromJSON="+group);
4182 loggingContext.transactionEnded();
4184 PolicyLogger.audit("Transaction Failed - See Error.log");
4186 response = "No Group";
4190 // The Path on the PAP side is not carried on the RESTful interface with the AC
4191 // (because it is local to the PAP)
4192 // so we need to fill that in before submitting the group for update
4193 ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());
4196 acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
4197 } catch(Exception e){
4198 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
4199 +"group="+existingGroup.getId());
4200 response = "DB Error";
4205 papEngine.updateGroup(group);
4206 } catch (PAPException e) {
4207 logger.error("Exception occured While Updating PDP Groups"+e);
4208 response = "error in updateGroup method";
4211 if (logger.isDebugEnabled()) {
4212 logger.debug("Group '" + group.getId() + "' updated");
4215 acPutTransaction.commitTransaction();
4217 // Group changed, which might include changing the policies
4219 groupChanged(existingGroup);
4220 } catch (Exception e) {
4221 logger.error("Exception occured in Group Change Method"+e);
4222 response = "error in groupChanged method";
4225 if (response==null){
4226 response = "success";
4227 PolicyLogger.audit("Policy successfully deleted!");
4228 PolicyLogger.audit("Transaction Ended Successfully");
4231 loggingContext.transactionEnded();
4232 PolicyLogger.audit("Transaction Ended");
4238 // Heartbeat thread - periodically check on PDPs' status
4242 * Heartbeat with all known PDPs.
4244 * Implementation note:
4246 * The PDPs are contacted Sequentially, not in Parallel.
4248 * If we did this in parallel using multiple threads we would simultaneously use
4252 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
4253 * when user changes occur.
4254 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
4256 * The Sequential operation does a heartbeat request to each PDP one at a time.
4257 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
4258 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
4259 * it could take a long time to cycle through all of the PDPs.
4260 * That means that this may not notice a PDP being down in a predictable time.
4264 private class Heartbeat implements Runnable {
4265 private PAPPolicyEngine papEngine;
4266 private Set<EcompPDP> pdps = new HashSet<EcompPDP>();
4267 private int heartbeatInterval;
4268 private int heartbeatTimeout;
4270 public volatile boolean isRunning = false;
4272 public synchronized boolean isRunning() {
4273 return this.isRunning;
4276 public synchronized void terminate() {
4277 this.isRunning = false;
4280 public Heartbeat(PAPPolicyEngine papEngine2) {
4281 this.papEngine = papEngine2;
4282 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
4283 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
4289 // Set ourselves as running
4291 synchronized(this) {
4292 this.isRunning = true;
4294 HashMap<String, URL> idToURLMap = new HashMap<String, URL>();
4296 while (this.isRunning()) {
4297 // Wait the given time
4298 Thread.sleep(heartbeatInterval);
4300 // get the list of PDPs (may have changed since last time)
4302 synchronized(papEngine) {
4304 for (EcompPDPGroup g : papEngine.getEcompPDPGroups()) {
4305 for (EcompPDP p : g.getEcompPdps()) {
4309 } catch (PAPException e) {
4310 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
4314 // Check for shutdown
4316 if (this.isRunning() == false) {
4317 logger.info("isRunning is false, getting out of loop.");
4321 // try to get the summary status from each PDP
4322 boolean changeSeen = false;
4323 for (EcompPDP pdp : pdps) {
4325 // Check for shutdown
4327 if (this.isRunning() == false) {
4328 logger.info("isRunning is false, getting out of loop.");
4331 // the id of the PDP is its url (though we add a query parameter)
4332 URL pdpURL = idToURLMap.get(pdp.getId());
4333 if (pdpURL == null) {
4334 // haven't seen this PDP before
4335 String fullURLString = null;
4338 if(CheckPDP.validateID(pdp.getId())){
4339 fullURLString = pdp.getId() + "?type=hb";
4340 pdpURL = new URL(fullURLString);
4341 idToURLMap.put(pdp.getId(), pdpURL);
4343 } catch (MalformedURLException e) {
4344 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
4349 // Do a GET with type HeartBeat
4350 String newStatus = "";
4352 HttpURLConnection connection = null;
4356 // Open up the connection
4358 connection = (HttpURLConnection)pdpURL.openConnection();
4360 // Setup our method and headers
4362 connection.setRequestMethod("GET");
4363 connection.setConnectTimeout(heartbeatTimeout);
4364 // Added for Authentication
4365 String encoding = CheckPDP.getEncoding(pdp.getId());
4366 if(encoding !=null){
4367 connection.setRequestProperty("Authorization", "Basic " + encoding);
4372 connection.connect();
4373 if (connection.getResponseCode() == 204) {
4374 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
4375 if (logger.isDebugEnabled()) {
4376 logger.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
4379 // anything else is an unexpected result
4380 newStatus = PDPStatus.Status.UNKNOWN.toString();
4381 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
4383 } catch (UnknownHostException e) {
4384 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
4385 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
4386 } catch (SocketTimeoutException e) {
4387 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
4388 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
4389 } catch (ConnectException e) {
4390 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
4391 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
4392 } catch (Exception e) {
4393 newStatus = PDPStatus.Status.UNKNOWN.toString();
4394 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
4396 // cleanup the connection
4397 connection.disconnect();
4400 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
4401 if (logger.isDebugEnabled()) {
4402 logger.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
4405 setPDPSummaryStatus(pdp, newStatus);
4406 } catch (PAPException e) {
4407 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
4414 // Check for shutdown
4416 if (this.isRunning() == false) {
4417 logger.info("isRunning is false, getting out of loop.");
4421 // if any of the PDPs changed state, tell the ACs to update
4427 } catch (InterruptedException e) {
4428 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
4436 // HELPER to change Group status when PDP status is changed
4438 // (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
4441 private void setPDPSummaryStatus(EcompPDP pdp, PDPStatus.Status newStatus) throws PAPException {
4442 setPDPSummaryStatus(pdp, newStatus.toString());
4445 private void setPDPSummaryStatus(EcompPDP pdp, String newStatus) throws PAPException {
4446 synchronized(papEngine) {
4447 StdPDPStatus status = new StdPDPStatus();
4448 status.setStatus(PDPStatus.Status.valueOf(newStatus));
4449 ((StdPDP)pdp).setStatus(status);
4451 // now adjust the group
4452 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((EcompPDP) pdp);
4453 // if the PDP was just deleted it may transiently exist but not be in a group
4454 if (group != null) {
4455 group.resetStatus();
4462 // Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
4463 // in the PDP group directories
4467 public void changed() {
4468 // all PDPs in all groups need to be updated/sync'd
4469 Set<EcompPDPGroup> groups;
4471 groups = papEngine.getEcompPDPGroups();
4472 } catch (PAPException e) {
4473 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
4474 throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
4476 for (EcompPDPGroup group : groups) {
4477 groupChanged(group);
4482 public void groupChanged(EcompPDPGroup group) {
4483 // all PDPs within one group need to be updated/sync'd
4484 for (EcompPDP pdp : group.getEcompPdps()) {
4490 public void pdpChanged(EcompPDP pdp) {
4491 // kick off a thread to do an event notification for each PDP.
4492 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
4493 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
4494 // begin - Fix to maintain requestId - including storedRequestId in UpdatePDPThread to be used later when calling PDP
4495 // Thread t = new Thread(new UpdatePDPThread(pdp));
4496 Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId));
4497 // end - Fix to maintain requestId
4498 if(CheckPDP.validateID(pdp.getId())){
4503 private class UpdatePDPThread implements Runnable {
4504 private EcompPDP pdp;
4505 // begin - Fix to maintain requestId - define requestId under class to be used later when calling PDP
4506 private String requestId;
4507 // end - Fix to maintain requestId
4509 // remember which PDP to notify
4510 public UpdatePDPThread(EcompPDP pdp) {
4514 // begin - Fix to maintain requestId - clone UpdatePDPThread method with different method signature so to include requestId to be used later when calling PDP
4515 public UpdatePDPThread(EcompPDP pdp, String storedRequestId) {
4517 requestId = storedRequestId;
4519 // end - Fix to maintain requestId
4522 // send the current configuration to one PDP
4523 HttpURLConnection connection = null;
4524 // get a new logging context for the thread
4525 ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext);
4527 loggingContext.setServiceName("PAP:PDP.putConfig");
4528 // get a new transaction (request) ID and update the logging context.
4529 // begin - Fix to maintain requestId - replace unconditioned generation of new requestID so it won't be used later when calling PDP
4530 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
4531 // UUID requestID = UUID.randomUUID();
4532 // loggingContext.setRequestID(requestID.toString());
4533 if ((requestId == null) || (requestId == "")) {
4534 UUID requestID = UUID.randomUUID();
4535 loggingContext.setRequestID(requestID.toString());
4536 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
4538 loggingContext.setRequestID(requestId);
4539 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
4541 // end - Fix to maintain requestId
4542 loggingContext.transactionStarted();
4543 // dummy metric.log example posted below as proof of concept
4544 loggingContext.metricStarted();
4545 loggingContext.metricEnded();
4546 PolicyLogger.metrics("Metric example posted here - 1 of 2");
4547 loggingContext.metricStarted();
4548 loggingContext.metricEnded();
4549 PolicyLogger.metrics("Metric example posted here - 2 of 2");
4550 // dummy metric.log example posted above as proof of concept
4553 // the Id of the PDP is its URL
4555 if (logger.isDebugEnabled()) {
4556 logger.debug("creating url for id '" + pdp.getId() + "'");
4558 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
4559 //TODO (need to change "cache=", implying getting some input saying which to change)
4560 URL url = new URL(pdp.getId() + "?cache=all");
4563 // Open up the connection
4565 connection = (HttpURLConnection)url.openConnection();
4567 // Setup our method and headers
4569 connection.setRequestMethod("PUT");
4570 // Added for Authentication
4571 String encoding = CheckPDP.getEncoding(pdp.getId());
4572 if(encoding !=null){
4573 connection.setRequestProperty("Authorization", "Basic " + encoding);
4575 connection.setRequestProperty("Content-Type", "text/x-java-properties");
4576 // begin - Fix to maintain requestId - post requestID from loggingContext in PDP request header for call to PDP, then reinit storedRequestId to null
4577 // connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
4578 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
4579 storedRequestId = null;
4580 // end - Fix to maintain requestId
4582 // Adding this in. It seems the HttpUrlConnection class does NOT
4583 // properly forward our headers for POST re-direction. It does so
4584 // for a GET re-direction.
4586 // So we need to handle this ourselves.
4588 //TODO - is this needed for a PUT? seems better to leave in for now?
4589 // connection.setInstanceFollowRedirects(false);
4591 // PLD - MUST be able to handle re-directs.
4593 connection.setInstanceFollowRedirects(true);
4594 connection.setDoOutput(true);
4595 try (OutputStream os = connection.getOutputStream()) {
4597 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
4598 // if the PDP was just deleted, there is no group, but we want to send an update anyway
4599 if (group == null) {
4600 // create blank properties files
4601 Properties policyProperties = new Properties();
4602 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
4603 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
4604 policyProperties.store(os, "");
4606 Properties pipProps = new Properties();
4607 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
4608 pipProps.store(os, "");
4611 // send properties from the current group
4612 group.getPolicyProperties().store(os, "");
4613 Properties policyLocations = new Properties();
4614 for (PDPPolicy policy : group.getPolicies()) {
4615 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
4617 policyLocations.store(os, "");
4618 group.getPipConfigProperties().store(os, "");
4621 } catch (Exception e) {
4622 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
4623 // Since this is a server-side error, it probably does not reflect a problem on the client,
4624 // so do not change the PDP status.
4630 connection.connect();
4631 if (connection.getResponseCode() == 204) {
4632 logger.info("Success. We are configured correctly.");
4633 loggingContext.transactionEnded();
4634 auditLogger.info("Success. PDP is configured correctly.");
4635 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
4636 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
4637 } else if (connection.getResponseCode() == 200) {
4638 logger.info("Success. PDP needs to update its configuration.");
4639 loggingContext.transactionEnded();
4640 auditLogger.info("Success. PDP needs to update its configuration.");
4641 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
4642 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
4644 logger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
4645 loggingContext.transactionEnded();
4646 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
4647 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
4649 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
4651 } catch (Exception e) {
4652 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
4653 loggingContext.transactionEnded();
4654 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
4656 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
4657 } catch (PAPException e1) {
4658 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
4660 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
4663 // cleanup the connection
4664 connection.disconnect();
4666 // tell the AC to update it's status info
4674 // RESTful Interface from PAP to ACs notifying them of changes
4677 private void notifyAC() {
4678 // kick off a thread to do one event notification for all registered ACs
4679 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
4680 // as part of processing this message on their end.
4681 Thread t = new Thread(new NotifyACThread());
4685 private class NotifyACThread implements Runnable {
4688 List<String> disconnectedACs = new ArrayList<String>();
4690 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
4691 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
4692 for (String acURL : adminConsoleURLStringList) {
4693 HttpURLConnection connection = null;
4696 acURL += "?PAPNotification=true";
4698 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
4699 //TODO - If so, put correct parameters into the Query string here
4700 acURL += "&objectType=all" + "&action=update";
4702 if (logger.isDebugEnabled()) {
4703 logger.debug("creating url for id '" + acURL + "'");
4705 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
4706 //TODO (need to change "cache=", implying getting some input saying which to change)
4708 URL url = new URL(acURL );
4711 // Open up the connection
4713 connection = (HttpURLConnection)url.openConnection();
4715 // Setup our method and headers
4717 connection.setRequestMethod("PUT");
4718 connection.setRequestProperty("Content-Type", "text/x-java-properties");
4720 // Adding this in. It seems the HttpUrlConnection class does NOT
4721 // properly forward our headers for POST re-direction. It does so
4722 // for a GET re-direction.
4724 // So we need to handle this ourselves.
4726 //TODO - is this needed for a PUT? seems better to leave in for now?
4727 connection.setInstanceFollowRedirects(false);
4729 // Do not include any data in the PUT because this is just a
4730 // notification to the AC.
4731 // The AC will use GETs back to the PAP to get what it needs
4732 // to fill in the screens.
4738 connection.connect();
4739 if (connection.getResponseCode() == 204) {
4740 logger.info("Success. We updated correctly.");
4742 logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
4745 } catch (Exception e) {
4746 //TODO:EELF Cleanup - Remove logger
4747 //logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to sync config AC '" + acURL + "': " + e, e);
4748 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
4749 disconnectedACs.add(acURL);
4751 // cleanup the connection
4752 connection.disconnect();
4756 // remove any ACs that are no longer connected
4757 if (disconnectedACs.size() > 0) {
4758 adminConsoleURLStringList.removeAll(disconnectedACs);
4765 * Added by Mike M in 1602 release for Authorizing the PEP Requests for Granularity.
4767 private boolean authorizeRequest(HttpServletRequest request) {
4768 if(request instanceof HttpServletRequest) {
4770 // Get the client Credentials from the Request header.
4771 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
4773 // Check if the Client is Authorized.
4774 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
4784 public static String getConfigHome(){
4787 } catch (Exception e) {
4793 public static String getActionHome(){
4796 } catch (Exception e) {
4802 private static void loadWebapps() throws Exception{
4803 if(ACTION_HOME == null || CONFIG_HOME == null){
4804 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
4806 if (webappsPath == null) {
4807 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
4808 throw new Exception("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
4810 Path webappsPathConfig;
4811 Path webappsPathAction;
4812 if(webappsPath.toString().contains("\\"))
4814 webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config");
4815 webappsPathAction = Paths.get(webappsPath.toString()+"\\Action");
4819 webappsPathConfig = Paths.get(webappsPath.toString()+"/Config");
4820 webappsPathAction = Paths.get(webappsPath.toString()+"/Action");
4822 if (Files.notExists(webappsPathConfig))
4825 Files.createDirectories(webappsPathConfig);
4826 } catch (IOException e) {
4827 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: "
4828 + webappsPathConfig.toAbsolutePath().toString());
4831 if (Files.notExists(webappsPathAction))
4834 Files.createDirectories(webappsPathAction);
4835 } catch (IOException e) {
4836 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
4837 + webappsPathAction.toAbsolutePath().toString(), e);
4840 ACTION_HOME = webappsPathAction.toString();
4841 CONFIG_HOME = webappsPathConfig.toString();
4848 public EntityManagerFactory getEmf() {
4851 public IntegrityMonitor getIm() {
4855 public IntegrityAudit getIa() {