2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.onap.policy.pap.xacml.rest;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.UnsupportedEncodingException;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
32 import java.net.MalformedURLException;
33 import java.net.SocketTimeoutException;
35 import java.net.URLDecoder;
36 import java.net.UnknownHostException;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Properties;
45 import java.util.Scanner;
47 import java.util.UUID;
48 import java.util.concurrent.CopyOnWriteArrayList;
50 import javax.persistence.EntityManagerFactory;
51 import javax.persistence.Persistence;
52 import javax.persistence.PersistenceException;
53 import javax.servlet.Servlet;
54 import javax.servlet.ServletConfig;
55 import javax.servlet.ServletException;
56 import javax.servlet.annotation.WebInitParam;
57 import javax.servlet.annotation.WebServlet;
58 import javax.servlet.http.HttpServlet;
59 import javax.servlet.http.HttpServletRequest;
60 import javax.servlet.http.HttpServletResponse;
62 import org.apache.commons.io.IOUtils;
63 import org.onap.policy.common.ia.IntegrityAudit;
64 import org.onap.policy.common.im.AdministrativeStateException;
65 import org.onap.policy.common.im.ForwardProgressException;
66 import org.onap.policy.common.im.IntegrityMonitor;
67 import org.onap.policy.common.im.IntegrityMonitorProperties;
68 import org.onap.policy.common.im.StandbyStatusException;
69 import org.onap.policy.common.logging.ONAPLoggingContext;
70 import org.onap.policy.common.logging.ONAPLoggingUtils;
71 import org.onap.policy.common.logging.eelf.MessageCodes;
72 import org.onap.policy.common.logging.eelf.PolicyLogger;
73 import org.onap.policy.common.logging.flexlogger.FlexLogger;
74 import org.onap.policy.common.logging.flexlogger.Logger;
75 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
76 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
77 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
78 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
79 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
80 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
81 import org.onap.policy.rest.XACMLRest;
82 import org.onap.policy.rest.XACMLRestProperties;
83 import org.onap.policy.rest.dao.PolicyDBException;
84 import org.onap.policy.utils.CryptoUtils;
85 import org.onap.policy.utils.PolicyUtils;
86 import org.onap.policy.xacml.api.XACMLErrorConstants;
87 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
88 import org.onap.policy.xacml.api.pap.OnapPDP;
89 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
90 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
91 import org.onap.policy.xacml.std.pap.StdPDP;
92 import org.onap.policy.xacml.std.pap.StdPDPGroup;
93 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
94 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
95 import org.onap.policy.xacml.std.pap.StdPDPStatus;
97 import com.att.research.xacml.api.pap.PAPException;
98 import com.att.research.xacml.api.pap.PDPPolicy;
99 import com.att.research.xacml.api.pap.PDPStatus;
100 import com.att.research.xacml.util.FactoryException;
101 import com.att.research.xacml.util.XACMLProperties;
102 import com.fasterxml.jackson.databind.ObjectMapper;
103 import com.google.common.base.Splitter;
106 * Servlet implementation class XacmlPapServlet
109 description = "Implements the XACML PAP RESTful API.",
110 urlPatterns = { "/" },
113 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
115 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
116 private static final long serialVersionUID = 1L;
117 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
118 // audit (transaction) LOGGER
119 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
120 //Persistence Unit for JPA
121 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
122 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
124 private static final String ENVIRONMENT_HEADER = "Environment";
125 private static final String ADD_GROUP_ERROR = "addGroupError";
126 private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
128 private static final String REGEX = "[0-9a-zA-Z._ ]*";
131 * List of Admin Console URLs.
132 * Used to send notifications when configuration changes.
134 * The CopyOnWriteArrayList *should* protect from concurrency errors.
135 * This list is seldom changed but often read, so the costs of this approach make sense.
137 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
139 private static String configHome;
140 private static String actionHome;
142 * This PAP instance's own URL.
143 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
145 private static String papURL = null;
146 // The heartbeat thread.
147 private static Heartbeat heartbeat = null;
148 private static Thread heartbeatThread = null;
149 //The entity manager factory for JPA access
150 private static EntityManagerFactory emf;
151 private static PolicyDBDao policyDBDao;
153 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
155 private static PAPPolicyEngine papEngine = null;
157 * These are the parameters needed for DB access from the PAP
159 private static int papIntegrityAuditPeriodSeconds = -1;
160 private static String papDbDriver = null;
161 private static String papDbUrl = null;
162 private static String papDbUser = null;
163 private static String papDbPassword = null;
164 private static String papResourceName = null;
165 private static String[] papDependencyGroupsFlatArray = null;
166 private static String environment = null;
167 private static String pdpFile = null;
169 private transient IntegrityMonitor im;
170 private transient IntegrityAudit ia;
172 //MicroService Model Properties
173 private static String msOnapName;
174 private static String msPolicyName;
176 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
177 * this servlet starts. Its configurable by the admin.
179 private static transient Thread initiateThread = null;
180 private transient ONAPLoggingContext baseLoggingContext = null;
183 * @see HttpServlet#HttpServlet()
185 public XACMLPapServlet() {
190 * @see Servlet#init(ServletConfig)
192 public void init(ServletConfig config) throws ServletException {
195 baseLoggingContext = new ONAPLoggingContext();
196 // fixed data that will be the same in all logging output goes here
198 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
199 baseLoggingContext.setServer(hostname);
200 } catch (UnknownHostException e) {
201 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
204 XACMLRest.xacmlInit(config);
205 // Load the properties
206 XACMLRest.loadXacmlProperties(null, null);
208 * Retrieve the property values
210 setCommonProperties();
211 String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
212 if(papSiteName == null){
213 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
214 throw new PAPException("papSiteName is null");
216 String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
217 if(papNodeType == null){
218 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
219 throw new PAPException("papNodeType is null");
221 //Integer will throw an exception of anything is missing or unrecognized
222 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
223 int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
224 int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
225 //Boolean will default to false if anything is missing or unrecognized
226 boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
227 boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
228 String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
229 if(papDependencyGroups == null){
230 throw new PAPException("papDependencyGroups is null");
232 setPAPDependencyGroups(papDependencyGroups);
233 //Integer will throw an exception of anything is missing or unrecognized
234 int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
235 int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
236 int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
237 int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
238 LOGGER.debug("\n\n\n**************************************"
239 + "\n*************************************"
241 + "\n papDbDriver = " + papDbDriver
242 + "\n papDbUrl = " + papDbUrl
243 + "\n papDbUser = " + papDbUser
244 + "\n papTransWait = " + papTransWait
245 + "\n papTransTimeout = " + papTransTimeout
246 + "\n papAuditTimeout = " + papAuditTimeout
247 + "\n papAuditFlag = " + papAuditFlag
248 + "\n papFileSystemAudit = " + papFileSystemAudit
249 + "\n papResourceName = " + papResourceName
250 + "\n fpMonitorInterval = " + fpMonitorInterval
251 + "\n failedCounterThreshold = " + failedCounterThreshold
252 + "\n testTransInterval = " + testTransInterval
253 + "\n writeFpcInterval = " + writeFpcInterval
254 + "\n papSiteName = " + papSiteName
255 + "\n papNodeType = " + papNodeType
256 + "\n papDependencyGroupsList = " + papDependencyGroups
257 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
258 + "\n\n*************************************"
259 + "\n**************************************");
260 // Pull custom persistence settings
261 Properties properties;
263 properties = XACMLProperties.getProperties();
264 LOGGER.debug("\n\n\n**************************************"
265 + "\n**************************************"
267 + "properties = " + properties
268 + "\n\n**************************************");
269 } catch (IOException e) {
270 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
271 + "XACMLProperties.getProperties()");
272 throw new ServletException(e.getMessage(), e.getCause());
274 // Create an IntegrityMonitor
275 if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
276 properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
278 im = IntegrityMonitor.getInstance(papResourceName,properties);
279 // Create an IntegrityAudit
280 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
281 ia.startAuditThread();
282 // Create the entity manager factory
284 // we are about to call the PDPs and give them their configuration.
285 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
286 setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
287 //Create the policyDBDao
289 // Load our PAP engine, first create a factory
290 ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
291 // The factory knows how to go about creating a PAP Engine
292 setPAPEngine((PAPPolicyEngine) factory.newEngine());
293 PolicyDBDaoTransaction addNewGroup = null;
294 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
296 addNewGroup = policyDBDao.getNewTransaction();
297 OnapPDPGroup group = papEngine.getDefaultGroup();
298 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
299 "automaticallyAdded");
300 addNewGroup.commitTransaction();
301 addNewGroup = policyDBDao.getNewTransaction();
302 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
303 addNewGroup.commitTransaction();
304 } catch (Exception e) {
305 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
306 " Error creating new default group in the database");
307 if (addNewGroup != null) {
308 addNewGroup.rollbackTransaction();
312 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
313 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
315 * Auditing the local File System groups to be in sync with the Database
318 //get an AuditTransaction to lock out all other transactions
319 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
321 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
322 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
323 //get the current filesystem group and update from the database if needed
324 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
325 StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
326 if(updatedGroup!=null) {
327 papEngine.updateGroup(updatedGroup);
329 LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
331 //release the transaction lock
335 // Sanity check for URL.
336 if (XACMLPapServlet.papURL == null) {
337 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
339 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
340 // to all its known PDP nodes.
341 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
342 startInitiateThreadService(new Thread(this));
344 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
345 startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
347 } catch (FactoryException | PAPException e) {
348 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
349 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
350 } catch (Exception e) {
351 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
352 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
356 private static void startInitiateThreadService(Thread thread) {
357 initiateThread = thread;
358 initiateThread.start();
361 private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
363 mapper.writeValue(response.getOutputStream(), value);
364 } catch (Exception e) {
369 private static void startHeartBeatService(Heartbeat heartbeat) {
370 XACMLPapServlet.heartbeat = heartbeat;
371 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
372 XACMLPapServlet.heartbeatThread.start();
375 private static void setPolicyDBDao() throws ServletException {
377 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
378 } catch (Exception e) {
379 throw new ServletException("Unable to Create Policy DBDao Instance",e);
383 private static void setEMF(Properties properties) throws ServletException {
384 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
386 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
388 throw new ServletException("Unable to create Entity Manager Factory");
392 private static void setPAPURL(String papURL) {
393 XACMLPapServlet.papURL = papURL;
396 private static void setPAPEngine(PAPPolicyEngine newEngine) {
397 XACMLPapServlet.papEngine = newEngine;
400 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
402 //Now we have flattened the array into a simple comma-separated list
403 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
404 //clean up the entries
405 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
406 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
409 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
410 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
413 String msg = "integrity_audit_period_seconds ";
414 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
415 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
419 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
420 throw new PAPException(e);
424 private static void setCommonProperties() throws PAPException {
427 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
428 if(papDbDriver == null){
429 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
430 throw new PAPException("papDbDriver is null");
432 setPapDbDriver(papDbDriver);
433 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
434 if(papDbUrl == null){
435 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
436 throw new PAPException("papDbUrl is null");
438 setPapDbUrl(papDbUrl);
439 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
440 if(papDbUser == null){
441 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
442 throw new PAPException("papDbUser is null");
444 setPapDbUser(papDbUser);
445 papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
446 if(papDbPassword == null){
447 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
448 throw new PAPException("papDbPassword is null");
450 setPapDbPassword(papDbPassword);
451 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
452 if(papResourceName == null){
453 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
454 throw new PAPException("papResourceName is null");
456 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
457 //Micro Service Properties
458 msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
459 setMsOnapName(msOnapName);
460 msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
461 setMsPolicyName(msPolicyName);
462 // PDPId File location
463 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
464 if (XACMLPapServlet.pdpFile == null) {
465 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
466 + XACMLRestProperties.PROP_PDP_IDFILE);
467 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
472 * Thread used only during PAP startup to initiate change messages to all known PDPs.
473 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
477 // send the current configuration to all the PDPs that we know about
482 * @see Servlet#destroy()
484 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
485 * For now we assume that we do care.
488 public void destroy() {
489 // Make sure our threads are destroyed
490 if (XACMLPapServlet.heartbeatThread != null) {
491 // stop the heartbeat
493 if (XACMLPapServlet.heartbeat != null) {
494 XACMLPapServlet.heartbeat.terminate();
496 XACMLPapServlet.heartbeatThread.interrupt();
497 XACMLPapServlet.heartbeatThread.join();
498 } catch (InterruptedException e) {
499 XACMLPapServlet.heartbeatThread.interrupt();
500 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
503 if (initiateThread != null) {
505 initiateThread.interrupt();
506 initiateThread.join();
507 } catch (InterruptedException e) {
508 initiateThread.interrupt();
509 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
516 * - PDP nodes to register themselves with the PAP, and
517 * - Admin Console to make changes in the PDP Groups.
519 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
521 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
522 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
523 loggingContext.transactionStarted();
524 loggingContext.setServiceName("PAP.post");
525 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
526 UUID requestID = UUID.randomUUID();
527 loggingContext.setRequestID(requestID.toString());
528 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
530 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
532 PolicyDBDaoTransaction pdpTransaction = null;
533 loggingContext.metricStarted();
535 im.startTransaction();
536 loggingContext.metricEnded();
537 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
538 } catch (AdministrativeStateException ae){
539 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
540 + " state of " + im.getStateManager().getAdminState()
541 + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
542 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
543 loggingContext.metricEnded();
544 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
545 loggingContext.transactionEnded();
546 PolicyLogger.audit("Transaction Failed - See Error.log");
547 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
549 }catch (StandbyStatusException se) {
550 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
551 + " of " + im.getStateManager().getStandbyStatus()
552 + "\n Exception Message: " + se.getMessage();
553 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
554 loggingContext.metricEnded();
555 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
556 loggingContext.transactionEnded();
557 PolicyLogger.audit("Transaction Failed - See Error.log");
558 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
562 loggingContext.metricStarted();
563 XACMLRest.dumpRequest(request);
564 loggingContext.metricEnded();
565 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
566 // since getParameter reads the content string, explicitly get the content before doing that.
567 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
568 request.getInputStream();
569 String groupId = request.getParameter("groupId");
570 String apiflag = request.getParameter("apiflag");
571 if(groupId != null) {
572 // Is this from the Admin Console or API?
573 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
574 // this is from the API so we need to check the client credentials before processing the request
575 if(!authorizeRequest(request)){
576 String message = "PEP not Authorized for making this Request!!";
577 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
578 loggingContext.transactionEnded();
579 PolicyLogger.audit("Transaction Failed - See Error.log");
580 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
585 loggingContext.metricStarted();
586 doACPost(request, response, groupId, loggingContext);
587 loggingContext.metricEnded();
588 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
589 loggingContext.transactionEnded();
590 PolicyLogger.audit("Transaction Ended Successfully");
594 // Request is from a PDP asking for its config.
595 loggingContext.setServiceName("PDP:PAP.register");
597 String id = this.getPDPID(request);
598 String jmxport = this.getPDPJMX(request);
599 LOGGER.info("Request(doPost) from PDP coming up: " + id);
600 // Get the PDP Object
601 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
604 LOGGER.info("Unknown PDP: " + id);
606 if(CheckPDP.validateID(id)){
607 pdpTransaction = policyDBDao.getNewTransaction();
609 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
610 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
611 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
612 pdpTransaction.rollbackTransaction();
613 String message = "Failed to create new PDP for id: " + id;
614 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
615 loggingContext.transactionEnded();
616 PolicyLogger.audit("Transaction Failed - See Error.log");
617 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
621 // get the PDP we just created
623 pdp = XACMLPapServlet.papEngine.getPDP(id);
624 }catch(PAPException e){
628 if(pdpTransaction != null){
629 pdpTransaction.rollbackTransaction();
631 String message = "Failed to create new PDP for id: " + id;
632 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
633 loggingContext.transactionEnded();
634 PolicyLogger.audit("Transaction Failed - See Error.log");
635 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
640 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
641 loggingContext.transactionEnded();
642 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
643 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
644 PolicyLogger.audit("Transaction Failed - See Error.log");
649 loggingContext.metricStarted();
650 pdpTransaction.commitTransaction();
651 loggingContext.metricEnded();
652 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
653 } catch(Exception e){
654 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
657 if (jmxport != null && jmxport != ""){
659 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
660 }catch(NumberFormatException e){
664 // Get the PDP's Group
665 OnapPDPGroup group =null;
667 group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
668 }catch(PAPException e){
672 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
673 loggingContext.transactionEnded();
674 PolicyLogger.audit("Transaction Failed - See Error.log");
675 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
679 // Determine what group the PDP node is in and get
680 // its policy/pip properties.
681 Properties policies = group.getPolicyProperties();
682 Properties pipconfig = group.getPipConfigProperties();
683 // Get the current policy/pip configuration that the PDP has
684 Properties pdpProperties = new Properties();
686 pdpProperties.load(request.getInputStream());
687 }catch(IOException e){
690 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
691 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
692 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
693 // Validate the node's properties
694 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
695 // Send back current configuration
696 if (isCurrent == false) {
697 // Tell the PDP we are sending back the current policies/pip config
698 LOGGER.info("PDP configuration NOT current.");
699 if (policies != null) {
700 // Put URL's into the properties in case the PDP needs to
702 this.populatePolicyURL(request.getRequestURL(), policies);
703 // Copy the properties to the output stream
705 policies.store(response.getOutputStream(), "");
706 }catch(IOException e){
710 if (pipconfig != null) {
711 // Copy the properties to the output stream
713 pipconfig.store(response.getOutputStream(), "");
714 }catch(IOException e){
718 // We are good - and we are sending them information
719 response.setStatus(HttpServletResponse.SC_OK);
721 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
722 }catch(PAPException e){
726 // Tell them they are good
727 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
729 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
730 }catch(PAPException e){
734 // tell the AC that something changed
735 loggingContext.metricStarted();
737 loggingContext.metricEnded();
738 PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
739 loggingContext.transactionEnded();
740 auditLogger.info("Success");
741 PolicyLogger.audit("Transaction Ended Successfully");
742 } catch (PAPException | IOException | NumberFormatException e) {
743 if(pdpTransaction != null){
744 pdpTransaction.rollbackTransaction();
746 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
747 loggingContext.transactionEnded();
748 PolicyLogger.audit("Transaction Failed - See Error.log");
749 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
753 //Catch anything that fell through
754 loggingContext.transactionEnded();
755 PolicyLogger.audit("Transaction Ended");
759 private void setResponseError(HttpServletResponse response,int responseCode, String message) {
761 if(message != null && !message.isEmpty()){
762 response.sendError(responseCode, message);
764 } catch (IOException e) {
765 LOGGER.error("Error setting Error response Header ", e);
771 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
773 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
774 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
775 loggingContext.transactionStarted();
776 loggingContext.setServiceName("PAP.get");
777 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
778 UUID requestID = UUID.randomUUID();
779 loggingContext.setRequestID(requestID.toString());
780 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
782 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
785 loggingContext.metricStarted();
786 XACMLRest.dumpRequest(request);
787 loggingContext.metricEnded();
788 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
789 String pathInfo = request.getRequestURI();
790 LOGGER.info("path info: " + pathInfo);
791 if (pathInfo != null){
792 //DO NOT do a im.startTransaction for the test request
793 if (pathInfo.equals("/pap/test")) {
795 testService(loggingContext, response);
796 } catch (IOException e) {
802 //This im.startTransaction() covers all other Get transactions
804 loggingContext.metricStarted();
805 im.startTransaction();
806 loggingContext.metricEnded();
807 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
808 } catch (AdministrativeStateException ae){
809 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
810 + " state of " + im.getStateManager().getAdminState()
811 + "\n Exception Message: " + ae.getMessage();
812 LOGGER.info(message, ae);
813 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
814 loggingContext.transactionEnded();
815 PolicyLogger.audit("Transaction Failed - See Error.log");
816 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
818 }catch (StandbyStatusException se) {
819 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
820 + " of " + im.getStateManager().getStandbyStatus()
821 + "\n Exception Message: " + se.getMessage();
822 LOGGER.info(message, se);
823 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
824 loggingContext.transactionEnded();
825 PolicyLogger.audit("Transaction Failed - See Error.log");
826 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
829 // Request from the API to get the gitPath
830 String apiflag = request.getParameter("apiflag");
832 if(authorizeRequest(request)){
833 APIRequestHandler apiRequestHandler = new APIRequestHandler();
835 loggingContext.metricStarted();
836 apiRequestHandler.doGet(request,response, apiflag);
837 loggingContext.metricEnded();
838 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
839 }catch(IOException e){
842 loggingContext.transactionEnded();
843 PolicyLogger.audit("Transaction Ended Successfully");
847 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
848 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
849 loggingContext.transactionEnded();
850 PolicyLogger.audit("Transaction Failed - See Error.log");
851 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
856 // Is this from the Admin Console?
857 String groupId = request.getParameter("groupId");
858 if (groupId != null) {
859 // this is from the Admin Console, so handle separately
861 loggingContext.metricStarted();
862 doACGet(request, response, groupId, loggingContext);
863 loggingContext.metricEnded();
864 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
865 } catch(IOException e){
868 loggingContext.transactionEnded();
869 PolicyLogger.audit("Transaction Ended Successfully");
874 String id = this.getPDPID(request);
875 LOGGER.info("doGet from: " + id);
876 // Get the PDP Object
879 pdp = XACMLPapServlet.papEngine.getPDP(id);
880 }catch(PAPException e){
885 // Check if request came from localhost
886 if (request.getRemoteHost().equals("localhost") ||
887 request.getRemoteHost().equals(request.getLocalAddr())) {
888 // Return status information - basically all the groups
889 loggingContext.setServiceName("PAP.getGroups");
890 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
891 // convert response object to JSON and include in the response
892 mapperWriteValue(new ObjectMapper(), response, groups);
893 response.setHeader("content-type", "application/json");
894 response.setStatus(HttpServletResponse.SC_OK);
895 loggingContext.transactionEnded();
896 PolicyLogger.audit("Transaction Ended Successfully");
900 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
901 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
902 loggingContext.transactionEnded();
903 PolicyLogger.audit("Transaction Failed - See Error.log");
904 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
908 loggingContext.setServiceName("PAP.getPolicy");
909 // Get the PDP's Group
910 OnapPDPGroup group = null;
912 group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
913 } catch (PAPException e) {
917 String message = "No group associated with pdp " + pdp.getId();
918 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
919 loggingContext.transactionEnded();
920 PolicyLogger.audit("Transaction Failed - See Error.log");
921 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
925 // Which policy do they want?
926 String policyId = request.getParameter("id");
927 if (policyId == null) {
928 String message = "Did not specify an id for the policy";
929 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
930 loggingContext.transactionEnded();
931 PolicyLogger.audit("Transaction Failed - See Error.log");
932 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
936 PDPPolicy policy = group.getPolicy(policyId);
937 if (policy == null) {
938 String message = "Unknown policy: " + policyId;
939 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
940 loggingContext.transactionEnded();
941 PolicyLogger.audit("Transaction Failed - See Error.log");
942 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
947 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
948 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
949 } catch (PAPException| IOException e){
952 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
953 // Send the policy back
954 IOUtils.copy(is, os);
955 response.setStatus(HttpServletResponse.SC_OK);
956 loggingContext.transactionEnded();
957 auditLogger.info("Success");
958 PolicyLogger.audit("Transaction Ended Successfully");
959 } catch (IOException e) {
960 String message = "Failed to open policy id " + policyId;
962 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
963 loggingContext.transactionEnded();
964 PolicyLogger.audit("Transaction Failed - See Error.log");
965 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
967 } catch (PAPException e) {
969 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
970 loggingContext.transactionEnded();
971 PolicyLogger.audit("Transaction Failed - See Error.log");
972 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
976 loggingContext.transactionEnded();
977 PolicyLogger.audit("Transaction Ended");
982 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
984 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
985 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
986 loggingContext.transactionStarted();
987 loggingContext.setServiceName("PAP.put");
988 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
989 UUID requestID = UUID.randomUUID();
990 loggingContext.setRequestID(requestID.toString());
991 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
993 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
996 loggingContext.metricStarted();
997 im.startTransaction();
998 loggingContext.metricEnded();
999 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1000 } catch (AdministrativeStateException | StandbyStatusException e) {
1001 String message = "PUT interface called for PAP " + papResourceName;
1002 if (e instanceof AdministrativeStateException) {
1003 message += " but it has an Administrative state of "
1004 + im.getStateManager().getAdminState();
1005 } else if (e instanceof StandbyStatusException) {
1006 message += " but it has a Standby Status of "
1007 + im.getStateManager().getStandbyStatus();
1010 message += "\n Exception Message: " + e.getMessage();
1012 LOGGER.info(message, e);
1013 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1014 loggingContext.transactionEnded();
1015 PolicyLogger.audit("Transaction Failed - See Error.log");
1016 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1020 loggingContext.metricStarted();
1021 XACMLRest.dumpRequest(request);
1022 loggingContext.metricEnded();
1023 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1024 //need to check if request is from the API or Admin console
1025 String apiflag = request.getParameter("apiflag");
1026 //This would occur if a PolicyDBDao notification was received
1027 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1028 if(policyDBDaoRequestUrl != null){
1029 LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
1030 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1031 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1032 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1033 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1034 setResponseError(response,400, "entityid or entitytype not supplied");
1035 loggingContext.transactionEnded();
1036 PolicyLogger.audit("Transaction Ended Successfully");
1037 im.endTransaction();
1040 loggingContext.metricStarted();
1041 LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1042 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1043 loggingContext.metricEnded();
1044 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1045 response.setStatus(200);
1046 loggingContext.transactionEnded();
1047 PolicyLogger.audit("Transaction Ended Successfully");
1048 im.endTransaction();
1052 * Request for ImportService
1054 String importService = request.getParameter("importService");
1055 if (importService != null) {
1056 if(authorizeRequest(request)){
1057 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1059 loggingContext.metricStarted();
1060 apiRequestHandler.doPut(request, response, importService);
1061 loggingContext.metricEnded();
1062 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1063 }catch(IOException e){
1066 im.endTransaction();
1069 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1070 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1071 loggingContext.transactionEnded();
1072 PolicyLogger.audit("Transaction Failed - See Error.log");
1073 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1077 //This would occur if we received a notification of a policy rename from AC
1078 String oldPolicyName = request.getParameter("oldPolicyName");
1079 String newPolicyName = request.getParameter("newPolicyName");
1080 if(oldPolicyName != null && newPolicyName != null){
1081 if(LOGGER.isDebugEnabled()){
1082 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
1083 + "\npolicyToCreateUpdate = " + " ");
1087 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
1088 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
1089 if(LOGGER.isDebugEnabled()){
1090 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
1091 + "\npolicyToCreateUpdate = " + " ");
1093 } catch(UnsupportedEncodingException e){
1094 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1095 + "\npolicyToCreateUpdate = " + " ");
1096 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToCreateUpdate encoding not supported"
1097 + "\nfailure with the following exception: " + e);
1098 loggingContext.transactionEnded();
1099 PolicyLogger.audit("Transaction Failed - See error.log");
1100 im.endTransaction();
1103 //send it to PolicyDBDao
1104 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1106 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1107 }catch(Exception e){
1108 renameTransaction.rollbackTransaction();
1109 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1110 + "\nfailure with the following exception: " + e);
1111 loggingContext.transactionEnded();
1112 PolicyLogger.audit("Transaction Failed - See error.log");
1113 im.endTransaction();
1116 loggingContext.metricStarted();
1117 renameTransaction.commitTransaction();
1118 loggingContext.metricEnded();
1119 PolicyLogger.metrics("XACMLPapServlet goPut commitTransaction");
1120 response.setStatus(HttpServletResponse.SC_OK);
1121 loggingContext.transactionEnded();
1122 PolicyLogger.audit("Transaction Ended Successfully");
1123 im.endTransaction();
1127 // See if this is Admin Console registering itself with us
1129 String acURLString = request.getParameter("adminConsoleURL");
1130 if (acURLString != null) {
1131 loggingContext.setServiceName("AC:PAP.register");
1132 // remember this Admin Console for future updates
1133 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1134 adminConsoleURLStringList.add(acURLString);
1136 if (LOGGER.isDebugEnabled()) {
1137 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1139 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1140 loggingContext.transactionEnded();
1141 auditLogger.info("Success");
1142 PolicyLogger.audit("Transaction Ended Successfully");
1143 im.endTransaction();
1147 * This is to update the PDP Group with the policy/policies being pushed
1148 * Part of a 2 step process to push policies to the PDP that can now be done
1149 * From both the Admin Console and the PolicyEngine API
1151 String groupId = request.getParameter("groupId");
1152 if (groupId != null) {
1154 if(!authorizeRequest(request)){
1155 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1156 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1157 loggingContext.transactionEnded();
1158 PolicyLogger.audit("Transaction Failed - See Error.log");
1159 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1162 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1164 updateGroupsFromAPI(request, response, groupId, loggingContext);
1165 }catch(IOException e){
1168 loggingContext.transactionEnded();
1169 PolicyLogger.audit("Transaction Ended Successfully");
1170 im.endTransaction();
1174 // this is from the Admin Console, so handle separately
1176 loggingContext.metricEnded();
1177 doACPut(request, response, groupId, loggingContext);
1178 loggingContext.metricEnded();
1179 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1180 } catch (IOException e) {
1183 loggingContext.transactionEnded();
1184 PolicyLogger.audit("Transaction Ended Successfully");
1185 im.endTransaction();
1189 // Request is for policy validation and creation
1191 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1192 // this request is from the Admin Console
1193 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1195 loggingContext.metricStarted();
1196 savePolicyHandler.doPolicyAPIPut(request, response);
1197 loggingContext.metricEnded();
1198 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1199 } catch (IOException e) {
1202 loggingContext.transactionEnded();
1203 PolicyLogger.audit("Transaction Ended Successfully");
1204 im.endTransaction();
1206 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1207 // this request is from the Policy Creation API
1208 if(authorizeRequest(request)){
1209 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1211 loggingContext.metricStarted();
1212 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1213 loggingContext.metricEnded();
1214 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1215 } catch (IOException e) {
1218 loggingContext.transactionEnded();
1219 PolicyLogger.audit("Transaction Ended Successfully");
1220 im.endTransaction();
1223 String message = "PEP not Authorized for making this Request!!";
1224 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1225 loggingContext.transactionEnded();
1226 PolicyLogger.audit("Transaction Failed - See Error.log");
1227 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1228 im.endTransaction();
1232 // We do not expect anything from anywhere else.
1233 // This method is here in case we ever need to support other operations.
1234 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1235 loggingContext.transactionEnded();
1236 PolicyLogger.audit("Transaction Failed - See Error.log");
1237 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1238 loggingContext.transactionEnded();
1239 PolicyLogger.audit("Transaction Failed - See error.log");
1240 im.endTransaction();
1244 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1246 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1247 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1248 loggingContext.transactionStarted();
1249 loggingContext.setServiceName("PAP.delete");
1250 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1251 UUID requestID = UUID.randomUUID();
1252 loggingContext.setRequestID(requestID.toString());
1253 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1255 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1258 loggingContext.metricStarted();
1259 im.startTransaction();
1260 loggingContext.metricEnded();
1261 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1262 } catch (AdministrativeStateException ae){
1263 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1264 + " state of " + im.getStateManager().getAdminState()
1265 + "\n Exception Message: " + ae.getMessage();
1266 LOGGER.info(message, ae);
1267 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1268 loggingContext.transactionEnded();
1269 PolicyLogger.audit("Transaction Failed - See Error.log");
1270 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1272 }catch (StandbyStatusException se) {
1273 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1274 + " of " + im.getStateManager().getStandbyStatus()
1275 + "\n Exception Message: " + se.getMessage();
1276 LOGGER.info(message, se);
1277 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1278 loggingContext.transactionEnded();
1279 PolicyLogger.audit("Transaction Failed - See Error.log");
1280 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1283 loggingContext.metricStarted();
1284 XACMLRest.dumpRequest(request);
1285 loggingContext.metricEnded();
1286 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1287 String groupId = request.getParameter("groupId");
1288 String apiflag = request.getParameter("apiflag");
1289 if (groupId != null) {
1290 // Is this from the Admin Console or API?
1292 if(!authorizeRequest(request)){
1293 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1294 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1295 loggingContext.transactionEnded();
1296 PolicyLogger.audit("Transaction Failed - See Error.log");
1297 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1300 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1302 loggingContext.metricStarted();
1303 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1304 loggingContext.metricEnded();
1305 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1306 } catch (Exception e) {
1307 LOGGER.error("Exception Occured"+e);
1309 if(apiRequestHandler.getNewGroup()!=null){
1310 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1314 // this is from the Admin Console, so handle separately
1316 loggingContext.metricStarted();
1317 doACDelete(request, response, groupId, loggingContext);
1318 loggingContext.metricEnded();
1319 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1320 } catch (IOException e) {
1323 loggingContext.transactionEnded();
1324 PolicyLogger.audit("Transaction Ended Successfully");
1325 im.endTransaction();
1328 //Catch anything that fell through
1329 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1330 loggingContext.transactionEnded();
1331 PolicyLogger.audit("Transaction Failed - See Error.log");
1332 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1333 im.endTransaction();
1336 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1337 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1338 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1339 if (localRootPolicies == null || localReferencedPolicies == null) {
1340 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1343 // Compare the policies and pipconfig properties to the pdpProperties
1345 // the policy properties includes only xacml.rootPolicies and
1346 // xacml.referencedPolicies without any .url entries
1347 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1348 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1349 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1350 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1351 pdpPipConfig.equals(pipconfig)) {
1352 // The PDP is current
1355 } catch (Exception e) {
1356 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1357 // or if there are policies that do not have a corresponding ".url" property.
1358 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1359 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1364 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1365 String lists[] = new String[2];
1366 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1367 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1368 for (String list : lists) {
1369 if (list != null && list.isEmpty() == false) {
1370 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1371 String url = urlPath + "?id=" + id;
1372 LOGGER.info("Policy URL for " + id + ": " + url);
1373 policies.setProperty(id + ".url", url);
1379 protected String getPDPID(HttpServletRequest request) {
1380 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1381 if (pdpURL == null || pdpURL.isEmpty()) {
1382 // Should send back its port for identification
1383 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1389 protected String getPDPJMX(HttpServletRequest request) {
1390 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1391 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1392 // Should send back its port for identification
1393 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1400 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1405 * @param loggingContext
1406 * @throws ServletException
1407 * @throws IOException
1409 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1410 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1411 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1413 // for PUT operations the group may or may not need to exist before the operation can be done
1414 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1416 // get the request input stream content into a String
1418 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1419 scanner.useDelimiter("\\A");
1420 json = scanner.hasNext() ? scanner.next() : "";
1423 PolicyLogger.info("pushPolicy request from API: " + json);
1425 // convert Object sent as JSON into local object
1426 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1428 //Get the current policies from the Group and Add the new one
1429 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1430 currentPoliciesInGroup = group.getPolicies();
1431 //If the selected policy is in the group we must remove the old version of it
1432 LOGGER.info("Removing old version of the policy");
1433 for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1434 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1435 group.removePolicy(existingPolicy);
1436 LOGGER.info("Removing policy: " + existingPolicy);
1441 // Assume that this is an update of an existing PDP Group
1442 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1444 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1445 } catch(Exception e){
1446 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1447 +"group="+group.getId());
1448 throw new PAPException(e.getMessage());
1451 LOGGER.info("Calling updatGroup() with new group");
1452 papEngine.updateGroup(group);
1453 String policyId = "empty";
1454 if(policy !=null && policy.getId() != null){
1455 policyId = policy.getId();
1457 if(!policyId.matches(REGEX) ){
1458 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1459 response.addHeader("error",ADD_GROUP_ERROR);
1460 response.addHeader("message", "Policy Id is not valid");
1463 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1464 response.addHeader("operation", "push");
1465 response.addHeader("policyId", policyId);
1466 response.addHeader("groupId", groupId);
1468 LOGGER.info("Group '" + group.getId() + "' updated");
1470 loggingContext.metricStarted();
1471 acPutTransaction.commitTransaction();
1472 loggingContext.metricEnded();
1473 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1474 loggingContext.metricStarted();
1476 loggingContext.metricEnded();
1477 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1479 // Group changed, which might include changing the policies
1480 groupChanged(group, loggingContext);
1481 loggingContext.transactionEnded();
1482 LOGGER.info("Success");
1484 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1485 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1486 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1487 LOGGER.debug("Precheck Successful.");
1491 PolicyLogger.audit("Transaction Ended Successfully");
1493 } catch (PAPException e) {
1494 acPutTransaction.rollbackTransaction();
1495 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1496 loggingContext.transactionEnded();
1497 PolicyLogger.audit("Transaction Failed - See Error.log");
1498 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1499 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1500 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1501 response.addHeader("error",ADD_GROUP_ERROR);
1502 response.addHeader("message", message);
1508 * Requests from the Admin Console for operations not on single specific objects
1513 * @param loggingContext
1514 * @throws ServletException
1515 * @throws IOException
1517 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1518 PolicyDBDaoTransaction doACPostTransaction = null;
1520 String groupName = request.getParameter("groupName");
1521 String groupDescription = request.getParameter("groupDescription");
1522 String apiflag = request.getParameter("apiflag");
1523 if (groupName != null && groupDescription != null) {
1524 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1525 loggingContext.setServiceName("AC:PAP.createGroup");
1526 String unescapedName = null;
1527 String unescapedDescription = null;
1529 unescapedName = URLDecoder.decode(groupName, "UTF-8");
1530 unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1531 } catch (UnsupportedEncodingException e) {
1534 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1536 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1537 papEngine.newGroup(unescapedName, unescapedDescription);
1538 loggingContext.metricStarted();
1539 newGroupTransaction.commitTransaction();
1540 loggingContext.metricEnded();
1541 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1542 } catch (Exception e) {
1543 newGroupTransaction.rollbackTransaction();
1544 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1545 loggingContext.transactionEnded();
1546 PolicyLogger.audit("Transaction Failed - See Error.log");
1547 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1550 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1551 if (LOGGER.isDebugEnabled()) {
1552 LOGGER.debug("New Group '" + groupId + "' created");
1554 // tell the Admin Consoles there is a change
1555 loggingContext.metricStarted();
1557 loggingContext.metricEnded();
1558 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1559 // new group by definition has no PDPs, so no need to notify them of changes
1560 loggingContext.transactionEnded();
1561 PolicyLogger.audit("Transaction Failed - See Error.log");
1562 auditLogger.info("Success");
1563 PolicyLogger.audit("Transaction Ended Successfully");
1566 // for all remaining POST operations the group must exist before the operation can be done
1567 OnapPDPGroup group = null;
1569 group = papEngine.getGroup(groupId);
1570 } catch (PAPException e){
1573 if (group == null) {
1574 String message = "Unknown groupId '" + groupId + "'";
1575 //for fixing Header Manipulation of Fortify issue
1576 if(!message.matches(REGEX)){
1577 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1578 response.addHeader("error",ADD_GROUP_ERROR);
1579 response.addHeader("message", "GroupId Id is not valid");
1582 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1583 loggingContext.transactionEnded();
1584 PolicyLogger.audit("Transaction Failed - See Error.log");
1586 response.addHeader("error", "unknownGroupId");
1587 response.addHeader("operation", "push");
1588 response.addHeader("message", message);
1589 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1591 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1596 // If the request contains a policyId then we know we are pushing the policy to PDP
1597 if (request.getParameter("policyId") != null) {
1600 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1601 LOGGER.info("PushPolicy Request From The API");
1603 loggingContext.setServiceName("AC:PAP.postPolicy");
1604 LOGGER.info("PushPolicy Request From The AC");
1607 String policyId = request.getParameter("policyId");
1608 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1609 StdPDPGroup updatedGroup = null;
1611 //Copying the policy to the file system and updating groups in database
1612 LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1613 updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1614 loggingContext.metricStarted();
1615 addPolicyToGroupTransaction.commitTransaction();
1616 loggingContext.metricEnded();
1617 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1618 LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1620 } catch (Exception e) {
1621 addPolicyToGroupTransaction.rollbackTransaction();
1622 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1623 //for fixing Header Manipulation of Fortify issue
1624 if(!message.matches(REGEX)){
1625 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1626 response.addHeader("error",ADD_GROUP_ERROR);
1627 response.addHeader("message", "Policy Id is not valid");
1630 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1631 loggingContext.transactionEnded();
1632 PolicyLogger.audit("Transaction Failed - See Error.log");
1634 response.addHeader("error", "policyCopyError");
1635 response.addHeader("message", message);
1636 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1638 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1643 if(apiflag != null){
1645 * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1646 * The GUI does this from the POLICY-SDK-APP code.
1649 // Get new transaction to perform updateGroup()
1650 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1652 // get the request content into a String and read the inputStream into a buffer
1653 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1654 scanner.useDelimiter("\\A");
1655 String json = scanner.hasNext() ? scanner.next() : "";
1658 // convert Object sent as JSON into local object
1659 ObjectMapper mapper = new ObjectMapper();
1660 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1661 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1663 LOGGER.info("Request JSON Payload: " + json);
1665 // Assume that this is an update of an existing PDP Group
1666 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1668 acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1669 } catch(Exception e){
1670 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1672 throw new PAPException(e.getMessage());
1675 LOGGER.info("Calling updatGroup() with new group");
1676 papEngine.updateGroup(updatedGroup);
1678 LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1680 // Commit transaction to send notification to other PAPs
1681 loggingContext.metricStarted();
1682 acPutTransaction.commitTransaction();
1683 loggingContext.metricEnded();
1684 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1685 loggingContext.metricStarted();
1688 loggingContext.metricEnded();
1689 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1691 // Group changed to send notification to PDPs, which might include changing the policies
1692 groupChanged(updatedGroup,loggingContext);
1693 loggingContext.transactionEnded();
1694 LOGGER.info("Success");
1696 if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1697 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1698 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1699 LOGGER.debug("Precheck Successful.");
1703 //delete temporary policy file from the bin directory
1704 Files.deleteIfExists(Paths.get(policy.getId()));
1706 } catch (Exception e) {
1707 acPutTransaction.rollbackTransaction();
1708 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1709 loggingContext.transactionEnded();
1710 PolicyLogger.audit("Transaction Failed - See Error.log");
1711 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1712 LOGGER.error(message);
1713 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1714 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1715 response.addHeader("error",ADD_GROUP_ERROR);
1716 response.addHeader("message", message);
1721 // policy file copied ok and the Group was updated on the PDP
1722 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1723 response.addHeader("operation", "push");
1724 response.addHeader("policyId", policyId);
1725 response.addHeader("groupId", groupId);
1727 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1728 loggingContext.transactionEnded();
1729 auditLogger.info("Success");
1730 LOGGER.info("Transaction Ended Successfully");
1733 } else if (request.getParameter("default") != null) {
1734 // Args: group=<groupId> default=true <= make default
1735 // change the current default group to be the one identified in the request.
1736 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1737 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1738 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1739 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1741 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1742 papEngine.setDefaultGroup(group);
1743 loggingContext.metricStarted();
1744 setDefaultGroupTransaction.commitTransaction();
1745 loggingContext.metricEnded();
1746 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1747 } catch (Exception e) {
1748 setDefaultGroupTransaction.rollbackTransaction();
1749 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1750 loggingContext.transactionEnded();
1751 PolicyLogger.audit("Transaction Failed - See Error.log");
1752 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1755 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1756 if (LOGGER.isDebugEnabled()) {
1757 LOGGER.debug("Group '" + groupId + "' set to be default");
1759 // Notify the Admin Consoles that something changed
1760 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1761 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1762 loggingContext.metricStarted();
1764 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1765 loggingContext.metricEnded();
1766 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1767 loggingContext.transactionEnded();
1768 auditLogger.info("Success");
1769 LOGGER.info("Transaction Ended Successfully");
1771 } else if (request.getParameter("pdpId") != null) {
1772 doACPostTransaction = policyDBDao.getNewTransaction();
1773 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1774 loggingContext.setServiceName("AC:PAP.movePDP");
1775 String pdpId = request.getParameter("pdpId");
1776 OnapPDP pdp = papEngine.getPDP(pdpId);
1777 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1779 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1780 }catch(Exception e){
1781 doACPostTransaction.rollbackTransaction();
1782 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1783 " Error while moving pdp in the database: "
1784 +"pdp="+pdp.getId()+",to group="+group.getId());
1785 throw new PAPException(e.getMessage());
1787 papEngine.movePDP((OnapPDP) pdp, group);
1788 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1789 if (LOGGER.isDebugEnabled()) {
1790 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1792 // update the status of both the original group and the new one
1793 ((StdPDPGroup)originalGroup).resetStatus();
1794 ((StdPDPGroup)group).resetStatus();
1795 // Notify the Admin Consoles that something changed
1796 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1797 loggingContext.metricStarted();
1799 loggingContext.metricEnded();
1800 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1801 // Need to notify the PDP that it's config may have changed
1802 pdpChanged(pdp, loggingContext);
1803 loggingContext.metricStarted();
1804 doACPostTransaction.commitTransaction();
1805 loggingContext.metricEnded();
1806 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1807 loggingContext.transactionEnded();
1808 auditLogger.info("Success");
1809 PolicyLogger.audit("Transaction Ended Successfully");
1812 } catch (PAPException e) {
1813 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1814 loggingContext.transactionEnded();
1815 PolicyLogger.audit("Transaction Failed - See Error.log");
1816 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1822 * Requests from the Admin Console to GET info about the Groups and PDPs
1827 * @param loggingContext
1828 * @throws ServletException
1829 * @throws IOException
1831 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1833 String parameterDefault = request.getParameter("default");
1834 String pdpId = request.getParameter("pdpId");
1835 String pdpGroup = request.getParameter("getPDPGroup");
1836 if ("".equals(groupId)) {
1837 // request IS from AC but does not identify a group by name
1838 if (parameterDefault != null) {
1839 // Request is for the Default group (whatever its id)
1840 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1841 OnapPDPGroup group = papEngine.getDefaultGroup();
1842 // convert response object to JSON and include in the response
1843 mapperWriteValue(new ObjectMapper(), response, group);
1844 if (LOGGER.isDebugEnabled()) {
1845 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1847 response.setStatus(HttpServletResponse.SC_OK);
1848 response.setHeader("content-type", "application/json");
1850 response.getOutputStream().close();
1851 } catch (IOException e){
1854 loggingContext.transactionEnded();
1855 auditLogger.info("Success");
1856 PolicyLogger.audit("Transaction Ended Successfully");
1858 } else if (pdpId != null) {
1859 // Request is related to a PDP
1860 if (pdpGroup == null) {
1861 // Request is for the (unspecified) group containing a given PDP
1862 loggingContext.setServiceName("AC:PAP.getPDP");
1865 pdp = papEngine.getPDP(pdpId);
1866 }catch(PAPException e){
1869 // convert response object to JSON and include in the response
1870 mapperWriteValue(new ObjectMapper(), response, pdp);
1871 if (LOGGER.isDebugEnabled()) {
1872 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1874 response.setStatus(HttpServletResponse.SC_OK);
1875 response.setHeader("content-type", "application/json");
1877 response.getOutputStream().close();
1878 } catch (IOException e){
1881 loggingContext.transactionEnded();
1882 auditLogger.info("Success");
1883 PolicyLogger.audit("Transaction Ended Successfully");
1886 // Request is for the group containing a given PDP
1887 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1888 OnapPDPGroup group =null;
1890 OnapPDP pdp = papEngine.getPDP(pdpId);
1891 group = papEngine.getPDPGroup((OnapPDP) pdp);
1892 }catch(PAPException e){
1895 // convert response object to JSON and include in the response
1896 mapperWriteValue(new ObjectMapper(), response, group);
1897 if (LOGGER.isDebugEnabled()) {
1898 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1900 response.setStatus(HttpServletResponse.SC_OK);
1901 response.setHeader("content-type", "application/json");
1903 response.getOutputStream().close();
1904 } catch (IOException e){
1907 loggingContext.transactionEnded();
1908 auditLogger.info("Success");
1909 PolicyLogger.audit("Transaction Ended Successfully");
1913 // request is for top-level properties about all groups
1914 loggingContext.setServiceName("AC:PAP.getAllGroups");
1915 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
1916 // convert response object to JSON and include in the response
1917 mapperWriteValue(new ObjectMapper(), response, groups);
1918 if (LOGGER.isDebugEnabled()) {
1919 LOGGER.debug("GET All groups req");
1921 response.setStatus(HttpServletResponse.SC_OK);
1922 response.setHeader("content-type", "application/json");
1924 response.getOutputStream().close();
1925 } catch (IOException e){
1928 loggingContext.transactionEnded();
1929 auditLogger.info("Success");
1930 PolicyLogger.audit("Transaction Ended Successfully");
1934 // for all other GET operations the group must exist before the operation can be done
1935 OnapPDPGroup group = null;
1937 group = papEngine.getGroup(groupId);
1938 } catch(PAPException e){
1941 if (group == null) {
1942 String message = "Unknown groupId '" + groupId + "'";
1943 //for fixing Header Manipulation of Fortify issue
1944 if(!message.matches(REGEX)){
1945 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1946 response.addHeader("error",ADD_GROUP_ERROR);
1947 response.addHeader("message", "Group Id is not valid");
1950 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1951 loggingContext.transactionEnded();
1952 PolicyLogger.audit("Transaction Failed - See Error.log");
1953 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1956 // Figure out which request this is based on the parameters
1957 String policyId = request.getParameter("policyId");
1958 if (policyId != null) {
1959 // retrieve a policy
1960 loggingContext.setServiceName("AC:PAP.getPolicy");
1961 // convert response object to JSON and include in the response
1962 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1963 loggingContext.transactionEnded();
1964 PolicyLogger.audit("Transaction Failed - See Error.log");
1965 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1967 // No other parameters, so return the identified Group
1968 loggingContext.setServiceName("AC:PAP.getGroup");
1969 // convert response object to JSON and include in the response
1970 mapperWriteValue(new ObjectMapper(), response, group);
1971 if (LOGGER.isDebugEnabled()) {
1972 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1974 response.setStatus(HttpServletResponse.SC_OK);
1975 response.setHeader("content-type", "application/json");
1977 response.getOutputStream().close();
1978 } catch (IOException e){
1981 loggingContext.transactionEnded();
1982 auditLogger.info("Success");
1983 PolicyLogger.audit("Transaction Ended Successfully");
1986 // Currently there are no other GET calls from the AC.
1987 // 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.
1988 // Other GETs that could be called:
1989 // Specific Group (groupId=<groupId>)
1990 // A Policy (groupId=<groupId> policyId=<policyId>)
1991 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1992 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1993 loggingContext.transactionEnded();
1994 PolicyLogger.audit("Transaction Failed - See Error.log");
1995 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1996 } catch (PAPException e) {
1997 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1998 loggingContext.transactionEnded();
1999 PolicyLogger.audit("Transaction Failed - See Error.log");
2000 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2006 * Requests from the Admin Console to create new items or update existing ones
2011 * @param loggingContext
2012 * @throws ServletException
2013 * @throws IOException
2015 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2016 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
2018 // for PUT operations the group may or may not need to exist before the operation can be done
2019 OnapPDPGroup group = papEngine.getGroup(groupId);
2020 // determine the operation needed based on the parameters in the request
2021 // for remaining operations the group must exist before the operation can be done
2022 if (group == null) {
2023 String message = "Unknown groupId '" + groupId + "'";
2024 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2025 loggingContext.transactionEnded();
2026 PolicyLogger.audit("Transaction Failed - See Error.log");
2027 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
2030 if (request.getParameter("policy") != null) {
2031 // 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)
2032 loggingContext.setServiceName("AC:PAP.putPolicy");
2033 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
2034 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2035 loggingContext.transactionEnded();
2036 PolicyLogger.audit("Transaction Failed - See Error.log");
2037 auditLogger.info("Success");
2038 PolicyLogger.audit("Transaction Ended Successfully");
2040 } else if (request.getParameter("pdpId") != null) {
2041 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
2042 String pdpId = request.getParameter("pdpId");
2043 if (papEngine.getPDP(pdpId) == null) {
2044 loggingContext.setServiceName("AC:PAP.createPDP");
2046 loggingContext.setServiceName("AC:PAP.updatePDP");
2048 // get the request content into a String
2050 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2052 Scanner scanner = new Scanner(request.getInputStream());
2053 scanner.useDelimiter("\\A");
2054 json = scanner.hasNext() ? scanner.next() : "";
2056 }catch(IOException e){
2059 LOGGER.info("JSON request from AC: " + json);
2060 // convert Object sent as JSON into local object
2061 ObjectMapper mapper = new ObjectMapper();
2062 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
2063 if (pdpId == null ||
2064 objectFromJSON == null ||
2065 ! (objectFromJSON instanceof StdPDP) ||
2066 ((StdPDP)objectFromJSON).getId() == null ||
2067 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2068 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2069 loggingContext.transactionEnded();
2070 PolicyLogger.audit("Transaction Failed - See Error.log");
2071 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
2073 StdPDP pdp = (StdPDP) objectFromJSON;
2075 OnapPDP oPDP = null;
2077 oPDP = papEngine.getPDP(pdpId);
2078 }catch (PAPException e){
2082 // this is a request to create a new PDP object
2084 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
2085 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2086 } catch(Exception e){
2087 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2088 +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2089 throw new PAPException(e.getMessage());
2092 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2093 }catch(PAPException e){
2098 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2099 } catch(Exception e){
2100 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2101 +"pdp="+ pdp.getId());
2102 throw new PAPException(e.getMessage());
2104 // this is a request to update the pdp
2106 papEngine.updatePDP(pdp);
2107 }catch(PAPException e){
2111 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2112 if (LOGGER.isDebugEnabled()) {
2113 LOGGER.debug("PDP '" + pdpId + "' created/updated");
2115 // adjust the group's state including the new PDP
2116 ((StdPDPGroup)group).resetStatus();
2117 // tell the Admin Consoles there is a change
2118 loggingContext.metricStarted();
2120 loggingContext.metricEnded();
2121 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2122 // this might affect the PDP, so notify it of the change
2123 pdpChanged(pdp, loggingContext);
2124 loggingContext.metricStarted();
2125 acPutTransaction.commitTransaction();
2126 loggingContext.metricEnded();
2127 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2128 loggingContext.transactionEnded();
2129 auditLogger.info("Success");
2130 PolicyLogger.audit("Transaction Ended Successfully");
2134 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2135 +"pdp=null" + ",to group="+group.getId());
2136 throw new PAPException("PDP is null");
2137 } catch(Exception e){
2138 throw new PAPException("PDP is null" + e.getMessage() +e);
2141 } else if (request.getParameter("pipId") != null) {
2142 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
2143 loggingContext.setServiceName("AC:PAP.putPIP");
2144 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2145 loggingContext.transactionEnded();
2146 PolicyLogger.audit("Transaction Failed - See Error.log");
2147 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2150 // Assume that this is an update of an existing PDP Group
2151 // ARGS: group=<groupId> <= Update an Existing Group
2152 loggingContext.setServiceName("AC:PAP.updateGroup");
2153 // get the request content into a String
2155 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2157 Scanner scanner = new Scanner(request.getInputStream());
2158 scanner.useDelimiter("\\A");
2159 json = scanner.hasNext() ? scanner.next() : "";
2161 }catch(IOException e){
2164 LOGGER.info("JSON request from AC: " + json);
2165 // convert Object sent as JSON into local object
2166 ObjectMapper mapper = new ObjectMapper();
2167 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
2168 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2169 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2170 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2171 loggingContext.transactionEnded();
2172 PolicyLogger.audit("Transaction Failed - See Error.log");
2173 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
2175 // The Path on the PAP side is not carried on the RESTful interface with the AC
2176 // (because it is local to the PAP)
2177 // so we need to fill that in before submitting the group for update
2178 if(objectFromJSON != null){
2179 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2182 if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
2183 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
2185 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2187 } catch(Exception e){
2188 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2189 +"group="+group.getId());
2191 throw new PAPException(e.getMessage());
2194 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
2195 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
2196 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
2197 LOGGER.debug("Precheck Successful.");
2200 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2201 }catch(PAPException e){
2204 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2205 if (LOGGER.isDebugEnabled()) {
2206 LOGGER.debug("Group '" + group.getId() + "' updated");
2208 loggingContext.metricStarted();
2209 acPutTransaction.commitTransaction();
2210 loggingContext.metricEnded();
2211 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2212 // tell the Admin Consoles there is a change
2213 loggingContext.metricStarted();
2215 loggingContext.metricEnded();
2216 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2217 // Group changed, which might include changing the policies
2218 groupChanged(group, loggingContext);
2219 loggingContext.transactionEnded();
2220 auditLogger.info("Success");
2221 PolicyLogger.audit("Transaction Ended Successfully");
2224 } catch (PAPException e) {
2226 acPutTransaction.rollbackTransaction();
2227 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2228 loggingContext.transactionEnded();
2229 PolicyLogger.audit("Transaction Failed - See Error.log");
2230 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2236 * Requests from the Admin Console to delete/remove items
2241 * @param loggingContext
2242 * @throws ServletException
2243 * @throws IOException
2245 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2246 //This code is to allow deletes to propagate to the database since delete is not implemented
2247 String isDeleteNotify = request.getParameter("isDeleteNotify");
2248 if(isDeleteNotify != null){
2249 String policyToDelete = request.getParameter("policyToDelete");
2251 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
2252 } catch(UnsupportedEncodingException e){
2253 LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
2254 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
2257 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
2259 deleteTransaction.deletePolicy(policyToDelete);
2260 } catch(Exception e){
2261 deleteTransaction.rollbackTransaction();
2262 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
2263 + "\nfailure with the following exception: " + e);
2266 loggingContext.metricStarted();
2267 deleteTransaction.commitTransaction();
2268 loggingContext.metricEnded();
2269 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2270 response.setStatus(HttpServletResponse.SC_OK);
2273 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2275 // for all DELETE operations the group must exist before the operation can be done
2276 loggingContext.setServiceName("AC:PAP.delete");
2277 OnapPDPGroup group = papEngine.getGroup(groupId);
2278 if (group == null) {
2279 String message = "Unknown groupId '" + groupId + "'";
2280 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2281 loggingContext.transactionEnded();
2282 PolicyLogger.audit("Transaction Failed - See Error.log");
2283 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2286 // determine the operation needed based on the parameters in the request
2287 if (request.getParameter("policy") != null) {
2288 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
2289 loggingContext.setServiceName("AC:PAP.deletePolicy");
2290 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2291 loggingContext.transactionEnded();
2292 PolicyLogger.audit("Transaction Failed - See Error.log");
2293 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2295 } else if (request.getParameter("pdpId") != null) {
2296 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
2297 String pdpId = request.getParameter("pdpId");
2298 OnapPDP pdp = papEngine.getPDP(pdpId);
2300 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2301 } catch(Exception e){
2302 throw new PAPException(e);
2305 papEngine.removePDP((OnapPDP) pdp);
2306 }catch(PAPException e){
2309 // adjust the status of the group, which may have changed when we removed this PDP
2310 ((StdPDPGroup)group).resetStatus();
2311 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2312 loggingContext.metricStarted();
2314 loggingContext.metricEnded();
2315 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2316 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2317 pdpChanged(pdp, loggingContext);
2318 loggingContext.metricStarted();
2319 removePdpOrGroupTransaction.commitTransaction();
2320 loggingContext.metricEnded();
2321 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2322 loggingContext.transactionEnded();
2323 auditLogger.info("Success");
2324 PolicyLogger.audit("Transaction Ended Successfully");
2326 } else if (request.getParameter("pipId") != null) {
2327 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2328 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2329 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2330 loggingContext.transactionEnded();
2331 PolicyLogger.audit("Transaction Failed - See Error.log");
2332 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2335 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
2336 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2337 OnapPDPGroup moveToGroup = null;
2338 if (moveToGroupId != null) {
2340 moveToGroup = papEngine.getGroup(moveToGroupId);
2341 }catch(PAPException e){
2345 // get list of PDPs in the group being deleted so we can notify them that they got changed
2346 Set<OnapPDP> movedPDPs = new HashSet<>();
2347 movedPDPs.addAll(group.getOnapPdps());
2348 // do the move/remove
2350 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2351 } catch(Exception e){
2352 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2353 throw new PAPException(e.getMessage());
2356 papEngine.removeGroup(group, moveToGroup);
2357 }catch(PAPException e){
2360 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2361 loggingContext.metricStarted();
2363 loggingContext.metricEnded();
2364 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2365 // notify any PDPs in the removed set that their config may have changed
2366 for (OnapPDP pdp : movedPDPs) {
2367 pdpChanged(pdp, loggingContext);
2369 loggingContext.metricStarted();
2370 removePdpOrGroupTransaction.commitTransaction();
2371 loggingContext.metricEnded();
2372 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2373 loggingContext.transactionEnded();
2374 auditLogger.info("Success");
2375 PolicyLogger.audit("Transaction Ended Successfully");
2378 } catch (PAPException e) {
2379 removePdpOrGroupTransaction.rollbackTransaction();
2380 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2381 loggingContext.transactionEnded();
2382 PolicyLogger.audit("Transaction Failed - See Error.log");
2383 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2389 * Heartbeat thread - periodically check on PDPs' status
2391 * Heartbeat with all known PDPs.
2393 * Implementation note:
2395 * The PDPs are contacted Sequentially, not in Parallel.
2397 * If we did this in parallel using multiple threads we would simultaneously use
2401 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2402 * when user changes occur.
2403 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2405 * The Sequential operation does a heartbeat request to each PDP one at a time.
2406 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2407 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2408 * it could take a long time to cycle through all of the PDPs.
2409 * That means that this may not notice a PDP being down in a predictable time.
2411 private class Heartbeat implements Runnable {
2412 private PAPPolicyEngine papEngine;
2413 private Set<OnapPDP> pdps = new HashSet<>();
2414 private int heartbeatInterval;
2415 private int heartbeatTimeout;
2417 public volatile boolean isRunning = false;
2419 public synchronized boolean isRunning() {
2420 return this.isRunning;
2423 public synchronized void terminate() {
2424 this.isRunning = false;
2427 public Heartbeat(PAPPolicyEngine papEngine2) {
2428 papEngine = papEngine2;
2429 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2430 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2435 // Set ourselves as running
2436 synchronized(this) {
2437 this.isRunning = true;
2439 HashMap<String, URL> idToURLMap = new HashMap<>();
2441 while (this.isRunning()) {
2442 // Wait the given time
2443 Thread.sleep(heartbeatInterval);
2444 // get the list of PDPs (may have changed since last time)
2446 synchronized(papEngine) {
2448 for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2449 for (OnapPDP p : g.getOnapPdps()) {
2453 } catch (PAPException e) {
2454 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2457 // Check for shutdown
2458 if (this.isRunning() == false) {
2459 LOGGER.info("isRunning is false, getting out of loop.");
2462 // try to get the summary status from each PDP
2463 boolean changeSeen = false;
2464 for (OnapPDP pdp : pdps) {
2465 // Check for shutdown
2466 if (this.isRunning() == false) {
2467 LOGGER.info("isRunning is false, getting out of loop.");
2470 // the id of the PDP is its url (though we add a query parameter)
2471 URL pdpURL = idToURLMap.get(pdp.getId());
2472 if (pdpURL == null) {
2473 // haven't seen this PDP before
2474 String fullURLString = null;
2477 if(CheckPDP.validateID(pdp.getId())){
2478 fullURLString = pdp.getId() + "?type=hb";
2479 pdpURL = new URL(fullURLString);
2480 idToURLMap.put(pdp.getId(), pdpURL);
2482 } catch (MalformedURLException e) {
2483 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2487 // Do a GET with type HeartBeat
2488 String newStatus = "";
2489 HttpURLConnection connection = null;
2491 // Open up the connection
2493 connection = (HttpURLConnection)pdpURL.openConnection();
2494 // Setup our method and headers
2495 connection.setRequestMethod("GET");
2496 connection.setConnectTimeout(heartbeatTimeout);
2498 String encoding = CheckPDP.getEncoding(pdp.getId());
2499 if(encoding !=null){
2500 connection.setRequestProperty("Authorization", "Basic " + encoding);
2503 connection.connect();
2504 if (connection.getResponseCode() == 204) {
2505 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2506 if (LOGGER.isDebugEnabled()) {
2507 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2510 // anything else is an unexpected result
2511 newStatus = PDPStatus.Status.UNKNOWN.toString();
2512 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2515 } catch (UnknownHostException e) {
2516 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2517 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2518 } catch (SocketTimeoutException e) {
2519 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2520 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2521 } catch (ConnectException e) {
2522 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2523 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2524 } catch (Exception e) {
2525 newStatus = PDPStatus.Status.UNKNOWN.toString();
2526 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2528 // cleanup the connection
2529 if(connection != null)
2530 connection.disconnect();
2532 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2533 if (LOGGER.isDebugEnabled()) {
2534 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2537 setPDPSummaryStatus(pdp, newStatus);
2538 } catch (PAPException e) {
2539 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2544 // Check for shutdown
2545 if (this.isRunning() == false) {
2546 LOGGER.info("isRunning is false, getting out of loop.");
2549 // if any of the PDPs changed state, tell the ACs to update
2554 } catch (InterruptedException e) {
2555 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2557 Thread.currentThread().interrupt();
2563 * HELPER to change Group status when PDP status is changed
2564 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2566 private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2567 setPDPSummaryStatus(pdp, newStatus.toString());
2570 private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2571 synchronized(papEngine) {
2572 StdPDPStatus status = new StdPDPStatus();
2573 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2574 ((StdPDP)pdp).setStatus(status);
2575 // now adjust the group
2576 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2577 // if the PDP was just deleted it may transiently exist but not be in a group
2578 if (group != null) {
2579 group.resetStatus();
2585 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2586 * in the PDP group directories
2589 public void changed() {
2590 // all PDPs in all groups need to be updated/sync'd
2591 Set<OnapPDPGroup> groups;
2593 groups = papEngine.getOnapPDPGroups();
2594 } catch (PAPException e) {
2595 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2596 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2598 for (OnapPDPGroup group : groups) {
2599 groupChanged(group);
2603 public void changed(ONAPLoggingContext loggingContext) {
2604 // all PDPs in all groups need to be updated/sync'd
2605 Set<OnapPDPGroup> groups;
2607 groups = papEngine.getOnapPDPGroups();
2608 } catch (PAPException e) {
2609 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2610 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2612 for (OnapPDPGroup group : groups) {
2613 groupChanged(group, loggingContext);
2618 public void groupChanged(OnapPDPGroup group) {
2619 // all PDPs within one group need to be updated/sync'd
2620 for (OnapPDP pdp : group.getOnapPdps()) {
2625 public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2626 // all PDPs within one group need to be updated/sync'd
2627 for (OnapPDP pdp : group.getOnapPdps()) {
2628 pdpChanged(pdp, loggingContext);
2633 public void pdpChanged(OnapPDP pdp) {
2634 // kick off a thread to do an event notification for each PDP.
2635 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2636 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2637 Thread t = new Thread(new UpdatePDPThread(pdp));
2638 if(CheckPDP.validateID(pdp.getId())){
2643 public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2644 // kick off a thread to do an event notification for each PDP.
2645 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2646 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2647 Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2648 if(CheckPDP.validateID(pdp.getId())){
2653 private class UpdatePDPThread implements Runnable {
2654 private OnapPDP pdp;
2655 private String requestId;
2656 private ONAPLoggingContext loggingContext;
2658 public UpdatePDPThread(OnapPDP pdp) {
2662 public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2664 if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2665 this.requestId = loggingContext.getRequestID();
2667 this.loggingContext = loggingContext;
2671 // send the current configuration to one PDP
2672 HttpURLConnection connection = null;
2673 // get a new logging context for the thread
2675 if (this.loggingContext == null) {
2676 loggingContext = new ONAPLoggingContext(baseLoggingContext);
2678 } catch (Exception e) {
2679 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2680 // Since this is a server-side error, it probably does not reflect a problem on the client,
2681 // so do not change the PDP status.
2685 loggingContext.setServiceName("PAP:PDP.putConfig");
2686 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2687 if ((requestId == null) || (requestId == "")) {
2688 UUID requestID = UUID.randomUUID();
2689 loggingContext.setRequestID(requestID.toString());
2690 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2692 loggingContext.setRequestID(requestId);
2693 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2695 loggingContext.transactionStarted();
2696 // the Id of the PDP is its URL
2697 if (LOGGER.isDebugEnabled()) {
2698 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2700 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2701 //TODO (need to change "cache=", implying getting some input saying which to change)
2702 URL url = new URL(pdp.getId() + "?cache=all");
2703 // Open up the connection
2704 connection = (HttpURLConnection)url.openConnection();
2705 // Setup our method and headers
2706 connection.setRequestMethod("PUT");
2708 String encoding = CheckPDP.getEncoding(pdp.getId());
2709 if(encoding !=null){
2710 connection.setRequestProperty("Authorization", "Basic " + encoding);
2712 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2713 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2714 connection.setInstanceFollowRedirects(true);
2715 connection.setDoOutput(true);
2716 try (OutputStream os = connection.getOutputStream()) {
2717 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2718 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2719 if (group == null) {
2720 // create blank properties files
2721 Properties policyProperties = new Properties();
2722 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2723 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2724 policyProperties.store(os, "");
2725 Properties pipProps = new Properties();
2726 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2727 pipProps.store(os, "");
2729 // send properties from the current group
2730 group.getPolicyProperties().store(os, "");
2731 Properties policyLocations = new Properties();
2732 for (PDPPolicy policy : group.getPolicies()) {
2733 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2735 policyLocations.store(os, "");
2736 group.getPipConfigProperties().store(os, "");
2738 } catch (Exception e) {
2739 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2740 // Since this is a server-side error, it probably does not reflect a problem on the client,
2741 // so do not change the PDP status.
2745 loggingContext.metricStarted();
2746 connection.connect();
2747 loggingContext.metricEnded();
2748 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2749 if (connection.getResponseCode() == 204) {
2750 LOGGER.info("Success. We are configured correctly.");
2751 loggingContext.transactionEnded();
2752 auditLogger.info("Success. PDP is configured correctly.");
2753 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2754 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2755 } else if (connection.getResponseCode() == 200) {
2756 LOGGER.info("Success. PDP needs to update its configuration.");
2757 loggingContext.transactionEnded();
2758 auditLogger.info("Success. PDP needs to update its configuration.");
2759 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2760 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2762 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2763 loggingContext.transactionEnded();
2764 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2765 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2766 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2768 } catch (Exception e) {
2770 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2771 loggingContext.transactionEnded();
2772 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2774 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2775 } catch (PAPException e1) {
2777 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2778 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2781 // cleanup the connection
2782 if(connection != null){
2783 connection.disconnect();
2785 // tell the AC to update it's status info
2792 * RESTful Interface from PAP to ACs notifying them of changes
2794 private void notifyAC() {
2795 // kick off a thread to do one event notification for all registered ACs
2796 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2797 // as part of processing this message on their end.
2798 Thread t = new Thread(new NotifyACThread());
2802 private class NotifyACThread implements Runnable {
2804 List<String> disconnectedACs = new ArrayList<>();
2805 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2806 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2807 for (String acURL : adminConsoleURLStringList) {
2808 HttpURLConnection connection = null;
2810 acURL += "?PAPNotification=true";
2811 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2812 //TODO - If so, put correct parameters into the Query string here
2813 acURL += "&objectType=all" + "&action=update";
2814 if (LOGGER.isDebugEnabled()) {
2815 LOGGER.debug("creating url for id '" + acURL + "'");
2817 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2818 //TODO (need to change "cache=", implying getting some input saying which to change)
2819 URL url = new URL(acURL );
2820 // Open up the connection
2821 connection = (HttpURLConnection)url.openConnection();
2822 // Setup our method and headers
2823 connection.setRequestMethod("PUT");
2824 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2825 // Adding this in. It seems the HttpUrlConnection class does NOT
2826 // properly forward our headers for POST re-direction. It does so
2827 // for a GET re-direction.
2828 // So we need to handle this ourselves.
2829 //TODO - is this needed for a PUT? seems better to leave in for now?
2830 connection.setInstanceFollowRedirects(false);
2831 // Do not include any data in the PUT because this is just a
2832 // notification to the AC.
2833 // The AC will use GETs back to the PAP to get what it needs
2834 // to fill in the screens.
2836 connection.connect();
2837 if (connection.getResponseCode() == 204) {
2838 LOGGER.info("Success. We updated correctly.");
2840 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2843 } catch (Exception e) {
2844 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2845 disconnectedACs.add(acURL);
2847 // cleanup the connection
2848 if(connection != null)
2849 connection.disconnect();
2852 // remove any ACs that are no longer connected
2853 if (disconnectedACs.size() > 0) {
2854 adminConsoleURLStringList.removeAll(disconnectedACs);
2859 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2860 LOGGER.info("Test request received");
2862 im.evaluateSanity();
2863 //If we make it this far, all is well
2864 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2865 LOGGER.info(message);
2866 loggingContext.transactionEnded();
2867 PolicyLogger.audit("Transaction Failed - See Error.log");
2868 response.setStatus(HttpServletResponse.SC_OK);
2870 }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2872 if (e instanceof ForwardProgressException) {
2873 submsg = " is not making forward progress.";
2874 } else if (e instanceof AdministrativeStateException) {
2875 submsg = " Administrative State is LOCKED.";
2877 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2880 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2881 + " Exception Message: " + e.getMessage();
2882 LOGGER.info(message, e);
2883 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2884 loggingContext.transactionEnded();
2885 PolicyLogger.audit("Transaction Failed - See Error.log");
2886 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2888 }catch (Exception e) {
2889 //A subsystem is not making progress, is locked, standby or is not responding
2890 String eMsg = e.getMessage();
2892 eMsg = "No Exception Message";
2894 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2895 + " Exception Message: " + eMsg;
2896 LOGGER.info(message, e);
2897 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2898 loggingContext.transactionEnded();
2899 PolicyLogger.audit("Transaction Failed - See Error.log");
2900 //Get the specific list of subsystems that failed
2901 String ssFailureList = null;
2902 for(String failedSS : papDependencyGroupsFlatArray){
2903 if(eMsg.contains(failedSS)){
2904 if(ssFailureList == null){
2905 ssFailureList = failedSS;
2907 ssFailureList = ssFailureList.concat(","+failedSS);
2911 if(ssFailureList == null){
2912 ssFailureList = "UnknownSubSystem";
2914 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2915 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2921 * Authorizing the PEP Requests.
2923 private boolean authorizeRequest(HttpServletRequest request) {
2924 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2925 // Check if the Client is Authorized.
2926 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2933 private static void loadWebapps() throws PAPException{
2934 if(actionHome == null || configHome == null){
2935 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2937 if (webappsPath == null) {
2938 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2939 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2941 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2942 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2943 if (Files.notExists(webappsPathConfig)) {
2945 Files.createDirectories(webappsPathConfig);
2946 } catch (IOException e) {
2947 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2948 + webappsPathConfig.toAbsolutePath().toString());
2951 if (Files.notExists(webappsPathAction)) {
2953 Files.createDirectories(webappsPathAction);
2954 } catch (IOException e) {
2955 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2956 + webappsPathAction.toAbsolutePath().toString(), e);
2959 actionHome = webappsPathAction.toString();
2960 configHome = webappsPathConfig.toString();
2964 public static String getConfigHome(){
2967 } catch (PAPException e) {
2974 private static void setConfigHome(){
2975 configHome = getConfigHome();
2978 public static String getActionHome(){
2981 } catch (PAPException e) {
2988 private static void setActionHome(){
2989 actionHome = getActionHome();
2992 public static EntityManagerFactory getEmf() {
2996 public IntegrityAudit getIa() {
3000 public static String getPDPFile(){
3001 return XACMLPapServlet.pdpFile;
3004 public static String getPersistenceUnit(){
3005 return PERSISTENCE_UNIT;
3008 public static PAPPolicyEngine getPAPEngine(){
3012 public static PolicyDBDaoTransaction getDbDaoTransaction(){
3013 return policyDBDao.getNewTransaction();
3015 public static String getPapDbDriver() {
3019 public static void setPapDbDriver(String papDbDriver) {
3020 XACMLPapServlet.papDbDriver = papDbDriver;
3023 public static String getPapDbUrl() {
3027 public static void setPapDbUrl(String papDbUrl) {
3028 XACMLPapServlet.papDbUrl = papDbUrl;
3031 public static String getPapDbUser() {
3035 public static void setPapDbUser(String papDbUser) {
3036 XACMLPapServlet.papDbUser = papDbUser;
3039 public static String getPapDbPassword() {
3040 return papDbPassword;
3043 public static void setPapDbPassword(String papDbPassword) {
3044 XACMLPapServlet.papDbPassword = papDbPassword;
3047 public static String getMsOnapName() {
3051 public static void setMsOnapName(String msOnapName) {
3052 XACMLPapServlet.msOnapName = msOnapName;
3055 public static String getMsPolicyName() {
3056 return msPolicyName;
3059 public static void setMsPolicyName(String msPolicyName) {
3060 XACMLPapServlet.msPolicyName = msPolicyName;