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.IntegrityMonitorException;
68 import org.onap.policy.common.im.IntegrityMonitorProperties;
69 import org.onap.policy.common.im.StandbyStatusException;
70 import org.onap.policy.common.logging.ONAPLoggingContext;
71 import org.onap.policy.common.logging.ONAPLoggingUtils;
72 import org.onap.policy.common.logging.eelf.MessageCodes;
73 import org.onap.policy.common.logging.eelf.PolicyLogger;
74 import org.onap.policy.common.logging.flexlogger.FlexLogger;
75 import org.onap.policy.common.logging.flexlogger.Logger;
76 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
77 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
78 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
79 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
80 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
81 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
82 import org.onap.policy.rest.XACMLRest;
83 import org.onap.policy.rest.XACMLRestProperties;
84 import org.onap.policy.rest.dao.PolicyDBException;
85 import org.onap.policy.utils.CryptoUtils;
86 import org.onap.policy.utils.PolicyUtils;
87 import org.onap.policy.xacml.api.XACMLErrorConstants;
88 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
89 import org.onap.policy.xacml.api.pap.OnapPDP;
90 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
91 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
92 import org.onap.policy.xacml.std.pap.StdPDP;
93 import org.onap.policy.xacml.std.pap.StdPDPGroup;
94 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
95 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
96 import org.onap.policy.xacml.std.pap.StdPDPStatus;
98 import com.att.research.xacml.api.pap.PAPException;
99 import com.att.research.xacml.api.pap.PDPPolicy;
100 import com.att.research.xacml.api.pap.PDPStatus;
101 import com.att.research.xacml.util.FactoryException;
102 import com.att.research.xacml.util.XACMLProperties;
103 import com.fasterxml.jackson.databind.ObjectMapper;
104 import com.google.common.base.Splitter;
107 * Servlet implementation class XacmlPapServlet
110 description = "Implements the XACML PAP RESTful API.",
111 urlPatterns = { "/" },
114 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
116 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
117 private static final long serialVersionUID = 1L;
118 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
119 // audit (transaction) LOGGER
120 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
121 //Persistence Unit for JPA
122 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
123 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
125 private static final String ENVIRONMENT_HEADER = "Environment";
126 private static final String ADD_GROUP_ERROR = "addGroupError";
127 private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
129 private static final String REGEX = "[0-9a-zA-Z._ ]*";
132 * List of Admin Console URLs.
133 * Used to send notifications when configuration changes.
135 * The CopyOnWriteArrayList *should* protect from concurrency errors.
136 * This list is seldom changed but often read, so the costs of this approach make sense.
138 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
140 private static String configHome;
141 private static String actionHome;
143 * This PAP instance's own URL.
144 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
146 private static String papURL = null;
147 // The heartbeat thread.
148 private static Heartbeat heartbeat = null;
149 private static Thread heartbeatThread = null;
150 //The entity manager factory for JPA access
151 private static EntityManagerFactory emf;
152 private static PolicyDBDao policyDBDao;
154 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
156 private static PAPPolicyEngine papEngine = null;
158 * These are the parameters needed for DB access from the PAP
160 private static int papIntegrityAuditPeriodSeconds = -1;
161 private static String papDbDriver = null;
162 private static String papDbUrl = null;
163 private static String papDbUser = null;
164 private static String papDbPassword = null;
165 private static String papResourceName = null;
166 private static String[] papDependencyGroupsFlatArray = null;
167 private static String environment = null;
168 private static String pdpFile = null;
170 private transient IntegrityMonitor im;
171 private transient IntegrityAudit ia;
173 //MicroService Model Properties
174 private static String msOnapName;
175 private static String msPolicyName;
177 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
178 * this servlet starts. Its configurable by the admin.
180 private static transient Thread initiateThread = null;
181 private transient ONAPLoggingContext baseLoggingContext = null;
184 * @see HttpServlet#HttpServlet()
186 public XACMLPapServlet() {
191 * @see Servlet#init(ServletConfig)
193 public void init(ServletConfig config) throws ServletException {
196 baseLoggingContext = new ONAPLoggingContext();
197 // fixed data that will be the same in all logging output goes here
199 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
200 baseLoggingContext.setServer(hostname);
201 } catch (UnknownHostException e) {
202 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
205 XACMLRest.xacmlInit(config);
206 // Load the properties
207 XACMLRest.loadXacmlProperties(null, null);
209 * Retrieve the property values
211 setCommonProperties();
212 String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
213 if(papSiteName == null){
214 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
215 throw new PAPException("papSiteName is null");
217 String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
218 if(papNodeType == null){
219 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
220 throw new PAPException("papNodeType is null");
222 //Integer will throw an exception of anything is missing or unrecognized
223 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
224 int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
225 int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
226 //Boolean will default to false if anything is missing or unrecognized
227 boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
228 boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
229 String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
230 if(papDependencyGroups == null){
231 throw new PAPException("papDependencyGroups is null");
233 setPAPDependencyGroups(papDependencyGroups);
234 //Integer will throw an exception of anything is missing or unrecognized
235 int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
236 int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
237 int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
238 int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
239 LOGGER.debug("\n\n\n**************************************"
240 + "\n*************************************"
242 + "\n papDbDriver = " + papDbDriver
243 + "\n papDbUrl = " + papDbUrl
244 + "\n papDbUser = " + papDbUser
245 + "\n papTransWait = " + papTransWait
246 + "\n papTransTimeout = " + papTransTimeout
247 + "\n papAuditTimeout = " + papAuditTimeout
248 + "\n papAuditFlag = " + papAuditFlag
249 + "\n papFileSystemAudit = " + papFileSystemAudit
250 + "\n papResourceName = " + papResourceName
251 + "\n fpMonitorInterval = " + fpMonitorInterval
252 + "\n failedCounterThreshold = " + failedCounterThreshold
253 + "\n testTransInterval = " + testTransInterval
254 + "\n writeFpcInterval = " + writeFpcInterval
255 + "\n papSiteName = " + papSiteName
256 + "\n papNodeType = " + papNodeType
257 + "\n papDependencyGroupsList = " + papDependencyGroups
258 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
259 + "\n\n*************************************"
260 + "\n**************************************");
261 // Pull custom persistence settings
262 Properties properties;
264 properties = XACMLProperties.getProperties();
265 LOGGER.debug("\n\n\n**************************************"
266 + "\n**************************************"
268 + "properties = " + properties
269 + "\n\n**************************************");
270 } catch (IOException e) {
271 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
272 + "XACMLProperties.getProperties()");
273 throw new ServletException(e.getMessage(), e.getCause());
275 // Create an IntegrityMonitor
276 if(properties.getProperty(PERSISTENCE_JDBC_PWD) != null ){
277 properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
279 im = IntegrityMonitor.getInstance(papResourceName,properties);
280 // Create an IntegrityAudit
281 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
282 ia.startAuditThread();
283 // Create the entity manager factory
285 // we are about to call the PDPs and give them their configuration.
286 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
287 setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
288 //Create the policyDBDao
290 // Load our PAP engine, first create a factory
291 ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
292 // The factory knows how to go about creating a PAP Engine
293 setPAPEngine((PAPPolicyEngine) factory.newEngine());
294 PolicyDBDaoTransaction addNewGroup = null;
295 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
297 addNewGroup = policyDBDao.getNewTransaction();
298 OnapPDPGroup group = papEngine.getDefaultGroup();
299 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
300 "automaticallyAdded");
301 addNewGroup.commitTransaction();
302 addNewGroup = policyDBDao.getNewTransaction();
303 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
304 addNewGroup.commitTransaction();
305 } catch (Exception e) {
306 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
307 " Error creating new default group in the database");
308 if (addNewGroup != null) {
309 addNewGroup.rollbackTransaction();
313 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
314 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
316 * Auditing the local File System groups to be in sync with the Database
319 //get an AuditTransaction to lock out all other transactions
320 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
322 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
323 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
324 //get the current filesystem group and update from the database if needed
325 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
326 StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
327 if(updatedGroup!=null) {
328 papEngine.updateGroup(updatedGroup);
330 LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
332 //release the transaction lock
336 // Sanity check for URL.
337 if (XACMLPapServlet.papURL == null) {
338 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
340 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
341 // to all its known PDP nodes.
342 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
343 startInitiateThreadService(new Thread(this));
345 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
346 startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
348 } catch (FactoryException | PAPException e) {
349 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
350 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
351 } catch (Exception e) {
352 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
353 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
357 private static void startInitiateThreadService(Thread thread) {
358 initiateThread = thread;
359 initiateThread.start();
362 private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
364 mapper.writeValue(response.getOutputStream(), value);
365 } catch (Exception e) {
370 private static void startHeartBeatService(Heartbeat heartbeat) {
371 XACMLPapServlet.heartbeat = heartbeat;
372 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
373 XACMLPapServlet.heartbeatThread.start();
376 private static void setPolicyDBDao() throws ServletException {
378 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
379 } catch (Exception e) {
380 throw new ServletException("Unable to Create Policy DBDao Instance",e);
384 private static void setEMF(Properties properties) throws ServletException {
385 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
387 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
389 throw new ServletException("Unable to create Entity Manager Factory");
393 private static void setPAPURL(String papURL) {
394 XACMLPapServlet.papURL = papURL;
397 private static void setPAPEngine(PAPPolicyEngine newEngine) {
398 XACMLPapServlet.papEngine = newEngine;
401 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
403 //Now we have flattened the array into a simple comma-separated list
404 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
405 //clean up the entries
406 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
407 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
410 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
411 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
414 String msg = "integrity_audit_period_seconds ";
415 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
416 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
420 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
421 throw new PAPException(e);
425 private static void setCommonProperties() throws PAPException {
428 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
429 if(papDbDriver == null){
430 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
431 throw new PAPException("papDbDriver is null");
433 setPapDbDriver(papDbDriver);
434 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
435 if(papDbUrl == null){
436 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
437 throw new PAPException("papDbUrl is null");
439 setPapDbUrl(papDbUrl);
440 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
441 if(papDbUser == null){
442 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
443 throw new PAPException("papDbUser is null");
445 setPapDbUser(papDbUser);
446 papDbPassword = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
447 if(papDbPassword == null){
448 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
449 throw new PAPException("papDbPassword is null");
451 setPapDbPassword(papDbPassword);
452 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
453 if(papResourceName == null){
454 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
455 throw new PAPException("papResourceName is null");
457 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
458 //Micro Service Properties
459 msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
460 setMsOnapName(msOnapName);
461 msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
462 setMsPolicyName(msPolicyName);
463 // PDPId File location
464 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
465 if (XACMLPapServlet.pdpFile == null) {
466 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
467 + XACMLRestProperties.PROP_PDP_IDFILE);
468 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
473 * Thread used only during PAP startup to initiate change messages to all known PDPs.
474 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
478 // send the current configuration to all the PDPs that we know about
483 * @see Servlet#destroy()
485 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
486 * For now we assume that we do care.
489 public void destroy() {
490 // Make sure our threads are destroyed
491 if (XACMLPapServlet.heartbeatThread != null) {
492 // stop the heartbeat
494 if (XACMLPapServlet.heartbeat != null) {
495 XACMLPapServlet.heartbeat.terminate();
497 XACMLPapServlet.heartbeatThread.interrupt();
498 XACMLPapServlet.heartbeatThread.join();
499 } catch (InterruptedException e) {
500 XACMLPapServlet.heartbeatThread.interrupt();
501 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
504 if (initiateThread != null) {
506 initiateThread.interrupt();
507 initiateThread.join();
508 } catch (InterruptedException e) {
509 initiateThread.interrupt();
510 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
517 * - PDP nodes to register themselves with the PAP, and
518 * - Admin Console to make changes in the PDP Groups.
520 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
522 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
523 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
524 loggingContext.transactionStarted();
525 loggingContext.setServiceName("PAP.post");
526 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
527 UUID requestID = UUID.randomUUID();
528 loggingContext.setRequestID(requestID.toString());
529 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
531 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
533 PolicyDBDaoTransaction pdpTransaction = null;
534 loggingContext.metricStarted();
536 im.startTransaction();
537 loggingContext.metricEnded();
538 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
539 } catch (AdministrativeStateException ae){
540 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
541 + " state of " + im.getStateManager().getAdminState()
542 + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
543 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
544 loggingContext.metricEnded();
545 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
546 loggingContext.transactionEnded();
547 PolicyLogger.audit("Transaction Failed - See Error.log");
548 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
550 }catch (StandbyStatusException se) {
551 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
552 + " of " + im.getStateManager().getStandbyStatus()
553 + "\n Exception Message: " + se.getMessage();
554 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
555 loggingContext.metricEnded();
556 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
557 loggingContext.transactionEnded();
558 PolicyLogger.audit("Transaction Failed - See Error.log");
559 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
561 } catch (IntegrityMonitorException e) {
562 String message = "POST interface called for PAP " + papResourceName + " but an exception occurred"
563 + "\n Exception Message: " + e.getMessage();
564 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, e);
565 loggingContext.metricEnded();
566 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
567 loggingContext.transactionEnded();
568 PolicyLogger.audit("Transaction Failed - See Error.log");
569 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
573 loggingContext.metricStarted();
574 XACMLRest.dumpRequest(request);
575 loggingContext.metricEnded();
576 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
577 // since getParameter reads the content string, explicitly get the content before doing that.
578 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
579 request.getInputStream();
580 String groupId = request.getParameter("groupId");
581 String apiflag = request.getParameter("apiflag");
582 if(groupId != null) {
583 // Is this from the Admin Console or API?
584 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
585 // this is from the API so we need to check the client credentials before processing the request
586 if(!authorizeRequest(request)){
587 String message = "PEP not Authorized for making this Request!!";
588 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
589 loggingContext.transactionEnded();
590 PolicyLogger.audit("Transaction Failed - See Error.log");
591 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
596 loggingContext.metricStarted();
597 doACPost(request, response, groupId, loggingContext);
598 loggingContext.metricEnded();
599 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
600 loggingContext.transactionEnded();
601 PolicyLogger.audit("Transaction Ended Successfully");
605 // Request is from a PDP asking for its config.
606 loggingContext.setServiceName("PDP:PAP.register");
608 String id = this.getPDPID(request);
609 String jmxport = this.getPDPJMX(request);
610 LOGGER.info("Request(doPost) from PDP coming up: " + id);
611 // Get the PDP Object
612 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
615 LOGGER.info("Unknown PDP: " + id);
617 if(CheckPDP.validateID(id)){
618 pdpTransaction = policyDBDao.getNewTransaction();
620 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
621 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
622 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
623 pdpTransaction.rollbackTransaction();
624 String message = "Failed to create new PDP for id: " + id;
625 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
626 loggingContext.transactionEnded();
627 PolicyLogger.audit("Transaction Failed - See Error.log");
628 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
632 // get the PDP we just created
634 pdp = XACMLPapServlet.papEngine.getPDP(id);
635 }catch(PAPException e){
639 if(pdpTransaction != null){
640 pdpTransaction.rollbackTransaction();
642 String message = "Failed to create new PDP for id: " + id;
643 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
644 loggingContext.transactionEnded();
645 PolicyLogger.audit("Transaction Failed - See Error.log");
646 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
651 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
652 loggingContext.transactionEnded();
653 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
654 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
655 PolicyLogger.audit("Transaction Failed - See Error.log");
660 loggingContext.metricStarted();
661 pdpTransaction.commitTransaction();
662 loggingContext.metricEnded();
663 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
664 } catch(Exception e){
665 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
668 if (jmxport != null && jmxport != ""){
670 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
671 }catch(NumberFormatException e){
675 // Get the PDP's Group
676 OnapPDPGroup group =null;
678 group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
679 }catch(PAPException e){
683 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
684 loggingContext.transactionEnded();
685 PolicyLogger.audit("Transaction Failed - See Error.log");
686 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
690 // Determine what group the PDP node is in and get
691 // its policy/pip properties.
692 Properties policies = group.getPolicyProperties();
693 Properties pipconfig = group.getPipConfigProperties();
694 // Get the current policy/pip configuration that the PDP has
695 Properties pdpProperties = new Properties();
697 pdpProperties.load(request.getInputStream());
698 }catch(IOException e){
701 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
702 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
703 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
704 // Validate the node's properties
705 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
706 // Send back current configuration
707 if (isCurrent == false) {
708 // Tell the PDP we are sending back the current policies/pip config
709 LOGGER.info("PDP configuration NOT current.");
710 if (policies != null) {
711 // Put URL's into the properties in case the PDP needs to
713 this.populatePolicyURL(request.getRequestURL(), policies);
714 // Copy the properties to the output stream
716 policies.store(response.getOutputStream(), "");
717 }catch(IOException e){
721 if (pipconfig != null) {
722 // Copy the properties to the output stream
724 pipconfig.store(response.getOutputStream(), "");
725 }catch(IOException e){
729 // We are good - and we are sending them information
730 response.setStatus(HttpServletResponse.SC_OK);
732 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
733 }catch(PAPException e){
737 // Tell them they are good
738 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
740 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
741 }catch(PAPException e){
745 // tell the AC that something changed
746 loggingContext.metricStarted();
748 loggingContext.metricEnded();
749 PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
750 loggingContext.transactionEnded();
751 auditLogger.info("Success");
752 PolicyLogger.audit("Transaction Ended Successfully");
753 } catch (PAPException | IOException | NumberFormatException e) {
754 if(pdpTransaction != null){
755 pdpTransaction.rollbackTransaction();
757 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
758 loggingContext.transactionEnded();
759 PolicyLogger.audit("Transaction Failed - See Error.log");
760 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
764 //Catch anything that fell through
765 loggingContext.transactionEnded();
766 PolicyLogger.audit("Transaction Ended");
770 private void setResponseError(HttpServletResponse response,int responseCode, String message) {
772 if(message != null && !message.isEmpty()){
773 response.sendError(responseCode, message);
775 } catch (IOException e) {
776 LOGGER.error("Error setting Error response Header ", e);
782 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
784 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
785 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
786 loggingContext.transactionStarted();
787 loggingContext.setServiceName("PAP.get");
788 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
789 UUID requestID = UUID.randomUUID();
790 loggingContext.setRequestID(requestID.toString());
791 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
793 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
795 loggingContext.metricStarted();
796 XACMLRest.dumpRequest(request);
797 loggingContext.metricEnded();
798 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
799 String pathInfo = request.getRequestURI();
800 LOGGER.info("path info: " + pathInfo);
801 if (pathInfo != null){
802 //DO NOT do a im.startTransaction for the test request
803 if (pathInfo.equals("/pap/test")) {
805 testService(loggingContext, response);
806 } catch (IOException e) {
812 //This im.startTransaction() covers all other Get transactions
814 loggingContext.metricStarted();
815 im.startTransaction();
816 loggingContext.metricEnded();
817 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
818 } catch (AdministrativeStateException ae){
819 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
820 + " state of " + im.getStateManager().getAdminState()
821 + "\n Exception Message: " + ae.getMessage();
822 LOGGER.info(message, ae);
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);
828 }catch (StandbyStatusException se) {
829 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
830 + " of " + im.getStateManager().getStandbyStatus()
831 + "\n Exception Message: " + se.getMessage();
832 LOGGER.info(message, se);
833 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
834 loggingContext.transactionEnded();
835 PolicyLogger.audit("Transaction Failed - See Error.log");
836 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
838 } catch (IntegrityMonitorException e) {
839 String message = "GET interface called for PAP " + papResourceName + " but an exception occurred"
840 + "\n Exception Message: " + e.getMessage();
841 LOGGER.info(message, e);
842 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
843 loggingContext.transactionEnded();
844 PolicyLogger.audit("Transaction Failed - See Error.log");
845 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
848 // Request from the API to get the gitPath
849 String apiflag = request.getParameter("apiflag");
851 if(authorizeRequest(request)){
852 APIRequestHandler apiRequestHandler = new APIRequestHandler();
854 loggingContext.metricStarted();
855 apiRequestHandler.doGet(request,response, apiflag);
856 loggingContext.metricEnded();
857 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
858 }catch(IOException e){
861 loggingContext.transactionEnded();
862 PolicyLogger.audit("Transaction Ended Successfully");
866 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
867 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
868 loggingContext.transactionEnded();
869 PolicyLogger.audit("Transaction Failed - See Error.log");
870 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
875 // Is this from the Admin Console?
876 String groupId = request.getParameter("groupId");
877 if (groupId != null) {
878 // this is from the Admin Console, so handle separately
880 loggingContext.metricStarted();
881 doACGet(request, response, groupId, loggingContext);
882 loggingContext.metricEnded();
883 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
884 } catch(IOException e){
887 loggingContext.transactionEnded();
888 PolicyLogger.audit("Transaction Ended Successfully");
893 String id = this.getPDPID(request);
894 LOGGER.info("doGet from: " + id);
895 // Get the PDP Object
898 pdp = XACMLPapServlet.papEngine.getPDP(id);
899 }catch(PAPException e){
904 // Check if request came from localhost
905 if (request.getRemoteHost().equals("localhost") ||
906 request.getRemoteHost().equals(request.getLocalAddr())) {
907 // Return status information - basically all the groups
908 loggingContext.setServiceName("PAP.getGroups");
909 Set<OnapPDPGroup> groups = null;
911 groups = papEngine.getOnapPDPGroups();
912 } catch(PAPException e) {
914 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
915 loggingContext.transactionEnded();
916 PolicyLogger.audit("Transaction Failed - See Error.log");
917 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
921 // convert response object to JSON and include in the response
922 mapperWriteValue(new ObjectMapper(), response, groups);
923 response.setHeader("content-type", "application/json");
924 response.setStatus(HttpServletResponse.SC_OK);
925 loggingContext.transactionEnded();
926 PolicyLogger.audit("Transaction Ended Successfully");
930 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
931 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
932 loggingContext.transactionEnded();
933 PolicyLogger.audit("Transaction Failed - See Error.log");
934 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
938 loggingContext.setServiceName("PAP.getPolicy");
939 // Get the PDP's Group
940 OnapPDPGroup group = null;
942 group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
943 } catch (PAPException e) {
947 String message = "No group associated with pdp " + pdp.getId();
948 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
949 loggingContext.transactionEnded();
950 PolicyLogger.audit("Transaction Failed - See Error.log");
951 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
955 // Which policy do they want?
956 String policyId = request.getParameter("id");
957 if (policyId == null) {
958 String message = "Did not specify an id for the policy";
959 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
960 loggingContext.transactionEnded();
961 PolicyLogger.audit("Transaction Failed - See Error.log");
962 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
966 PDPPolicy policy = group.getPolicy(policyId);
967 if (policy == null) {
968 String message = "Unknown policy: " + policyId;
969 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
970 loggingContext.transactionEnded();
971 PolicyLogger.audit("Transaction Failed - See Error.log");
972 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
977 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
978 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
979 } catch (PAPException| IOException e){
982 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
983 // Send the policy back
984 IOUtils.copy(is, os);
985 response.setStatus(HttpServletResponse.SC_OK);
986 loggingContext.transactionEnded();
987 auditLogger.info("Success");
988 PolicyLogger.audit("Transaction Ended Successfully");
989 } catch (IOException e) {
990 String message = "Failed to open policy id " + policyId;
992 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
993 loggingContext.transactionEnded();
994 PolicyLogger.audit("Transaction Failed - See Error.log");
995 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
997 loggingContext.transactionEnded();
998 PolicyLogger.audit("Transaction Ended");
1003 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1005 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1006 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1007 loggingContext.transactionStarted();
1008 loggingContext.setServiceName("PAP.put");
1009 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1010 UUID requestID = UUID.randomUUID();
1011 loggingContext.setRequestID(requestID.toString());
1012 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
1014 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
1017 loggingContext.metricStarted();
1018 im.startTransaction();
1019 loggingContext.metricEnded();
1020 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1021 } catch (IntegrityMonitorException e) {
1022 String message = "PUT interface called for PAP " + papResourceName;
1023 if (e instanceof AdministrativeStateException) {
1024 message += " but it has an Administrative state of "
1025 + im.getStateManager().getAdminState();
1026 } else if (e instanceof StandbyStatusException) {
1027 message += " but it has a Standby Status of "
1028 + im.getStateManager().getStandbyStatus();
1030 message += " but an exception occurred";
1033 message += "\n Exception Message: " + e.getMessage();
1035 LOGGER.info(message, e);
1036 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1037 loggingContext.transactionEnded();
1038 PolicyLogger.audit("Transaction Failed - See Error.log");
1039 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1043 loggingContext.metricStarted();
1044 XACMLRest.dumpRequest(request);
1045 loggingContext.metricEnded();
1046 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1047 //need to check if request is from the API or Admin console
1048 String apiflag = request.getParameter("apiflag");
1049 //This would occur if a PolicyDBDao notification was received
1050 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1051 if(policyDBDaoRequestUrl != null){
1052 LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." );
1053 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1054 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1055 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1056 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
1057 setResponseError(response,400, "entityid or entitytype not supplied");
1058 loggingContext.transactionEnded();
1059 PolicyLogger.audit("Transaction Ended Successfully");
1060 im.endTransaction();
1063 loggingContext.metricStarted();
1064 LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1065 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
1066 loggingContext.metricEnded();
1067 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1068 response.setStatus(200);
1069 loggingContext.transactionEnded();
1070 PolicyLogger.audit("Transaction Ended Successfully");
1071 im.endTransaction();
1075 * Request for ImportService
1077 String importService = request.getParameter("importService");
1078 if (importService != null) {
1079 if(authorizeRequest(request)){
1080 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1082 loggingContext.metricStarted();
1083 apiRequestHandler.doPut(request, response, importService);
1084 loggingContext.metricEnded();
1085 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1086 }catch(IOException e){
1089 im.endTransaction();
1092 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1093 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1094 loggingContext.transactionEnded();
1095 PolicyLogger.audit("Transaction Failed - See Error.log");
1096 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1101 // See if this is Admin Console registering itself with us
1103 String acURLString = request.getParameter("adminConsoleURL");
1104 if (acURLString != null) {
1105 loggingContext.setServiceName("AC:PAP.register");
1106 // remember this Admin Console for future updates
1107 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1108 adminConsoleURLStringList.add(acURLString);
1110 if (LOGGER.isDebugEnabled()) {
1111 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1113 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1114 loggingContext.transactionEnded();
1115 auditLogger.info("Success");
1116 PolicyLogger.audit("Transaction Ended Successfully");
1117 im.endTransaction();
1121 * This is to update the PDP Group with the policy/policies being pushed
1122 * Part of a 2 step process to push policies to the PDP that can now be done
1123 * From both the Admin Console and the PolicyEngine API
1125 String groupId = request.getParameter("groupId");
1126 if (groupId != null) {
1128 if(!authorizeRequest(request)){
1129 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1130 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1131 loggingContext.transactionEnded();
1132 PolicyLogger.audit("Transaction Failed - See Error.log");
1133 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1136 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1138 updateGroupsFromAPI(request, response, groupId, loggingContext);
1139 }catch(IOException e){
1142 loggingContext.transactionEnded();
1143 PolicyLogger.audit("Transaction Ended Successfully");
1144 im.endTransaction();
1148 // this is from the Admin Console, so handle separately
1150 loggingContext.metricEnded();
1151 doACPut(request, response, groupId, loggingContext);
1152 loggingContext.metricEnded();
1153 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1154 } catch (IOException e) {
1157 loggingContext.transactionEnded();
1158 PolicyLogger.audit("Transaction Ended Successfully");
1159 im.endTransaction();
1163 // Request is for policy validation and creation
1165 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1166 // this request is from the Admin Console
1167 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1169 loggingContext.metricStarted();
1170 savePolicyHandler.doPolicyAPIPut(request, response);
1171 loggingContext.metricEnded();
1172 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1173 } catch (IOException e) {
1176 loggingContext.transactionEnded();
1177 PolicyLogger.audit("Transaction Ended Successfully");
1178 im.endTransaction();
1180 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1181 // this request is from the Policy Creation API
1182 if(authorizeRequest(request)){
1183 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1185 loggingContext.metricStarted();
1186 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1187 loggingContext.metricEnded();
1188 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1189 } catch (IOException e) {
1192 loggingContext.transactionEnded();
1193 PolicyLogger.audit("Transaction Ended Successfully");
1194 im.endTransaction();
1197 String message = "PEP not Authorized for making this Request!!";
1198 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1199 loggingContext.transactionEnded();
1200 PolicyLogger.audit("Transaction Failed - See Error.log");
1201 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1202 im.endTransaction();
1206 // We do not expect anything from anywhere else.
1207 // This method is here in case we ever need to support other operations.
1208 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1209 loggingContext.transactionEnded();
1210 PolicyLogger.audit("Transaction Failed - See Error.log");
1211 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1212 loggingContext.transactionEnded();
1213 PolicyLogger.audit("Transaction Failed - See error.log");
1214 im.endTransaction();
1218 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1220 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1221 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1222 loggingContext.transactionStarted();
1223 loggingContext.setServiceName("PAP.delete");
1224 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1225 UUID requestID = UUID.randomUUID();
1226 loggingContext.setRequestID(requestID.toString());
1227 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1229 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1232 loggingContext.metricStarted();
1233 im.startTransaction();
1234 loggingContext.metricEnded();
1235 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1236 } catch (AdministrativeStateException ae){
1237 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1238 + " state of " + im.getStateManager().getAdminState()
1239 + "\n Exception Message: " + ae.getMessage();
1240 LOGGER.info(message, ae);
1241 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1242 loggingContext.transactionEnded();
1243 PolicyLogger.audit("Transaction Failed - See Error.log");
1244 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1246 }catch (StandbyStatusException se) {
1247 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1248 + " of " + im.getStateManager().getStandbyStatus()
1249 + "\n Exception Message: " + se.getMessage();
1250 LOGGER.info(message, se);
1251 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1252 loggingContext.transactionEnded();
1253 PolicyLogger.audit("Transaction Failed - See Error.log");
1254 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1256 } catch (IntegrityMonitorException e) {
1257 String message = "PUT interface called for PAP " + papResourceName + " but an exception occurred"
1258 + "\n Exception Message: " + e.getMessage();
1259 LOGGER.info(message, e);
1260 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1261 loggingContext.transactionEnded();
1262 PolicyLogger.audit("Transaction Failed - See Error.log");
1263 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1266 loggingContext.metricStarted();
1267 XACMLRest.dumpRequest(request);
1268 loggingContext.metricEnded();
1269 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1270 String groupId = request.getParameter("groupId");
1271 String apiflag = request.getParameter("apiflag");
1272 if (groupId != null) {
1273 // Is this from the Admin Console or API?
1275 if(!authorizeRequest(request)){
1276 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1277 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1278 loggingContext.transactionEnded();
1279 PolicyLogger.audit("Transaction Failed - See Error.log");
1280 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1283 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1285 loggingContext.metricStarted();
1286 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1287 loggingContext.metricEnded();
1288 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1289 } catch (Exception e) {
1290 LOGGER.error("Exception Occured"+e);
1292 if(apiRequestHandler.getNewGroup()!=null){
1293 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1297 // this is from the Admin Console, so handle separately
1299 loggingContext.metricStarted();
1300 doACDelete(request, response, groupId, loggingContext);
1301 loggingContext.metricEnded();
1302 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1303 } catch (IOException e) {
1306 loggingContext.transactionEnded();
1307 PolicyLogger.audit("Transaction Ended Successfully");
1308 im.endTransaction();
1311 //Catch anything that fell through
1312 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1313 loggingContext.transactionEnded();
1314 PolicyLogger.audit("Transaction Failed - See Error.log");
1315 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1316 im.endTransaction();
1319 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1320 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1321 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1322 if (localRootPolicies == null || localReferencedPolicies == null) {
1323 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1326 // Compare the policies and pipconfig properties to the pdpProperties
1328 // the policy properties includes only xacml.rootPolicies and
1329 // xacml.referencedPolicies without any .url entries
1330 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1331 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1332 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1333 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1334 pdpPipConfig.equals(pipconfig)) {
1335 // The PDP is current
1338 } catch (Exception e) {
1339 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1340 // or if there are policies that do not have a corresponding ".url" property.
1341 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1342 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1347 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1348 String lists[] = new String[2];
1349 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1350 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1351 for (String list : lists) {
1352 if (list != null && list.isEmpty() == false) {
1353 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1354 String url = urlPath + "?id=" + id;
1355 LOGGER.info("Policy URL for " + id + ": " + url);
1356 policies.setProperty(id + ".url", url);
1362 protected String getPDPID(HttpServletRequest request) {
1363 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1364 if (pdpURL == null || pdpURL.isEmpty()) {
1365 // Should send back its port for identification
1366 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1372 protected String getPDPJMX(HttpServletRequest request) {
1373 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1374 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1375 // Should send back its port for identification
1376 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1383 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1388 * @param loggingContext
1389 * @throws ServletException
1390 * @throws IOException
1392 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1393 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1394 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1396 // for PUT operations the group may or may not need to exist before the operation can be done
1397 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1399 // get the request input stream content into a String
1401 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1402 scanner.useDelimiter("\\A");
1403 json = scanner.hasNext() ? scanner.next() : "";
1406 PolicyLogger.info("pushPolicy request from API: " + json);
1408 // convert Object sent as JSON into local object
1409 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1411 //Get the current policies from the Group and Add the new one
1412 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1413 currentPoliciesInGroup = group.getPolicies();
1414 //If the selected policy is in the group we must remove the old version of it
1415 LOGGER.info("Removing old version of the policy");
1416 for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
1417 if (existingPolicy.getName().equals(policy.getName()) && !existingPolicy.getId().equals(policy.getId())){
1418 group.removePolicy(existingPolicy);
1419 LOGGER.info("Removing policy: " + existingPolicy);
1424 // Assume that this is an update of an existing PDP Group
1425 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1427 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1428 } catch(Exception e){
1429 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1430 +"group="+group.getId());
1431 throw new PAPException(e.getMessage());
1434 LOGGER.info("Calling updatGroup() with new group");
1435 papEngine.updateGroup(group);
1436 String policyId = "empty";
1437 if(policy !=null && policy.getId() != null){
1438 policyId = policy.getId();
1440 if(!policyId.matches(REGEX) ){
1441 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1442 response.addHeader("error",ADD_GROUP_ERROR);
1443 response.addHeader("message", "Policy Id is not valid");
1446 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1447 response.addHeader("operation", "push");
1448 response.addHeader("policyId", policyId);
1449 response.addHeader("groupId", groupId);
1451 LOGGER.info("Group '" + group.getId() + "' updated");
1453 loggingContext.metricStarted();
1454 acPutTransaction.commitTransaction();
1455 loggingContext.metricEnded();
1456 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1457 loggingContext.metricStarted();
1459 loggingContext.metricEnded();
1460 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1462 // Group changed, which might include changing the policies
1463 groupChanged(group, loggingContext);
1464 loggingContext.transactionEnded();
1465 LOGGER.info("Success");
1467 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1468 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1469 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1470 LOGGER.debug("Precheck Successful.");
1474 PolicyLogger.audit("Transaction Ended Successfully");
1476 } catch (PAPException e) {
1477 acPutTransaction.rollbackTransaction();
1478 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1479 loggingContext.transactionEnded();
1480 PolicyLogger.audit("Transaction Failed - See Error.log");
1481 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1482 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1483 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1484 response.addHeader("error",ADD_GROUP_ERROR);
1485 response.addHeader("message", message);
1491 * Requests from the Admin Console for operations not on single specific objects
1496 * @param loggingContext
1497 * @throws ServletException
1498 * @throws IOException
1500 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1501 PolicyDBDaoTransaction doACPostTransaction = null;
1503 String groupName = request.getParameter("groupName");
1504 String groupDescription = request.getParameter("groupDescription");
1505 String apiflag = request.getParameter("apiflag");
1506 if (groupName != null && groupDescription != null) {
1507 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1508 loggingContext.setServiceName("AC:PAP.createGroup");
1509 String unescapedName = null;
1510 String unescapedDescription = null;
1512 unescapedName = URLDecoder.decode(groupName, "UTF-8");
1513 unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1514 } catch (UnsupportedEncodingException e) {
1517 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1519 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1520 papEngine.newGroup(unescapedName, unescapedDescription);
1521 loggingContext.metricStarted();
1522 newGroupTransaction.commitTransaction();
1523 loggingContext.metricEnded();
1524 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1525 } catch (Exception e) {
1526 newGroupTransaction.rollbackTransaction();
1527 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1528 loggingContext.transactionEnded();
1529 PolicyLogger.audit("Transaction Failed - See Error.log");
1530 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1533 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1534 if (LOGGER.isDebugEnabled()) {
1535 LOGGER.debug("New Group '" + groupId + "' created");
1537 // tell the Admin Consoles there is a change
1538 loggingContext.metricStarted();
1540 loggingContext.metricEnded();
1541 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1542 // new group by definition has no PDPs, so no need to notify them of changes
1543 loggingContext.transactionEnded();
1544 PolicyLogger.audit("Transaction Failed - See Error.log");
1545 auditLogger.info("Success");
1546 PolicyLogger.audit("Transaction Ended Successfully");
1549 // for all remaining POST operations the group must exist before the operation can be done
1550 OnapPDPGroup group = null;
1552 group = papEngine.getGroup(groupId);
1553 } catch (PAPException e){
1556 if (group == null) {
1557 String message = "Unknown groupId '" + groupId + "'";
1558 //for fixing Header Manipulation of Fortify issue
1559 if(!message.matches(REGEX)){
1560 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1561 response.addHeader("error",ADD_GROUP_ERROR);
1562 response.addHeader("message", "GroupId Id is not valid");
1565 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1566 loggingContext.transactionEnded();
1567 PolicyLogger.audit("Transaction Failed - See Error.log");
1569 response.addHeader("error", "unknownGroupId");
1570 response.addHeader("operation", "push");
1571 response.addHeader("message", message);
1572 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1574 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1579 // If the request contains a policyId then we know we are pushing the policy to PDP
1580 if (request.getParameter("policyId") != null) {
1583 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1584 LOGGER.info("PushPolicy Request From The API");
1586 loggingContext.setServiceName("AC:PAP.postPolicy");
1587 LOGGER.info("PushPolicy Request From The AC");
1590 String policyId = request.getParameter("policyId");
1591 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1592 StdPDPGroup updatedGroup = null;
1594 //Copying the policy to the file system and updating groups in database
1595 LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
1596 updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1597 loggingContext.metricStarted();
1598 addPolicyToGroupTransaction.commitTransaction();
1599 loggingContext.metricEnded();
1600 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1601 LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
1603 } catch (Exception e) {
1604 addPolicyToGroupTransaction.rollbackTransaction();
1605 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1606 //for fixing Header Manipulation of Fortify issue
1607 if(!message.matches(REGEX)){
1608 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1609 response.addHeader("error",ADD_GROUP_ERROR);
1610 response.addHeader("message", "Policy Id is not valid");
1613 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1614 loggingContext.transactionEnded();
1615 PolicyLogger.audit("Transaction Failed - See Error.log");
1617 response.addHeader("error", "policyCopyError");
1618 response.addHeader("message", message);
1619 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1621 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1626 if(apiflag != null){
1628 * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
1629 * The GUI does this from the POLICY-SDK-APP code.
1632 // Get new transaction to perform updateGroup()
1633 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1635 // get the request content into a String and read the inputStream into a buffer
1636 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1637 scanner.useDelimiter("\\A");
1638 String json = scanner.hasNext() ? scanner.next() : "";
1641 // convert Object sent as JSON into local object
1642 ObjectMapper mapper = new ObjectMapper();
1643 Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
1644 StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
1646 LOGGER.info("Request JSON Payload: " + json);
1648 // Assume that this is an update of an existing PDP Group
1649 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1651 acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
1652 } catch(Exception e){
1653 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
1655 throw new PAPException(e.getMessage());
1658 LOGGER.info("Calling updatGroup() with new group");
1659 papEngine.updateGroup(updatedGroup);
1661 LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
1663 // Commit transaction to send notification to other PAPs
1664 loggingContext.metricStarted();
1665 acPutTransaction.commitTransaction();
1666 loggingContext.metricEnded();
1667 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1668 loggingContext.metricStarted();
1671 loggingContext.metricEnded();
1672 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
1674 // Group changed to send notification to PDPs, which might include changing the policies
1675 groupChanged(updatedGroup,loggingContext);
1676 loggingContext.transactionEnded();
1677 LOGGER.info("Success");
1679 if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1680 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1681 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1682 LOGGER.debug("Precheck Successful.");
1686 //delete temporary policy file from the bin directory
1687 Files.deleteIfExists(Paths.get(policy.getId()));
1689 } catch (Exception e) {
1690 acPutTransaction.rollbackTransaction();
1691 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1692 loggingContext.transactionEnded();
1693 PolicyLogger.audit("Transaction Failed - See Error.log");
1694 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API.";
1695 LOGGER.error(message);
1696 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1697 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1698 response.addHeader("error",ADD_GROUP_ERROR);
1699 response.addHeader("message", message);
1704 // policy file copied ok and the Group was updated on the PDP
1705 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1706 response.addHeader("operation", "push");
1707 response.addHeader("policyId", policyId);
1708 response.addHeader("groupId", groupId);
1710 LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1711 loggingContext.transactionEnded();
1712 auditLogger.info("Success");
1713 LOGGER.info("Transaction Ended Successfully");
1716 } else if (request.getParameter("default") != null) {
1717 // Args: group=<groupId> default=true <= make default
1718 // change the current default group to be the one identified in the request.
1719 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1720 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1721 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1722 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1724 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1725 papEngine.setDefaultGroup(group);
1726 loggingContext.metricStarted();
1727 setDefaultGroupTransaction.commitTransaction();
1728 loggingContext.metricEnded();
1729 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1730 } catch (Exception e) {
1731 setDefaultGroupTransaction.rollbackTransaction();
1732 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1733 loggingContext.transactionEnded();
1734 PolicyLogger.audit("Transaction Failed - See Error.log");
1735 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1738 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1739 if (LOGGER.isDebugEnabled()) {
1740 LOGGER.debug("Group '" + groupId + "' set to be default");
1742 // Notify the Admin Consoles that something changed
1743 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1744 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1745 loggingContext.metricStarted();
1747 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1748 loggingContext.metricEnded();
1749 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1750 loggingContext.transactionEnded();
1751 auditLogger.info("Success");
1752 LOGGER.info("Transaction Ended Successfully");
1754 } else if (request.getParameter("pdpId") != null) {
1755 doACPostTransaction = policyDBDao.getNewTransaction();
1756 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1757 loggingContext.setServiceName("AC:PAP.movePDP");
1758 String pdpId = request.getParameter("pdpId");
1759 OnapPDP pdp = papEngine.getPDP(pdpId);
1760 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1762 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1763 }catch(Exception e){
1764 doACPostTransaction.rollbackTransaction();
1765 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1766 " Error while moving pdp in the database: "
1767 +"pdp="+pdp.getId()+",to group="+group.getId());
1768 throw new PAPException(e.getMessage());
1770 papEngine.movePDP((OnapPDP) pdp, group);
1771 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1772 if (LOGGER.isDebugEnabled()) {
1773 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1775 // update the status of both the original group and the new one
1776 ((StdPDPGroup)originalGroup).resetStatus();
1777 ((StdPDPGroup)group).resetStatus();
1778 // Notify the Admin Consoles that something changed
1779 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1780 loggingContext.metricStarted();
1782 loggingContext.metricEnded();
1783 PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
1784 // Need to notify the PDP that it's config may have changed
1785 pdpChanged(pdp, loggingContext);
1786 loggingContext.metricStarted();
1787 doACPostTransaction.commitTransaction();
1788 loggingContext.metricEnded();
1789 PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
1790 loggingContext.transactionEnded();
1791 auditLogger.info("Success");
1792 PolicyLogger.audit("Transaction Ended Successfully");
1795 } catch (PAPException e) {
1796 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1797 loggingContext.transactionEnded();
1798 PolicyLogger.audit("Transaction Failed - See Error.log");
1799 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1805 * Requests from the Admin Console to GET info about the Groups and PDPs
1810 * @param loggingContext
1811 * @throws ServletException
1812 * @throws IOException
1814 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1816 String parameterDefault = request.getParameter("default");
1817 String pdpId = request.getParameter("pdpId");
1818 String pdpGroup = request.getParameter("getPDPGroup");
1819 if ("".equals(groupId)) {
1820 // request IS from AC but does not identify a group by name
1821 if (parameterDefault != null) {
1822 // Request is for the Default group (whatever its id)
1823 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1824 OnapPDPGroup group = papEngine.getDefaultGroup();
1825 // convert response object to JSON and include in the response
1826 mapperWriteValue(new ObjectMapper(), response, group);
1827 if (LOGGER.isDebugEnabled()) {
1828 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1830 response.setStatus(HttpServletResponse.SC_OK);
1831 response.setHeader("content-type", "application/json");
1833 response.getOutputStream().close();
1834 } catch (IOException e){
1837 loggingContext.transactionEnded();
1838 auditLogger.info("Success");
1839 PolicyLogger.audit("Transaction Ended Successfully");
1841 } else if (pdpId != null) {
1842 // Request is related to a PDP
1843 if (pdpGroup == null) {
1844 // Request is for the (unspecified) group containing a given PDP
1845 loggingContext.setServiceName("AC:PAP.getPDP");
1848 pdp = papEngine.getPDP(pdpId);
1849 }catch(PAPException e){
1852 // convert response object to JSON and include in the response
1853 mapperWriteValue(new ObjectMapper(), response, pdp);
1854 if (LOGGER.isDebugEnabled()) {
1855 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1857 response.setStatus(HttpServletResponse.SC_OK);
1858 response.setHeader("content-type", "application/json");
1860 response.getOutputStream().close();
1861 } catch (IOException e){
1864 loggingContext.transactionEnded();
1865 auditLogger.info("Success");
1866 PolicyLogger.audit("Transaction Ended Successfully");
1869 // Request is for the group containing a given PDP
1870 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1871 OnapPDPGroup group =null;
1873 OnapPDP pdp = papEngine.getPDP(pdpId);
1874 group = papEngine.getPDPGroup((OnapPDP) pdp);
1875 }catch(PAPException e){
1878 // convert response object to JSON and include in the response
1879 mapperWriteValue(new ObjectMapper(), response, group);
1880 if (LOGGER.isDebugEnabled()) {
1881 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1883 response.setStatus(HttpServletResponse.SC_OK);
1884 response.setHeader("content-type", "application/json");
1886 response.getOutputStream().close();
1887 } catch (IOException e){
1890 loggingContext.transactionEnded();
1891 auditLogger.info("Success");
1892 PolicyLogger.audit("Transaction Ended Successfully");
1896 // request is for top-level properties about all groups
1897 loggingContext.setServiceName("AC:PAP.getAllGroups");
1898 Set<OnapPDPGroup> groups = null;
1900 groups = papEngine.getOnapPDPGroups();
1901 } catch(PAPException e) {
1902 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1903 loggingContext.transactionEnded();
1904 PolicyLogger.audit("Transaction Failed - See Error.log");
1905 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1908 // convert response object to JSON and include in the response
1909 mapperWriteValue(new ObjectMapper(), response, groups);
1910 if (LOGGER.isDebugEnabled()) {
1911 LOGGER.debug("GET All groups req");
1913 response.setStatus(HttpServletResponse.SC_OK);
1914 response.setHeader("content-type", "application/json");
1916 response.getOutputStream().close();
1917 } catch (IOException e){
1920 loggingContext.transactionEnded();
1921 auditLogger.info("Success");
1922 PolicyLogger.audit("Transaction Ended Successfully");
1926 // for all other GET operations the group must exist before the operation can be done
1927 OnapPDPGroup group = null;
1929 group = papEngine.getGroup(groupId);
1930 } catch(PAPException e){
1933 if (group == null) {
1934 String message = "Unknown groupId '" + groupId + "'";
1935 //for fixing Header Manipulation of Fortify issue
1936 if(!message.matches(REGEX)){
1937 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1938 response.addHeader("error",ADD_GROUP_ERROR);
1939 response.addHeader("message", "Group Id is not valid");
1942 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1943 loggingContext.transactionEnded();
1944 PolicyLogger.audit("Transaction Failed - See Error.log");
1945 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1948 // Figure out which request this is based on the parameters
1949 String policyId = request.getParameter("policyId");
1950 if (policyId != null) {
1951 // retrieve a policy
1952 loggingContext.setServiceName("AC:PAP.getPolicy");
1953 // convert response object to JSON and include in the response
1954 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1955 loggingContext.transactionEnded();
1956 PolicyLogger.audit("Transaction Failed - See Error.log");
1957 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1959 // No other parameters, so return the identified Group
1960 loggingContext.setServiceName("AC:PAP.getGroup");
1961 // convert response object to JSON and include in the response
1962 mapperWriteValue(new ObjectMapper(), response, group);
1963 if (LOGGER.isDebugEnabled()) {
1964 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1966 response.setStatus(HttpServletResponse.SC_OK);
1967 response.setHeader("content-type", "application/json");
1969 response.getOutputStream().close();
1970 } catch (IOException e){
1973 loggingContext.transactionEnded();
1974 auditLogger.info("Success");
1975 PolicyLogger.audit("Transaction Ended Successfully");
1978 // Currently there are no other GET calls from the AC.
1979 // 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.
1980 // Other GETs that could be called:
1981 // Specific Group (groupId=<groupId>)
1982 // A Policy (groupId=<groupId> policyId=<policyId>)
1983 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1984 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1985 loggingContext.transactionEnded();
1986 PolicyLogger.audit("Transaction Failed - See Error.log");
1987 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1988 } catch (PAPException e) {
1989 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1990 loggingContext.transactionEnded();
1991 PolicyLogger.audit("Transaction Failed - See Error.log");
1992 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1998 * Requests from the Admin Console to create new items or update existing ones
2003 * @param loggingContext
2004 * @throws ServletException
2005 * @throws IOException
2007 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2008 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
2010 // for PUT operations the group may or may not need to exist before the operation can be done
2011 OnapPDPGroup group = papEngine.getGroup(groupId);
2012 // determine the operation needed based on the parameters in the request
2013 // for remaining operations the group must exist before the operation can be done
2014 if (group == null) {
2015 String message = "Unknown groupId '" + groupId + "'";
2016 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2017 loggingContext.transactionEnded();
2018 PolicyLogger.audit("Transaction Failed - See Error.log");
2019 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
2022 if (request.getParameter("policy") != null) {
2023 // 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)
2024 loggingContext.setServiceName("AC:PAP.putPolicy");
2025 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
2026 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2027 loggingContext.transactionEnded();
2028 PolicyLogger.audit("Transaction Failed - See Error.log");
2029 auditLogger.info("Success");
2030 PolicyLogger.audit("Transaction Ended Successfully");
2032 } else if (request.getParameter("pdpId") != null) {
2033 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
2034 String pdpId = request.getParameter("pdpId");
2035 if (papEngine.getPDP(pdpId) == null) {
2036 loggingContext.setServiceName("AC:PAP.createPDP");
2038 loggingContext.setServiceName("AC:PAP.updatePDP");
2040 // get the request content into a String
2042 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2044 Scanner scanner = new Scanner(request.getInputStream());
2045 scanner.useDelimiter("\\A");
2046 json = scanner.hasNext() ? scanner.next() : "";
2048 }catch(IOException e){
2051 LOGGER.info("JSON request from AC: " + json);
2052 // convert Object sent as JSON into local object
2053 ObjectMapper mapper = new ObjectMapper();
2054 Object objectFromJSON = null;
2056 objectFromJSON = mapper.readValue(json, StdPDP.class);
2057 } catch(Exception e) {
2060 if (pdpId == null ||
2061 objectFromJSON == null ||
2062 ! (objectFromJSON instanceof StdPDP) ||
2063 ((StdPDP)objectFromJSON).getId() == null ||
2064 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
2065 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
2066 loggingContext.transactionEnded();
2067 PolicyLogger.audit("Transaction Failed - See Error.log");
2068 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input pdpid for object:"+objectFromJSON);
2070 StdPDP pdp = (StdPDP) objectFromJSON;
2072 OnapPDP oPDP = null;
2074 oPDP = papEngine.getPDP(pdpId);
2075 }catch (PAPException e){
2079 // this is a request to create a new PDP object
2081 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
2082 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
2083 } catch(Exception e){
2084 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2085 +"pdp="+ (pdp.getId()) +",to group="+group.getId());
2086 throw new PAPException(e.getMessage());
2089 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
2090 }catch(PAPException e){
2095 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
2096 } catch(Exception e){
2097 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
2098 +"pdp="+ pdp.getId());
2099 throw new PAPException(e.getMessage());
2101 // this is a request to update the pdp
2103 papEngine.updatePDP(pdp);
2104 }catch(PAPException e){
2108 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2109 if (LOGGER.isDebugEnabled()) {
2110 LOGGER.debug("PDP '" + pdpId + "' created/updated");
2112 // adjust the group's state including the new PDP
2113 ((StdPDPGroup)group).resetStatus();
2114 // tell the Admin Consoles there is a change
2115 loggingContext.metricStarted();
2117 loggingContext.metricEnded();
2118 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2119 // this might affect the PDP, so notify it of the change
2120 pdpChanged(pdp, loggingContext);
2121 loggingContext.metricStarted();
2122 acPutTransaction.commitTransaction();
2123 loggingContext.metricEnded();
2124 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2125 loggingContext.transactionEnded();
2126 auditLogger.info("Success");
2127 PolicyLogger.audit("Transaction Ended Successfully");
2131 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
2132 +"pdp=null" + ",to group="+group.getId());
2133 throw new PAPException("PDP is null");
2134 } catch(Exception e){
2135 throw new PAPException("PDP is null" + e.getMessage() +e);
2138 } else if (request.getParameter("pipId") != null) {
2139 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
2140 loggingContext.setServiceName("AC:PAP.putPIP");
2141 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2142 loggingContext.transactionEnded();
2143 PolicyLogger.audit("Transaction Failed - See Error.log");
2144 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2147 // Assume that this is an update of an existing PDP Group
2148 // ARGS: group=<groupId> <= Update an Existing Group
2149 loggingContext.setServiceName("AC:PAP.updateGroup");
2150 // get the request content into a String
2152 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
2154 Scanner scanner = new Scanner(request.getInputStream());
2155 scanner.useDelimiter("\\A");
2156 json = scanner.hasNext() ? scanner.next() : "";
2158 }catch(IOException e){
2161 LOGGER.info("JSON request from AC: " + json);
2162 // convert Object sent as JSON into local object
2163 ObjectMapper mapper = new ObjectMapper();
2164 Object objectFromJSON = null;
2166 objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
2167 } catch(Exception e) {
2170 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
2171 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
2172 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
2173 loggingContext.transactionEnded();
2174 PolicyLogger.audit("Transaction Failed - See Error.log");
2175 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input id for object:"+objectFromJSON);
2177 // The Path on the PAP side is not carried on the RESTful interface with the AC
2178 // (because it is local to the PAP)
2179 // so we need to fill that in before submitting the group for update
2180 if(objectFromJSON != null){
2181 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
2184 if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){
2185 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete");
2187 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
2189 } catch(Exception e){
2190 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
2191 +"group="+group.getId());
2193 throw new PAPException(e.getMessage());
2196 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
2197 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
2198 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
2199 LOGGER.debug("Precheck Successful.");
2202 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2203 }catch(PAPException e){
2206 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2207 if (LOGGER.isDebugEnabled()) {
2208 LOGGER.debug("Group '" + group.getId() + "' updated");
2210 loggingContext.metricStarted();
2211 acPutTransaction.commitTransaction();
2212 loggingContext.metricEnded();
2213 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2214 // tell the Admin Consoles there is a change
2215 loggingContext.metricStarted();
2217 loggingContext.metricEnded();
2218 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2219 // Group changed, which might include changing the policies
2220 groupChanged(group, loggingContext);
2221 loggingContext.transactionEnded();
2222 auditLogger.info("Success");
2223 PolicyLogger.audit("Transaction Ended Successfully");
2226 } catch (PAPException e) {
2228 acPutTransaction.rollbackTransaction();
2229 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2230 loggingContext.transactionEnded();
2231 PolicyLogger.audit("Transaction Failed - See Error.log");
2232 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2238 * Requests from the Admin Console to delete/remove items
2243 * @param loggingContext
2244 * @throws ServletException
2245 * @throws IOException
2247 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2248 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2250 // for all DELETE operations the group must exist before the operation can be done
2251 loggingContext.setServiceName("AC:PAP.delete");
2252 OnapPDPGroup group = papEngine.getGroup(groupId);
2253 if (group == null) {
2254 String message = "Unknown groupId '" + groupId + "'";
2255 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2256 loggingContext.transactionEnded();
2257 PolicyLogger.audit("Transaction Failed - See Error.log");
2258 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2261 // determine the operation needed based on the parameters in the request
2262 if (request.getParameter("policy") != null) {
2263 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
2264 loggingContext.setServiceName("AC:PAP.deletePolicy");
2265 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2266 loggingContext.transactionEnded();
2267 PolicyLogger.audit("Transaction Failed - See Error.log");
2268 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2270 } else if (request.getParameter("pdpId") != null) {
2271 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
2272 String pdpId = request.getParameter("pdpId");
2273 OnapPDP pdp = papEngine.getPDP(pdpId);
2275 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2276 } catch(Exception e){
2277 throw new PAPException(e);
2280 papEngine.removePDP((OnapPDP) pdp);
2281 }catch(PAPException e){
2284 // adjust the status of the group, which may have changed when we removed this PDP
2285 ((StdPDPGroup)group).resetStatus();
2286 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2287 loggingContext.metricStarted();
2289 loggingContext.metricEnded();
2290 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2291 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2292 pdpChanged(pdp, loggingContext);
2293 loggingContext.metricStarted();
2294 removePdpOrGroupTransaction.commitTransaction();
2295 loggingContext.metricEnded();
2296 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2297 loggingContext.transactionEnded();
2298 auditLogger.info("Success");
2299 PolicyLogger.audit("Transaction Ended Successfully");
2301 } else if (request.getParameter("pipId") != null) {
2302 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2303 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2304 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2305 loggingContext.transactionEnded();
2306 PolicyLogger.audit("Transaction Failed - See Error.log");
2307 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2310 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
2311 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2312 OnapPDPGroup moveToGroup = null;
2313 if (moveToGroupId != null) {
2315 moveToGroup = papEngine.getGroup(moveToGroupId);
2316 }catch(PAPException e){
2320 // get list of PDPs in the group being deleted so we can notify them that they got changed
2321 Set<OnapPDP> movedPDPs = new HashSet<>();
2322 movedPDPs.addAll(group.getOnapPdps());
2323 // do the move/remove
2325 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2326 } catch(Exception e){
2327 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2328 throw new PAPException(e.getMessage());
2331 papEngine.removeGroup(group, moveToGroup);
2332 }catch(PAPException e){
2335 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2336 loggingContext.metricStarted();
2338 loggingContext.metricEnded();
2339 PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
2340 // notify any PDPs in the removed set that their config may have changed
2341 for (OnapPDP pdp : movedPDPs) {
2342 pdpChanged(pdp, loggingContext);
2344 loggingContext.metricStarted();
2345 removePdpOrGroupTransaction.commitTransaction();
2346 loggingContext.metricEnded();
2347 PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
2348 loggingContext.transactionEnded();
2349 auditLogger.info("Success");
2350 PolicyLogger.audit("Transaction Ended Successfully");
2353 } catch (PAPException e) {
2354 removePdpOrGroupTransaction.rollbackTransaction();
2355 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2356 loggingContext.transactionEnded();
2357 PolicyLogger.audit("Transaction Failed - See Error.log");
2358 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2364 * Heartbeat thread - periodically check on PDPs' status
2366 * Heartbeat with all known PDPs.
2368 * Implementation note:
2370 * The PDPs are contacted Sequentially, not in Parallel.
2372 * If we did this in parallel using multiple threads we would simultaneously use
2376 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2377 * when user changes occur.
2378 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2380 * The Sequential operation does a heartbeat request to each PDP one at a time.
2381 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2382 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2383 * it could take a long time to cycle through all of the PDPs.
2384 * That means that this may not notice a PDP being down in a predictable time.
2386 private class Heartbeat implements Runnable {
2387 private PAPPolicyEngine papEngine;
2388 private Set<OnapPDP> pdps = new HashSet<>();
2389 private int heartbeatInterval;
2390 private int heartbeatTimeout;
2392 public volatile boolean isRunning = false;
2394 public synchronized boolean isRunning() {
2395 return this.isRunning;
2398 public synchronized void terminate() {
2399 this.isRunning = false;
2402 public Heartbeat(PAPPolicyEngine papEngine2) {
2403 papEngine = papEngine2;
2404 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2405 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2410 // Set ourselves as running
2411 synchronized(this) {
2412 this.isRunning = true;
2414 HashMap<String, URL> idToURLMap = new HashMap<>();
2416 while (this.isRunning()) {
2417 // Wait the given time
2418 Thread.sleep(heartbeatInterval);
2419 // get the list of PDPs (may have changed since last time)
2421 synchronized(papEngine) {
2423 for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2424 for (OnapPDP p : g.getOnapPdps()) {
2428 } catch (PAPException e) {
2429 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2432 // Check for shutdown
2433 if (this.isRunning() == false) {
2434 LOGGER.info("isRunning is false, getting out of loop.");
2437 // try to get the summary status from each PDP
2438 boolean changeSeen = false;
2439 for (OnapPDP pdp : pdps) {
2440 // Check for shutdown
2441 if (this.isRunning() == false) {
2442 LOGGER.info("isRunning is false, getting out of loop.");
2445 // the id of the PDP is its url (though we add a query parameter)
2446 URL pdpURL = idToURLMap.get(pdp.getId());
2447 if (pdpURL == null) {
2448 // haven't seen this PDP before
2449 String fullURLString = null;
2452 if(CheckPDP.validateID(pdp.getId())){
2453 fullURLString = pdp.getId() + "?type=hb";
2454 pdpURL = new URL(fullURLString);
2455 idToURLMap.put(pdp.getId(), pdpURL);
2457 } catch (MalformedURLException e) {
2458 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2462 // Do a GET with type HeartBeat
2463 String newStatus = "";
2464 HttpURLConnection connection = null;
2466 // Open up the connection
2468 connection = (HttpURLConnection)pdpURL.openConnection();
2469 // Setup our method and headers
2470 connection.setRequestMethod("GET");
2471 connection.setConnectTimeout(heartbeatTimeout);
2473 String encoding = CheckPDP.getEncoding(pdp.getId());
2474 if(encoding !=null){
2475 connection.setRequestProperty("Authorization", "Basic " + encoding);
2478 connection.connect();
2479 if (connection.getResponseCode() == 204) {
2480 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2481 if (LOGGER.isDebugEnabled()) {
2482 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2485 // anything else is an unexpected result
2486 newStatus = PDPStatus.Status.UNKNOWN.toString();
2487 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2490 } catch (UnknownHostException e) {
2491 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2492 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2493 } catch (SocketTimeoutException e) {
2494 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2495 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2496 } catch (ConnectException e) {
2497 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2498 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2499 } catch (Exception e) {
2500 newStatus = PDPStatus.Status.UNKNOWN.toString();
2501 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2503 // cleanup the connection
2504 if(connection != null)
2505 connection.disconnect();
2507 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2508 if (LOGGER.isDebugEnabled()) {
2509 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2512 setPDPSummaryStatus(pdp, newStatus);
2513 } catch (PAPException e) {
2514 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2519 // Check for shutdown
2520 if (this.isRunning() == false) {
2521 LOGGER.info("isRunning is false, getting out of loop.");
2524 // if any of the PDPs changed state, tell the ACs to update
2529 } catch (InterruptedException e) {
2530 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2532 Thread.currentThread().interrupt();
2538 * HELPER to change Group status when PDP status is changed
2539 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2541 private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2542 setPDPSummaryStatus(pdp, newStatus.toString());
2545 private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2546 synchronized(papEngine) {
2547 StdPDPStatus status = new StdPDPStatus();
2548 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2549 ((StdPDP)pdp).setStatus(status);
2550 // now adjust the group
2551 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2552 // if the PDP was just deleted it may transiently exist but not be in a group
2553 if (group != null) {
2554 group.resetStatus();
2560 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2561 * in the PDP group directories
2564 public void changed() {
2565 // all PDPs in all groups need to be updated/sync'd
2566 Set<OnapPDPGroup> groups;
2568 groups = papEngine.getOnapPDPGroups();
2569 } catch (PAPException e) {
2570 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2571 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2573 for (OnapPDPGroup group : groups) {
2574 groupChanged(group);
2578 public void changed(ONAPLoggingContext loggingContext) {
2579 // all PDPs in all groups need to be updated/sync'd
2580 Set<OnapPDPGroup> groups;
2582 groups = papEngine.getOnapPDPGroups();
2583 } catch (PAPException e) {
2584 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2585 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2587 for (OnapPDPGroup group : groups) {
2588 groupChanged(group, loggingContext);
2593 public void groupChanged(OnapPDPGroup group) {
2594 // all PDPs within one group need to be updated/sync'd
2595 for (OnapPDP pdp : group.getOnapPdps()) {
2600 public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
2601 // all PDPs within one group need to be updated/sync'd
2602 for (OnapPDP pdp : group.getOnapPdps()) {
2603 pdpChanged(pdp, loggingContext);
2608 public void pdpChanged(OnapPDP pdp) {
2609 // kick off a thread to do an event notification for each PDP.
2610 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2611 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2612 Thread t = new Thread(new UpdatePDPThread(pdp));
2613 if(CheckPDP.validateID(pdp.getId())){
2618 public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2619 // kick off a thread to do an event notification for each PDP.
2620 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2621 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2622 Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
2623 if(CheckPDP.validateID(pdp.getId())){
2628 private class UpdatePDPThread implements Runnable {
2629 private OnapPDP pdp;
2630 private String requestId;
2631 private ONAPLoggingContext loggingContext;
2633 public UpdatePDPThread(OnapPDP pdp) {
2637 public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
2639 if ((loggingContext != null) && (loggingContext.getRequestID() != null || loggingContext.getRequestID() == "")) {
2640 this.requestId = loggingContext.getRequestID();
2642 this.loggingContext = loggingContext;
2646 // send the current configuration to one PDP
2647 HttpURLConnection connection = null;
2648 // get a new logging context for the thread
2650 if (this.loggingContext == null) {
2651 loggingContext = new ONAPLoggingContext(baseLoggingContext);
2653 } catch (Exception e) {
2654 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2655 // Since this is a server-side error, it probably does not reflect a problem on the client,
2656 // so do not change the PDP status.
2660 loggingContext.setServiceName("PAP:PDP.putConfig");
2661 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2662 if ((requestId == null) || (requestId == "")) {
2663 UUID requestID = UUID.randomUUID();
2664 loggingContext.setRequestID(requestID.toString());
2665 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2667 loggingContext.setRequestID(requestId);
2668 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2670 loggingContext.transactionStarted();
2671 // the Id of the PDP is its URL
2672 if (LOGGER.isDebugEnabled()) {
2673 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2675 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2676 //TODO (need to change "cache=", implying getting some input saying which to change)
2677 URL url = new URL(pdp.getId() + "?cache=all");
2678 // Open up the connection
2679 connection = (HttpURLConnection)url.openConnection();
2680 // Setup our method and headers
2681 connection.setRequestMethod("PUT");
2683 String encoding = CheckPDP.getEncoding(pdp.getId());
2684 if(encoding !=null){
2685 connection.setRequestProperty("Authorization", "Basic " + encoding);
2687 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2688 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2689 connection.setInstanceFollowRedirects(true);
2690 connection.setDoOutput(true);
2691 try (OutputStream os = connection.getOutputStream()) {
2692 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2693 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2694 if (group == null) {
2695 // create blank properties files
2696 Properties policyProperties = new Properties();
2697 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2698 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2699 policyProperties.store(os, "");
2700 Properties pipProps = new Properties();
2701 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2702 pipProps.store(os, "");
2704 // send properties from the current group
2705 group.getPolicyProperties().store(os, "");
2706 Properties policyLocations = new Properties();
2707 for (PDPPolicy policy : group.getPolicies()) {
2708 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2710 policyLocations.store(os, "");
2711 group.getPipConfigProperties().store(os, "");
2713 } catch (Exception e) {
2714 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2715 // Since this is a server-side error, it probably does not reflect a problem on the client,
2716 // so do not change the PDP status.
2720 loggingContext.metricStarted();
2721 connection.connect();
2722 loggingContext.metricEnded();
2723 PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread connection connect");
2724 if (connection.getResponseCode() == 204) {
2725 LOGGER.info("Success. We are configured correctly.");
2726 loggingContext.transactionEnded();
2727 auditLogger.info("Success. PDP is configured correctly.");
2728 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2729 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2730 } else if (connection.getResponseCode() == 200) {
2731 LOGGER.info("Success. PDP needs to update its configuration.");
2732 loggingContext.transactionEnded();
2733 auditLogger.info("Success. PDP needs to update its configuration.");
2734 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2735 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2737 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2738 loggingContext.transactionEnded();
2739 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2740 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2741 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2743 } catch (Exception e) {
2745 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2746 loggingContext.transactionEnded();
2747 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2749 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2750 } catch (PAPException e1) {
2752 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2753 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2756 // cleanup the connection
2757 if(connection != null){
2758 connection.disconnect();
2760 // tell the AC to update it's status info
2767 * RESTful Interface from PAP to ACs notifying them of changes
2769 private void notifyAC() {
2770 // kick off a thread to do one event notification for all registered ACs
2771 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2772 // as part of processing this message on their end.
2773 Thread t = new Thread(new NotifyACThread());
2777 private class NotifyACThread implements Runnable {
2779 List<String> disconnectedACs = new ArrayList<>();
2780 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2781 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2782 for (String acURL : adminConsoleURLStringList) {
2783 HttpURLConnection connection = null;
2785 acURL += "?PAPNotification=true";
2786 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2787 //TODO - If so, put correct parameters into the Query string here
2788 acURL += "&objectType=all" + "&action=update";
2789 if (LOGGER.isDebugEnabled()) {
2790 LOGGER.debug("creating url for id '" + acURL + "'");
2792 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2793 //TODO (need to change "cache=", implying getting some input saying which to change)
2794 URL url = new URL(acURL );
2795 // Open up the connection
2796 connection = (HttpURLConnection)url.openConnection();
2797 // Setup our method and headers
2798 connection.setRequestMethod("PUT");
2799 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2800 // Adding this in. It seems the HttpUrlConnection class does NOT
2801 // properly forward our headers for POST re-direction. It does so
2802 // for a GET re-direction.
2803 // So we need to handle this ourselves.
2804 //TODO - is this needed for a PUT? seems better to leave in for now?
2805 connection.setInstanceFollowRedirects(false);
2806 // Do not include any data in the PUT because this is just a
2807 // notification to the AC.
2808 // The AC will use GETs back to the PAP to get what it needs
2809 // to fill in the screens.
2811 connection.connect();
2812 if (connection.getResponseCode() == 204) {
2813 LOGGER.info("Success. We updated correctly.");
2815 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2818 } catch (Exception e) {
2819 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2820 disconnectedACs.add(acURL);
2822 // cleanup the connection
2823 if(connection != null)
2824 connection.disconnect();
2827 // remove any ACs that are no longer connected
2828 if (!disconnectedACs.isEmpty()) {
2829 adminConsoleURLStringList.removeAll(disconnectedACs);
2834 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2835 LOGGER.info("Test request received");
2837 im.evaluateSanity();
2838 //If we make it this far, all is well
2839 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2840 LOGGER.info(message);
2841 loggingContext.transactionEnded();
2842 PolicyLogger.audit("Transaction Failed - See Error.log");
2843 response.setStatus(HttpServletResponse.SC_OK);
2845 }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2847 if (e instanceof ForwardProgressException) {
2848 submsg = " is not making forward progress.";
2849 } else if (e instanceof AdministrativeStateException) {
2850 submsg = " Administrative State is LOCKED.";
2852 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2855 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2856 + " Exception Message: " + e.getMessage();
2857 LOGGER.info(message, e);
2858 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2859 loggingContext.transactionEnded();
2860 PolicyLogger.audit("Transaction Failed - See Error.log");
2861 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2863 }catch (Exception e) {
2864 //A subsystem is not making progress, is locked, standby or is not responding
2865 String eMsg = e.getMessage();
2867 eMsg = "No Exception Message";
2869 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2870 + " Exception Message: " + eMsg;
2871 LOGGER.info(message, e);
2872 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2873 loggingContext.transactionEnded();
2874 PolicyLogger.audit("Transaction Failed - See Error.log");
2875 //Get the specific list of subsystems that failed
2876 String ssFailureList = null;
2877 for(String failedSS : papDependencyGroupsFlatArray){
2878 if(eMsg.contains(failedSS)){
2879 if(ssFailureList == null){
2880 ssFailureList = failedSS;
2882 ssFailureList = ssFailureList.concat(","+failedSS);
2886 if(ssFailureList == null){
2887 ssFailureList = "UnknownSubSystem";
2889 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2890 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2896 * Authorizing the PEP Requests.
2898 private boolean authorizeRequest(HttpServletRequest request) {
2899 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2900 // Check if the Client is Authorized.
2901 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2908 private static void loadWebapps() throws PAPException{
2909 if(actionHome == null || configHome == null){
2910 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2912 if (webappsPath == null) {
2913 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2914 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2916 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2917 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2918 if (Files.notExists(webappsPathConfig)) {
2920 Files.createDirectories(webappsPathConfig);
2921 } catch (IOException e) {
2922 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2923 + webappsPathConfig.toAbsolutePath().toString());
2926 if (Files.notExists(webappsPathAction)) {
2928 Files.createDirectories(webappsPathAction);
2929 } catch (IOException e) {
2930 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2931 + webappsPathAction.toAbsolutePath().toString(), e);
2934 actionHome = webappsPathAction.toString();
2935 configHome = webappsPathConfig.toString();
2939 public static String getConfigHome(){
2942 } catch (PAPException e) {
2949 private static void setConfigHome(){
2950 configHome = getConfigHome();
2953 public static String getActionHome(){
2956 } catch (PAPException e) {
2963 private static void setActionHome(){
2964 actionHome = getActionHome();
2967 public static EntityManagerFactory getEmf() {
2971 public IntegrityAudit getIa() {
2975 public static String getPDPFile(){
2976 return XACMLPapServlet.pdpFile;
2979 public static String getPersistenceUnit(){
2980 return PERSISTENCE_UNIT;
2983 public static PAPPolicyEngine getPAPEngine(){
2987 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2988 return policyDBDao.getNewTransaction();
2990 public static String getPapDbDriver() {
2994 public static void setPapDbDriver(String papDbDriver) {
2995 XACMLPapServlet.papDbDriver = papDbDriver;
2998 public static String getPapDbUrl() {
3002 public static void setPapDbUrl(String papDbUrl) {
3003 XACMLPapServlet.papDbUrl = papDbUrl;
3006 public static String getPapDbUser() {
3010 public static void setPapDbUser(String papDbUser) {
3011 XACMLPapServlet.papDbUser = papDbUser;
3014 public static String getPapDbPassword() {
3015 return papDbPassword;
3018 public static void setPapDbPassword(String papDbPassword) {
3019 XACMLPapServlet.papDbPassword = papDbPassword;
3022 public static String getMsOnapName() {
3026 public static void setMsOnapName(String msOnapName) {
3027 XACMLPapServlet.msOnapName = msOnapName;
3030 public static String getMsPolicyName() {
3031 return msPolicyName;
3034 public static void setMsPolicyName(String msPolicyName) {
3035 XACMLPapServlet.msPolicyName = msPolicyName;