2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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;
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.att.research.xacml.api.pap.PDPStatus;
26 import com.att.research.xacml.util.FactoryException;
27 import com.att.research.xacml.util.XACMLProperties;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.google.common.base.Splitter;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.net.InetAddress;
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.List;
41 import java.util.Properties;
43 import java.util.UUID;
44 import java.util.concurrent.CopyOnWriteArrayList;
45 import javax.persistence.PersistenceException;
46 import javax.servlet.Servlet;
47 import javax.servlet.ServletConfig;
48 import javax.servlet.ServletException;
49 import javax.servlet.annotation.WebInitParam;
50 import javax.servlet.annotation.WebServlet;
51 import javax.servlet.http.HttpServlet;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
54 import org.apache.commons.io.IOUtils;
55 import org.onap.policy.common.ia.IntegrityAudit;
56 import org.onap.policy.common.im.AdministrativeStateException;
57 import org.onap.policy.common.im.ForwardProgressException;
58 import org.onap.policy.common.im.IntegrityMonitor;
59 import org.onap.policy.common.im.IntegrityMonitorException;
60 import org.onap.policy.common.im.IntegrityMonitorProperties;
61 import org.onap.policy.common.im.StandbyStatusException;
62 import org.onap.policy.common.logging.ONAPLoggingContext;
63 import org.onap.policy.common.logging.ONAPLoggingUtils;
64 import org.onap.policy.common.logging.eelf.MessageCodes;
65 import org.onap.policy.common.logging.eelf.PolicyLogger;
66 import org.onap.policy.common.logging.flexlogger.FlexLogger;
67 import org.onap.policy.common.logging.flexlogger.Logger;
68 import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications;
69 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
70 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
71 import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
72 import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
73 import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
74 import org.onap.policy.pap.xacml.restAuth.CheckPDP;
75 import org.onap.policy.rest.XACMLRest;
76 import org.onap.policy.rest.XACMLRestProperties;
77 import org.onap.policy.rest.dao.PolicyDBException;
78 import org.onap.policy.utils.PeCryptoUtils;
79 import org.onap.policy.utils.PolicyUtils;
80 import org.onap.policy.xacml.api.XACMLErrorConstants;
81 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
82 import org.onap.policy.xacml.api.pap.OnapPDP;
83 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
84 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
85 import org.onap.policy.xacml.std.pap.StdPDP;
86 import org.onap.policy.xacml.std.pap.StdPDPGroup;
87 import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
88 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
89 import org.onap.policy.xacml.std.pap.StdPDPStatus;
92 * Servlet implementation class XacmlPapServlet.
94 @WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"},
96 initParams = {@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties",
97 description = "The location of the properties file holding configuration information.")})
98 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
99 private static final long serialVersionUID = 1L;
100 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
101 // audit (transaction) LOGGER
102 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
103 // Persistence Unit for JPA
104 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
105 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
107 private static final String ENVIRONMENT_HEADER = "Environment";
108 private static final String ADD_GROUP_ERROR = "addGroupError";
109 private static final String PERSISTENCE_JDBC_PWD = "javax.persistence.jdbc.password";
111 private static final String REGEX = "[0-9a-zA-Z._ ]*";
114 * List of Admin Console URLs. Used to send notifications when configuration changes.
116 * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom
117 * changed but often read, so the costs of this approach make sense.
119 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList =
120 new CopyOnWriteArrayList<>();
122 private static String configHome;
123 private static String actionHome;
125 * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET
126 * the Policy files from this process.
128 private static String papUrl = null;
129 // The heartbeat thread.
130 private static Heartbeat heartbeat = null;
131 private static Thread heartbeatThread = null;
132 private static PolicyDBDao policyDbDao;
134 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
136 private static PAPPolicyEngine papEngine = null;
138 * These are the parameters needed for DB access from the PAP
140 private static int papIntegrityAuditPeriodSeconds = -1;
141 private static String papDbDriver = null;
142 private static String papDbUrl = null;
143 private static String papDbUser = null;
144 private static String papDbPd = null;
145 private static String papResourceName = null;
146 private static String[] papDependencyGroupsFlatArray = null;
147 private static String environment = null;
148 private static String pdpFile = null;
150 private transient IntegrityMonitor im;
151 private transient IntegrityAudit ia;
153 // MicroService Model Properties
154 private static String msOnapName;
155 private static String msPolicyName;
157 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
158 * this servlet starts. Its configurable by the admin.
160 private static transient Thread initiateThread = null;
161 private transient ONAPLoggingContext baseLoggingContext = null;
162 private static final String GROUPID = "groupId";
165 * @see HttpServlet#HttpServlet()
167 public XACMLPapServlet() {
172 * @see Servlet#init(ServletConfig)
175 public void init(ServletConfig config) throws ServletException {
178 baseLoggingContext = new ONAPLoggingContext();
179 // fixed data that will be the same in all logging output goes here
181 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
182 baseLoggingContext.setServer(hostname);
183 } catch (UnknownHostException e) {
184 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR
185 + "Unable to get hostname for logging", e);
189 XACMLRest.xacmlInit(config);
190 // Load the properties
191 XACMLRest.loadXacmlProperties(null, null);
193 * Retrieve the property values
195 setCommonProperties();
196 String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
197 if (papSiteName == null) {
198 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
199 " ERROR: Bad papSiteName property entry");
200 throw new PAPException("papSiteName is null");
202 String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
203 if (papNodeType == null) {
204 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
205 " ERROR: Bad papNodeType property entry");
206 throw new PAPException("papNodeType is null");
208 // Integer will throw an exception of anything is missing or
210 int papTransWait = Integer
211 .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
212 int papTransTimeout = Integer.parseInt(
213 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
214 int papAuditTimeout = Integer.parseInt(
215 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
216 // Boolean will default to false if anything is missing or
218 boolean papAuditFlag = Boolean.parseBoolean(
219 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
220 boolean papFileSystemAudit = Boolean.parseBoolean(
221 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
222 String papDependencyGroups =
223 XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
224 if (papDependencyGroups == null) {
225 throw new PAPException("papDependencyGroups is null");
227 setPAPDependencyGroups(papDependencyGroups);
228 // Integer will throw an exception of anything is missing or
230 int fpMonitorInterval = Integer.parseInt(
231 XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
232 int failedCounterThreshold = Integer.parseInt(XACMLProperties
233 .getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
234 int testTransInterval = Integer.parseInt(
235 XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
236 int writeFpcInterval = Integer.parseInt(
237 XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
238 LOGGER.debug("\n\n\n**************************************"
239 + "\n*************************************" + "\n" + "\n papDbDriver = "
240 + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + papDbUser
241 + "\n papTransWait = " + papTransWait + "\n papTransTimeout = "
242 + papTransTimeout + "\n papAuditTimeout = " + papAuditTimeout
243 + "\n papAuditFlag = " + papAuditFlag + "\n papFileSystemAudit = "
244 + papFileSystemAudit + "\n papResourceName = " + papResourceName
245 + "\n fpMonitorInterval = " + fpMonitorInterval
246 + "\n failedCounterThreshold = " + failedCounterThreshold
247 + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = "
248 + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = "
249 + papNodeType + "\n papDependencyGroupsList = " + papDependencyGroups
250 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
251 + "\n\n*************************************"
252 + "\n**************************************");
253 // Pull custom persistence settings
254 Properties properties;
256 properties = XACMLProperties.getProperties();
257 LOGGER.debug("\n\n\n**************************************"
258 + "\n**************************************" + "\n\n" + "properties = "
259 + properties + "\n\n**************************************");
260 } catch (IOException e) {
261 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet",
262 " Error loading properties with: " + "XACMLProperties.getProperties()");
263 throw new ServletException(e.getMessage(), e.getCause());
265 // Create an IntegrityMonitor
266 if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
267 properties.setProperty(PERSISTENCE_JDBC_PWD,
268 PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
270 im = IntegrityMonitor.getInstance(papResourceName, properties);
271 // Create an IntegrityAudit
272 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
273 ia.startAuditThread();
274 // we are about to call the PDPs and give them their configuration.
275 // To do that we need to have the URL of this PAP so we can
276 // construct the Policy file URLs
277 setPapUrl(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
278 // Create the policyDBDao
280 // Load our PAP engine, first create a factory
281 ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(
282 XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
283 // The factory knows how to go about creating a PAP Engine
284 setPAPEngine(factory.newEngine());
285 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
286 createDefaultGroupOnInit();
288 policyDbDao.setPapEngine(XACMLPapServlet.papEngine);
289 if (Boolean.parseBoolean(
290 XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
292 * Auditing the local File System groups to be in sync with the Database
295 // get an AuditTransaction to lock out all other transactions
296 PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
298 LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
299 LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
300 // get the current filesystem group and update from the database
302 StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
303 StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group);
304 if (updatedGroup != null) {
305 papEngine.updateGroup(updatedGroup);
308 "PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
310 // sync up the config data from DB to file system
311 LOGGER.info("PapServlet: Sync config data from DB to file system");
312 policyDbDao.synchronizeConfigDataInFileSystem();
314 // release the transaction lock
318 // Configurable - have the PAP servlet initiate sending the latest
319 // PDP policy/pip configuration
320 // to all its known PDP nodes.
321 if (Boolean.parseBoolean(XACMLProperties
322 .getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
323 startInitiateThreadService(new Thread(this));
325 // After startup, the PAP does Heartbeat's to each of the PDPs
327 startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine));
328 } catch (FactoryException | PAPException e) {
329 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
330 " Failed to create engine");
331 throw new ServletException(
332 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e);
333 } catch (Exception e) {
334 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
335 " Failed to create engine - unexpected error");
336 throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR
337 + "PAP not initialized; unexpected error: " + e);
342 private void createDefaultGroupOnInit() {
343 PolicyDBDaoTransaction addNewGroup = null;
345 addNewGroup = policyDbDao.getNewTransaction();
346 OnapPDPGroup group = papEngine.getDefaultGroup();
347 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
348 "automaticallyAdded");
349 addNewGroup.commitTransaction();
350 addNewGroup = policyDbDao.getNewTransaction();
351 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
352 addNewGroup.commitTransaction();
353 } catch (Exception e) {
354 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
355 " Error creating new default group in the database");
356 if (addNewGroup != null) {
357 addNewGroup.rollbackTransaction();
362 private static void startInitiateThreadService(Thread thread) {
363 initiateThread = thread;
364 initiateThread.start();
367 private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response,
370 mapper.writeValue(response.getOutputStream(), value);
371 } catch (Exception e) {
376 private static void startHeartBeatService(Heartbeat heartbeat) {
377 XACMLPapServlet.heartbeat = heartbeat;
378 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
379 XACMLPapServlet.heartbeatThread.start();
382 private static void setPolicyDbDao() throws ServletException {
384 policyDbDao = PolicyDBDao.getPolicyDBDaoInstance();
385 } catch (Exception e) {
386 throw new ServletException("Unable to Create Policy DBDao Instance", e);
390 public static PolicyDBDao getPolicyDbDao() {
394 private static void setPapUrl(String papUrl) {
395 XACMLPapServlet.papUrl = papUrl;
398 public static String getPapUrl() {
402 private static void setPAPEngine(PAPPolicyEngine newEngine) {
403 XACMLPapServlet.papEngine = newEngine;
406 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
408 // Now we have flattened the array into a simple comma-separated list
409 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
410 // clean up the entries
411 for (int i = 0; i < papDependencyGroupsFlatArray.length; i++) {
412 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
415 if (XACMLProperties.getProperty(
416 XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) {
417 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties
418 .getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS)
421 } catch (Exception e) {
422 String msg = "integrity_audit_period_seconds ";
423 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
424 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
425 " ERROR: " + msg + "Bad property entry");
428 } catch (Exception e) {
429 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
430 " ERROR: Bad property entry");
431 throw new PAPException(e);
435 private static void setCommonProperties() throws PAPException {
438 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
439 if (papDbDriver == null) {
440 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
441 " ERROR: Bad papDbDriver property entry");
442 throw new PAPException("papDbDriver is null");
444 setPapDbDriver(papDbDriver);
445 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
446 if (papDbUrl == null) {
447 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
448 " ERROR: Bad papDbUrl property entry");
449 throw new PAPException("papDbUrl is null");
451 setPapDbUrl(papDbUrl);
452 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
453 if (papDbUser == null) {
454 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
455 " ERROR: Bad papDbUser property entry");
456 throw new PAPException("papDbUser is null");
458 setPapDbUser(papDbUser);
459 PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
460 papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD));
461 if (papDbPd == null) {
462 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
463 " ERROR: Bad papDbPassword property entry");
464 throw new PAPException("papDbPassword is null");
466 setPapDbPassword(papDbPd);
467 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
468 if (papResourceName == null) {
469 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
470 " ERROR: Bad papResourceName property entry");
471 throw new PAPException("papResourceName is null");
473 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
474 // Micro Service Properties
475 msOnapName = XACMLProperties.getProperty("xacml.policy.msOnapName");
476 setMsOnapName(msOnapName);
477 msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName");
478 setMsPolicyName(msPolicyName);
479 // PDPId File location
480 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
481 if (XACMLPapServlet.pdpFile == null) {
482 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
483 + " The PDP Id Authentication File Property is not valid: "
484 + XACMLRestProperties.PROP_PDP_IDFILE);
485 throw new PAPException("The PDP Id Authentication File Property :"
486 + XACMLRestProperties.PROP_PDP_IDFILE + " is not Valid. ");
491 * Thread used only during PAP startup to initiate change messages to all known PDPs. This must
492 * be on a separate thread so that any GET requests from the PDPs during this update can be
497 // send the current configuration to all the PDPs that we know about
502 * @see Servlet#destroy()
504 * Depending on how this servlet is run, we may or may not care about cleaning up the
505 * resources. For now we assume that we do care.
508 public void destroy() {
509 // Make sure our threads are destroyed
510 if (XACMLPapServlet.heartbeatThread != null) {
511 // stop the heartbeat
513 if (XACMLPapServlet.heartbeat != null) {
514 XACMLPapServlet.heartbeat.terminate();
516 XACMLPapServlet.heartbeatThread.interrupt();
517 XACMLPapServlet.heartbeatThread.join();
518 } catch (InterruptedException e) {
519 XACMLPapServlet.heartbeatThread.interrupt();
520 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
521 " Error stopping heartbeat");
524 if (initiateThread != null) {
526 initiateThread.interrupt();
527 initiateThread.join();
528 } catch (InterruptedException e) {
529 initiateThread.interrupt();
530 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
531 " Error stopping thread");
536 private ConsoleAndApiService getAcServiceInstance() {
537 return new ConsoleAndApiService();
541 * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make
542 * changes in the PDP Groups.
544 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
547 protected void doPost(HttpServletRequest request, HttpServletResponse response)
548 throws ServletException, IOException {
549 ONAPLoggingContext loggingContext =
550 ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
551 setLoggingContext(loggingContext, "doPost", "PAP.post");
552 PolicyDBDaoTransaction pdpTransaction = null;
554 loggingContext.metricStarted();
555 im.startTransaction();
556 loggingContext.metricEnded();
557 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
558 } catch (AdministrativeStateException ae) {
559 String message = "POST interface called for PAP " + papResourceName
560 + " but it has an Administrative state of "
561 + im.getStateManager().getAdminState() + "\n Exception Message: "
562 + PolicyUtils.CATCH_EXCEPTION;
563 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
564 loggingContext.metricEnded();
565 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
566 loggingContext.transactionEnded();
567 PolicyLogger.audit("Transaction Failed - See Error.log");
568 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
570 } catch (IntegrityMonitorException ime) {
571 String message = "POST interface called for PAP " + papResourceName
572 + " but it has an Administrative state of "
573 + im.getStateManager().getAdminState()
574 + " and a Standby Status of "
575 + im.getStateManager().getStandbyStatus()
576 + "\n Exception Message: "
578 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime);
579 loggingContext.metricEnded();
580 PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
581 loggingContext.transactionEnded();
582 PolicyLogger.audit("Transaction Failed - See Error.log");
583 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
587 loggingContext.metricStarted();
588 XACMLRest.dumpRequest(request);
589 loggingContext.metricEnded();
590 PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
591 // since getParameter reads the content string, explicitly get the
592 // content before doing that.
593 // Simply getting the inputStream seems to protect it against being
594 // consumed by getParameter.
595 request.getInputStream();
596 String groupId = request.getParameter(GROUPID);
597 String apiflag = request.getParameter("apiflag");
598 if (groupId != null) {
599 // Is this from the Admin Console or API?
600 if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
601 // this is from the API so we need to check the client
602 // credentials before processing the request
603 if (!authorizeRequest(request)) {
604 String message = "PEP not Authorized for making this Request!!";
605 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
606 loggingContext.transactionEnded();
607 PolicyLogger.audit("Transaction Failed - See Error.log");
608 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
613 loggingContext.metricStarted();
614 getAcServiceInstance().doAcPost(request, response, groupId, loggingContext,
616 loggingContext.metricEnded();
617 PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
618 loggingContext.transactionEnded();
619 PolicyLogger.audit("Transaction Ended Successfully");
623 // Request is from a PDP asking for its config.
624 loggingContext.setServiceName("PDP:PAP.register");
626 String id = this.getPDPID(request);
627 String jmxport = this.getPDPJMX(request);
628 LOGGER.info("Request(doPost) from PDP coming up: " + id);
629 // Get the PDP Object
630 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
633 LOGGER.info("Unknown PDP: " + id);
635 if (CheckPDP.validateID(id)) {
636 pdpTransaction = policyDbDao.getNewTransaction();
638 pdpTransaction.addPdpToGroup(id,
639 XACMLPapServlet.papEngine.getDefaultGroup().getId(), id,
640 "Registered on first startup", Integer.parseInt(jmxport),
642 XACMLPapServlet.papEngine.newPDP(id,
643 XACMLPapServlet.papEngine.getDefaultGroup(), id,
644 "Registered on first startup", Integer.parseInt(jmxport));
645 } catch (NullPointerException | PAPException | IllegalArgumentException
646 | IllegalStateException | PersistenceException | PolicyDBException e) {
647 pdpTransaction.rollbackTransaction();
648 String message = "Failed to create new PDP for id: " + id;
649 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
651 loggingContext.transactionEnded();
652 PolicyLogger.audit("Transaction Failed - See Error.log");
653 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
658 // get the PDP we just created
660 pdp = XACMLPapServlet.papEngine.getPDP(id);
661 } catch (PAPException e) {
665 if (pdpTransaction != null) {
666 pdpTransaction.rollbackTransaction();
668 String message = "Failed to create new PDP for id: " + id;
669 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
670 loggingContext.transactionEnded();
671 PolicyLogger.audit("Transaction Failed - See Error.log");
672 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
678 String message = "PDP is Unauthorized to Connect to PAP: " + id;
679 loggingContext.transactionEnded();
680 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
681 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
682 "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
683 PolicyLogger.audit("Transaction Failed - See Error.log");
688 loggingContext.metricStarted();
689 pdpTransaction.commitTransaction();
690 loggingContext.metricEnded();
691 PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
692 } catch (Exception e) {
693 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
694 "Could not commit transaction to put pdp in the database");
697 if (jmxport != null && !"".equals(jmxport)) {
699 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
700 } catch (NumberFormatException e) {
704 // Get the PDP's Group
705 OnapPDPGroup group = null;
707 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
708 } catch (PAPException e) {
712 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW
713 + " PDP not associated with any group, even the default");
714 loggingContext.transactionEnded();
715 PolicyLogger.audit("Transaction Failed - See Error.log");
716 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
717 "PDP not associated with any group, even the default");
721 // Determine what group the PDP node is in and get
722 // its policy/pip properties.
723 Properties policies = group.getPolicyProperties();
724 Properties pipconfig = group.getPipConfigProperties();
725 // Get the current policy/pip configuration that the PDP has
726 Properties pdpProperties = new Properties();
728 pdpProperties.load(request.getInputStream());
729 } catch (IOException e) {
732 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
733 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
734 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
735 // Validate the node's properties
736 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
737 // Send back current configuration
739 // Tell the PDP we are sending back the current policies/pip
741 LOGGER.info("PDP configuration NOT current.");
742 if (policies != null) {
743 // Put URL's into the properties in case the PDP needs to
745 this.populatePolicyURL(request.getRequestURL(), policies);
746 // Copy the properties to the output stream
748 policies.store(response.getOutputStream(), "");
749 } catch (IOException e) {
753 if (pipconfig != null) {
754 // Copy the properties to the output stream
756 pipconfig.store(response.getOutputStream(), "");
757 } catch (IOException e) {
761 // We are good - and we are sending them information
762 response.setStatus(HttpServletResponse.SC_OK);
764 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
765 } catch (PAPException e) {
769 // Tell them they are good
770 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
772 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
773 } catch (PAPException e) {
777 auditLogger.info("Success");
778 PolicyLogger.audit("Transaction Ended Successfully");
779 } catch (PAPException | IOException | NumberFormatException e) {
780 if (pdpTransaction != null) {
781 pdpTransaction.rollbackTransaction();
783 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
784 loggingContext.transactionEnded();
785 PolicyLogger.audit("Transaction Failed - See Error.log");
786 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
791 // Catch anything that fell through
792 loggingContext.transactionEnded();
793 PolicyLogger.audit("Transaction Ended");
797 private void setResponseError(HttpServletResponse response, int responseCode, String message) {
799 if (message != null && !message.isEmpty()) {
800 response.sendError(responseCode, message);
802 } catch (IOException e) {
803 LOGGER.error("Error setting Error response Header ", e);
808 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
811 protected void doGet(HttpServletRequest request, HttpServletResponse response)
812 throws ServletException, IOException {
813 ONAPLoggingContext loggingContext =
814 ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
815 setLoggingContext(loggingContext, "doGet", "PAP.get");
816 loggingContext.metricStarted();
817 XACMLRest.dumpRequest(request);
818 loggingContext.metricEnded();
819 PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
820 String pathInfo = request.getRequestURI();
821 LOGGER.info("path info: " + pathInfo);
822 if (pathInfo != null && "/pap/test".equals(pathInfo)) {
823 // DO NOT do a im.startTransaction for the test request
825 testService(loggingContext, response);
826 } catch (IOException e) {
831 // This im.startTransaction() covers all other Get transactions
833 loggingContext.metricStarted();
834 im.startTransaction();
835 loggingContext.metricEnded();
836 PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction");
837 } catch (IntegrityMonitorException ime) {
838 String message = "GET interface called for PAP " + papResourceName
839 + " but it has an Administrative state of "
840 + im.getStateManager().getAdminState()
841 + " and a Standby Status of "
842 + im.getStateManager().getStandbyStatus()
843 + "\n Exception Message: "
845 LOGGER.info(message, ime);
846 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
847 loggingContext.transactionEnded();
848 PolicyLogger.audit("Transaction Failed - See Error.log");
849 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
852 // Request from the API to get the gitPath
853 String apiflag = request.getParameter("apiflag");
854 if (apiflag != null) {
855 if (authorizeRequest(request)) {
856 APIRequestHandler apiRequestHandler = new APIRequestHandler();
858 loggingContext.metricStarted();
859 apiRequestHandler.doGet(request, response, apiflag);
860 loggingContext.metricEnded();
861 PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
862 } catch (IOException e) {
865 loggingContext.transactionEnded();
866 PolicyLogger.audit("Transaction Ended Successfully");
871 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
872 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
873 loggingContext.transactionEnded();
874 PolicyLogger.audit("Transaction Failed - See Error.log");
875 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
880 // Is this from the Admin Console?
881 String groupId = request.getParameter(GROUPID);
882 if (groupId != null) {
883 // this is from the Admin Console, so handle separately
885 loggingContext.metricStarted();
886 getAcServiceInstance().doAcGet(request, response, groupId, loggingContext,
888 loggingContext.metricEnded();
889 PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
890 } catch (IOException e) {
893 loggingContext.transactionEnded();
894 PolicyLogger.audit("Transaction Ended Successfully");
899 String id = this.getPDPID(request);
900 LOGGER.info("doGet from: " + id);
901 // Get the PDP Object
904 pdp = XACMLPapServlet.papEngine.getPDP(id);
905 } catch (PAPException e) {
910 // Check if request came from localhost
911 if ("localhost".equals(request.getRemoteHost())
912 || request.getRemoteHost().equals(request.getLocalAddr())) {
913 // Return status information - basically all the groups
914 loggingContext.setServiceName("PAP.getGroups");
915 Set<OnapPDPGroup> groups = null;
917 groups = papEngine.getOnapPDPGroups();
918 } catch (PAPException e) {
920 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet",
922 loggingContext.transactionEnded();
923 PolicyLogger.audit("Transaction Failed - See Error.log");
924 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
929 // convert response object to JSON and include in the response
930 mapperWriteValue(new ObjectMapper(), response, groups);
931 response.setHeader("content-type", "application/json");
932 response.setStatus(HttpServletResponse.SC_OK);
933 loggingContext.transactionEnded();
934 PolicyLogger.audit("Transaction Ended Successfully");
938 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: "
939 + request.getLocalAddr();
940 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
941 loggingContext.transactionEnded();
942 PolicyLogger.audit("Transaction Failed - See Error.log");
943 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
947 loggingContext.setServiceName("PAP.getPolicy");
948 // Get the PDP's Group
949 OnapPDPGroup group = null;
951 group = XACMLPapServlet.papEngine.getPDPGroup(pdp);
952 } catch (PAPException e) {
956 String message = "No group associated with pdp " + pdp.getId();
957 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
958 loggingContext.transactionEnded();
959 PolicyLogger.audit("Transaction Failed - See Error.log");
960 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
964 // Which policy do they want?
965 String policyId = request.getParameter("id");
966 if (policyId == null) {
967 String message = "Did not specify an id for the policy";
968 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
969 loggingContext.transactionEnded();
970 PolicyLogger.audit("Transaction Failed - See Error.log");
971 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
975 PDPPolicy policy = group.getPolicy(policyId);
976 if (policy == null) {
977 String message = "Unknown policy: " + policyId;
978 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
979 loggingContext.transactionEnded();
980 PolicyLogger.audit("Transaction Failed - See Error.log");
981 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
986 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
987 + "Policy Name : " + policy.getName() + "\n Policy URI: "
988 + policy.getLocation().toString());
989 } catch (PAPException | IOException e) {
992 try (InputStream is = new FileInputStream(
993 ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId);
994 OutputStream os = response.getOutputStream()) {
995 // Send the policy back
996 IOUtils.copy(is, os);
997 response.setStatus(HttpServletResponse.SC_OK);
998 loggingContext.transactionEnded();
999 auditLogger.info("Success");
1000 PolicyLogger.audit("Transaction Ended Successfully");
1001 } catch (IOException e) {
1002 String message = "Failed to open policy id " + policyId;
1004 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1005 loggingContext.transactionEnded();
1006 PolicyLogger.audit("Transaction Failed - See Error.log");
1007 setResponseError(response, HttpServletResponse.SC_NOT_FOUND, message);
1009 loggingContext.transactionEnded();
1010 PolicyLogger.audit("Transaction Ended");
1011 im.endTransaction();
1015 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
1018 protected void doPut(HttpServletRequest request, HttpServletResponse response)
1019 throws ServletException, IOException {
1020 ONAPLoggingContext loggingContext =
1021 ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1022 setLoggingContext(loggingContext, "doPut", "PAP.put");
1024 loggingContext.metricStarted();
1025 im.startTransaction();
1026 loggingContext.metricEnded();
1027 PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
1028 } catch (IntegrityMonitorException e) {
1029 String message = "PUT interface called for PAP " + papResourceName
1030 + " but it has an Administrative state of "
1031 + im.getStateManager().getAdminState()
1032 + " and a Standby Status of "
1033 + im.getStateManager().getStandbyStatus()
1034 + "\n Exception Message: "
1036 LOGGER.info(message, e);
1037 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1038 loggingContext.transactionEnded();
1039 PolicyLogger.audit("Transaction Failed - See Error.log");
1040 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1044 loggingContext.metricStarted();
1045 // need to check if request is from the API or Admin console
1046 String apiflag = request.getParameter("apiflag");
1047 // For Debug purposes
1048 if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) {
1049 XACMLRest.dumpRequest(request);
1050 PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
1052 loggingContext.metricEnded();
1054 // This would occur if a PolicyDBDao notification was received
1055 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
1056 if (policyDBDaoRequestUrl != null) {
1057 LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received.");
1058 String policyDBDaoRequestEntityId = request.getParameter("entityid");
1059 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
1060 String policyDBDaoRequestExtraData = request.getParameter("extradata");
1061 if (policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null) {
1062 setResponseError(response, 400, "entityid or entitytype not supplied");
1063 loggingContext.transactionEnded();
1064 PolicyLogger.audit("Transaction Ended Successfully");
1065 im.endTransaction();
1068 loggingContext.metricStarted();
1069 LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
1070 HandleIncomingNotifications handleIncomingNotifications =
1071 new HandleIncomingNotifications();
1072 handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl,
1073 policyDBDaoRequestEntityId, policyDBDaoRequestEntityType,
1074 policyDBDaoRequestExtraData, this);
1075 loggingContext.metricEnded();
1076 PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
1077 response.setStatus(200);
1078 loggingContext.transactionEnded();
1079 PolicyLogger.audit("Transaction Ended Successfully");
1080 im.endTransaction();
1084 * Request for ImportService
1086 String importService = request.getParameter("importService");
1087 if (importService != null) {
1088 if (authorizeRequest(request)) {
1089 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1091 loggingContext.metricStarted();
1092 apiRequestHandler.doPut(request, response, importService);
1093 loggingContext.metricEnded();
1094 PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
1095 } catch (IOException e) {
1098 im.endTransaction();
1102 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1103 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message);
1104 loggingContext.transactionEnded();
1105 PolicyLogger.audit("Transaction Failed - See Error.log");
1106 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1111 // See if this is Admin Console registering itself with us
1113 String acURLString = request.getParameter("adminConsoleURL");
1114 if (acURLString != null) {
1115 loggingContext.setServiceName("AC:PAP.register");
1116 // remember this Admin Console for future updates
1117 if (!adminConsoleURLStringList.contains(acURLString)) {
1118 adminConsoleURLStringList.add(acURLString);
1120 if (LOGGER.isDebugEnabled()) {
1121 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1123 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1124 loggingContext.transactionEnded();
1125 auditLogger.info("Success");
1126 PolicyLogger.audit("Transaction Ended Successfully");
1127 im.endTransaction();
1131 * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step
1132 * process to push policies to the PDP that can now be done From both the Admin Console and
1133 * the PolicyEngine API
1135 String groupId = request.getParameter(GROUPID);
1136 if (groupId != null) {
1137 if (apiflag != null) {
1138 if (!authorizeRequest(request)) {
1140 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1141 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1142 loggingContext.transactionEnded();
1143 PolicyLogger.audit("Transaction Failed - See Error.log");
1144 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1147 if (apiflag.equalsIgnoreCase("addPolicyToGroup")) {
1149 updateGroupsFromAPI(request, response, groupId, loggingContext);
1150 } catch (IOException e) {
1153 loggingContext.transactionEnded();
1154 PolicyLogger.audit("Transaction Ended Successfully");
1155 im.endTransaction();
1159 // this is from the Admin Console, so handle separately
1161 loggingContext.metricEnded();
1162 getAcServiceInstance().doAcPut(request, response, groupId, loggingContext,
1164 loggingContext.metricEnded();
1165 PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
1166 } catch (IOException e) {
1169 loggingContext.transactionEnded();
1170 PolicyLogger.audit("Transaction Ended Successfully");
1171 im.endTransaction();
1175 // Request is for policy validation and creation
1177 if (apiflag != null && apiflag.equalsIgnoreCase("admin")) {
1178 // this request is from the Admin Console
1179 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1181 loggingContext.metricStarted();
1182 savePolicyHandler.doPolicyAPIPut(request, response);
1183 loggingContext.metricEnded();
1184 PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
1185 } catch (IOException e) {
1188 loggingContext.transactionEnded();
1189 PolicyLogger.audit("Transaction Ended Successfully");
1190 im.endTransaction();
1192 } else if (apiflag != null && "api".equalsIgnoreCase(apiflag)) {
1193 // this request is from the Policy Creation API
1194 if (authorizeRequest(request)) {
1195 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1197 loggingContext.metricStarted();
1198 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1199 loggingContext.metricEnded();
1200 PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
1201 } catch (IOException e) {
1204 loggingContext.transactionEnded();
1205 PolicyLogger.audit("Transaction Ended Successfully");
1206 im.endTransaction();
1209 String message = "PEP not Authorized for making this Request!!";
1210 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1211 loggingContext.transactionEnded();
1212 PolicyLogger.audit("Transaction Failed - See Error.log");
1213 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1214 im.endTransaction();
1218 // We do not expect anything from anywhere else.
1219 // This method is here in case we ever need to support other operations.
1221 XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1222 loggingContext.transactionEnded();
1223 PolicyLogger.audit("Transaction Failed - See Error.log");
1224 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST,
1225 "Request does not have groupId or apiflag");
1226 loggingContext.transactionEnded();
1227 PolicyLogger.audit("Transaction Failed - See error.log");
1228 im.endTransaction();
1232 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1235 protected void doDelete(HttpServletRequest request, HttpServletResponse response)
1236 throws ServletException, IOException {
1237 ONAPLoggingContext loggingContext =
1238 ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1239 setLoggingContext(loggingContext, "doDelete", "PAP.delete");
1241 loggingContext.metricStarted();
1242 im.startTransaction();
1243 loggingContext.metricEnded();
1244 PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction");
1245 } catch (IntegrityMonitorException ime) {
1246 String message = "DELETE interface called for PAP " + papResourceName
1247 + " but it has an Administrative state of "
1248 + im.getStateManager().getAdminState()
1249 + " and a Standby Status of "
1250 + im.getStateManager().getStandbyStatus()
1251 + "\n Exception Message: "
1253 LOGGER.info(message, ime);
1254 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1255 loggingContext.transactionEnded();
1256 PolicyLogger.audit("Transaction Failed - See Error.log");
1257 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1260 loggingContext.metricStarted();
1261 XACMLRest.dumpRequest(request);
1262 loggingContext.metricEnded();
1263 PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
1264 String groupId = request.getParameter(GROUPID);
1265 String apiflag = request.getParameter("apiflag");
1266 if (groupId != null) {
1267 // Is this from the Admin Console or API?
1268 if (apiflag != null) {
1269 if (!authorizeRequest(request)) {
1271 "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1272 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1273 loggingContext.transactionEnded();
1274 PolicyLogger.audit("Transaction Failed - See Error.log");
1275 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
1278 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1280 loggingContext.metricStarted();
1281 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1282 loggingContext.metricEnded();
1283 PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
1284 } catch (Exception e) {
1285 LOGGER.error("Exception Occured" + e);
1287 if (apiRequestHandler.getNewGroup() != null) {
1288 groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
1292 // this is from the Admin Console, so handle separately
1294 loggingContext.metricStarted();
1295 getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext,
1297 loggingContext.metricEnded();
1298 PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
1299 } catch (IOException e) {
1302 loggingContext.transactionEnded();
1303 PolicyLogger.audit("Transaction Ended Successfully");
1304 im.endTransaction();
1307 // Catch anything that fell through
1308 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1309 loggingContext.transactionEnded();
1310 PolicyLogger.audit("Transaction Failed - See Error.log");
1311 setResponseError(response, HttpServletResponse.SC_BAD_REQUEST,
1312 "Request does not have groupId");
1313 im.endTransaction();
1316 private boolean isPDPCurrent(Properties policies, Properties pipconfig,
1317 Properties pdpProperties) {
1318 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1319 String localReferencedPolicies =
1320 policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1321 if (localRootPolicies == null || localReferencedPolicies == null) {
1322 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE
1323 + "Missing property on PAP server: RootPolicies=" + localRootPolicies
1324 + " ReferencedPolicies=" + localReferencedPolicies);
1327 // Compare the policies and pipconfig properties to the pdpProperties
1329 // the policy properties includes only xacml.rootPolicies and
1330 // xacml.referencedPolicies without any .url entries
1331 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1332 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1333 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES))
1334 && localReferencedPolicies.equals(
1335 pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES))
1336 && pdpPipConfig.equals(pipconfig)) {
1337 // The PDP is current
1340 } catch (Exception e) {
1341 // we get here if the PDP did not include either xacml.rootPolicies
1342 // or xacml.pip.engines,
1343 // or if there are policies that do not have a corresponding ".url"
1345 // Either of these cases means that the PDP is not up-to-date, so
1346 // just drop-through to return false.
1347 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet",
1353 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1354 String lists[] = new String[2];
1355 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1356 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1357 for (String list : lists) {
1358 if (list != null && list.isEmpty() == false) {
1359 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1360 String url = urlPath + "?id=" + id;
1361 LOGGER.info("Policy URL for " + id + ": " + url);
1362 policies.setProperty(id + ".url", url);
1368 protected String getPDPID(HttpServletRequest request) {
1369 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1370 if (pdpURL == null || pdpURL.isEmpty()) {
1371 // Should send back its port for identification
1372 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1378 protected String getPDPJMX(HttpServletRequest request) {
1379 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1380 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1381 // Should send back its port for identification
1382 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE
1383 + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1390 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1395 * @param loggingContext
1396 * @throws ServletException
1397 * @throws IOException
1399 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response,
1400 String groupId, ONAPLoggingContext loggingContext) throws IOException {
1401 PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
1402 PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
1404 String userId = request.getParameter("userId");
1405 // for PUT operations the group may or may not need to exist before
1406 // the operation can be done
1407 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1409 // get the request input stream content into a String
1411 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1412 scanner.useDelimiter("\\A");
1413 json = scanner.hasNext() ? scanner.next() : "";
1416 PolicyLogger.info("pushPolicy request from API: " + json);
1418 // convert Object sent as JSON into local object
1419 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1421 // Get the current policies from the Group and Add the new one
1422 // If the selected policy is in the group we must remove the old
1424 LOGGER.info("Removing old version of the policy");
1425 for (PDPPolicy existingPolicy : group.getPolicies()) {
1426 if (existingPolicy.getName().equals(policy.getName())
1427 && !existingPolicy.getId().equals(policy.getId())) {
1428 group.removePolicy(existingPolicy);
1429 LOGGER.info("Removing policy: " + existingPolicy);
1434 // Assume that this is an update of an existing PDP Group
1435 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1437 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId);
1438 } catch (Exception e) {
1439 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1440 " Error while updating group in the database: " + "group=" + group.getId());
1441 throw new PAPException(e.getMessage());
1444 LOGGER.info("Calling updatGroup() with new group");
1445 papEngine.updateGroup(group);
1446 String policyId = "empty";
1447 if (policy != null && policy.getId() != null) {
1448 policyId = policy.getId();
1450 if (!policyId.matches(REGEX)) {
1451 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1452 response.addHeader("error", ADD_GROUP_ERROR);
1453 response.addHeader("message", "Policy Id is not valid");
1456 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1457 response.addHeader("operation", "push");
1458 response.addHeader("policyId", policyId);
1459 response.addHeader(GROUPID, groupId);
1461 LOGGER.info("Group '" + group.getId() + "' updated");
1463 loggingContext.metricStarted();
1464 acPutTransaction.commitTransaction();
1465 loggingContext.metricEnded();
1466 PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
1468 // Group changed, which might include changing the policies
1469 groupChanged(group, loggingContext);
1470 loggingContext.transactionEnded();
1471 LOGGER.info("Success");
1473 if (policy != null && ((policy.getId().contains("Config_MS_"))
1474 || (policy.getId().contains("BRMS_Param")))) {
1475 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1476 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1477 LOGGER.debug("Precheck Successful.");
1481 PolicyLogger.audit("Transaction Ended Successfully");
1483 } catch (PAPException e) {
1484 acPutTransaction.rollbackTransaction();
1485 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1486 " API PUT exception");
1487 loggingContext.transactionEnded();
1488 PolicyLogger.audit("Transaction Failed - See Error.log");
1489 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW
1490 + "Exception in request to update group from API - See Error.log on on the PAP.";
1491 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1493 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1494 response.addHeader("error", ADD_GROUP_ERROR);
1495 response.addHeader("message", message);
1501 * HELPER to change Group status when PDP status is changed (Must NOT be called from a method
1502 * that is synchronized on the papEngine or it may deadlock)
1504 public void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
1505 setPDPSummaryStatus(pdp, newStatus.toString());
1508 public void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
1509 synchronized (papEngine) {
1510 StdPDPStatus status = new StdPDPStatus();
1511 status.setStatus(PDPStatus.Status.valueOf(newStatus));
1512 ((StdPDP) pdp).setStatus(status);
1513 // now adjust the group
1514 StdPDPGroup group = (StdPDPGroup) papEngine.getPDPGroup(pdp);
1515 // if the PDP was just deleted it may transiently exist but not be
1517 if (group != null) {
1518 group.resetStatus();
1524 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in
1525 * the PDP group directories
1528 public void changed() {
1529 // all PDPs in all groups need to be updated/sync'd
1530 Set<OnapPDPGroup> groups;
1532 groups = papEngine.getOnapPDPGroups();
1533 } catch (PAPException e) {
1534 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
1535 " getPDPGroups failed");
1536 throw new IllegalAccessError(
1537 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1539 for (OnapPDPGroup group : groups) {
1540 groupChanged(group);
1544 public void changed(ONAPLoggingContext loggingContext) {
1545 // all PDPs in all groups need to be updated/sync'd
1546 Set<OnapPDPGroup> groups;
1548 groups = papEngine.getOnapPDPGroups();
1549 } catch (PAPException e) {
1550 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
1551 " getPDPGroups failed");
1552 throw new IllegalAccessError(
1553 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
1555 for (OnapPDPGroup group : groups) {
1556 groupChanged(group, loggingContext);
1561 public void groupChanged(OnapPDPGroup group) {
1562 // all PDPs within one group need to be updated/sync'd
1563 for (OnapPDP pdp : group.getOnapPdps()) {
1564 pdpChanged(pdp, getPdpDataByGroup(group));
1568 public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
1569 // all PDPs within one group need to be updated/sync'd
1570 for (OnapPDP pdp : group.getOnapPdps()) {
1571 pdpChanged(pdp, loggingContext, getPdpDataByGroup(group));
1576 public void pdpChanged(OnapPDP pdp) {
1577 // kick off a thread to do an event notification for each PDP.
1578 // This needs to be on a separate thread so that PDPs that do not
1579 // respond (down, non-existent, etc)
1580 // do not block the PSP response to the AC, which would freeze the GUI
1581 // until all PDPs sequentially respond or time-out.
1582 Thread t = new Thread(new UpdatePdpThread(pdp, getPdpDataByPdpId(pdp)));
1583 if (CheckPDP.validateID(pdp.getId())) {
1588 public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
1589 // kick off a thread to do an event notification for each PDP.
1590 // This needs to be on a separate thread so that PDPs that do not
1591 // respond (down, non-existent, etc)
1592 // do not block the PSP response to the AC, which would freeze the GUI
1593 // until all PDPs sequentially respond or time-out.
1594 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, getPdpDataByPdpId(pdp)));
1595 if (CheckPDP.validateID(pdp.getId())) {
1600 private void pdpChanged(OnapPDP pdp, List<Properties> pdpDataByGroup) {
1601 Thread t = new Thread(new UpdatePdpThread(pdp, pdpDataByGroup));
1602 if (CheckPDP.validateID(pdp.getId())) {
1607 private void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext,
1608 List<Properties> pdpDataByGroup) {
1609 Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup));
1610 if (CheckPDP.validateID(pdp.getId())) {
1615 private List<Properties> getPdpDataByGroup(OnapPDPGroup group) {
1616 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1617 return dataToNotify.setPolicyConfigProperties(group);
1620 private List<Properties> getPdpDataByPdpId(OnapPDP pdp) {
1621 DataToNotifyPdp dataToNotify = new DataToNotifyPdp();
1622 return dataToNotify.setPolicyConfigProperties(pdp, papEngine);
1625 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response)
1626 throws IOException {
1627 LOGGER.info("Test request received");
1629 im.evaluateSanity();
1630 // If we make it this far, all is well
1631 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
1632 LOGGER.info(message);
1633 loggingContext.transactionEnded();
1634 PolicyLogger.audit("Transaction Failed - See Error.log");
1635 response.setStatus(HttpServletResponse.SC_OK);
1637 } catch (ForwardProgressException | AdministrativeStateException
1638 | StandbyStatusException e) {
1640 if (e instanceof ForwardProgressException) {
1641 submsg = " is not making forward progress.";
1642 } else if (e instanceof AdministrativeStateException) {
1643 submsg = " Administrative State is LOCKED.";
1645 submsg = " Standby Status is NOT PROVIDING SERVICE.";
1648 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
1649 + " Exception Message: " + e.getMessage();
1650 LOGGER.info(message, e);
1651 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1652 loggingContext.transactionEnded();
1653 PolicyLogger.audit("Transaction Failed - See Error.log");
1654 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1656 } catch (Exception e) {
1657 // A subsystem is not making progress, is locked, standby or is not
1659 String eMsg = e.getMessage();
1661 eMsg = "No Exception Message";
1663 String message = "GET:/pap/test called and PAP " + papResourceName
1664 + " has had a subsystem failure." + " Exception Message: " + eMsg;
1665 LOGGER.info(message, e);
1666 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1667 loggingContext.transactionEnded();
1668 PolicyLogger.audit("Transaction Failed - See Error.log");
1669 // Get the specific list of subsystems that failed
1670 String ssFailureList = null;
1671 for (String failedSS : papDependencyGroupsFlatArray) {
1672 if (eMsg.contains(failedSS)) {
1673 if (ssFailureList == null) {
1674 ssFailureList = failedSS;
1676 ssFailureList = ssFailureList.concat("," + failedSS);
1680 if (ssFailureList == null) {
1681 ssFailureList = "UnknownSubSystem";
1683 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
1684 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1689 private void setLoggingContext(ONAPLoggingContext loggingContext, String methodType,
1690 String serviceName) {
1691 loggingContext.transactionStarted();
1692 loggingContext.setServiceName(serviceName);
1693 if (loggingContext.getRequestID() == null || "".equals(loggingContext.getRequestID())) {
1694 UUID requestID = UUID.randomUUID();
1695 loggingContext.setRequestID(requestID.toString());
1696 PolicyLogger.info("requestID not provided in call to XACMLPapServlet ('" + methodType
1697 + "') so we generated one");
1700 "requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
1705 * Authorizing the PEP Requests.
1707 private boolean authorizeRequest(HttpServletRequest request) {
1708 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
1709 // Check if the Client is Authorized.
1710 return clientCredentials != null && clientCredentials.equalsIgnoreCase(environment);
1713 private static void loadWebapps() throws PAPException {
1714 if (actionHome == null || configHome == null) {
1716 Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
1718 if (webappsPath == null) {
1719 PolicyLogger.error("Invalid Webapps Path Location property : "
1720 + XACMLRestProperties.PROP_PAP_WEBAPPS);
1721 throw new PAPException("Invalid Webapps Path Location property : "
1722 + XACMLRestProperties.PROP_PAP_WEBAPPS);
1724 Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config");
1725 Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action");
1726 if (Files.notExists(webappsPathConfig)) {
1728 Files.createDirectories(webappsPathConfig);
1729 } catch (IOException e) {
1730 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1731 "Failed to create config directory: "
1732 + webappsPathConfig.toAbsolutePath().toString());
1735 if (Files.notExists(webappsPathAction)) {
1737 Files.createDirectories(webappsPathAction);
1738 } catch (IOException e) {
1739 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
1740 + "Failed to create action directory: "
1741 + webappsPathAction.toAbsolutePath().toString(), e);
1744 actionHome = webappsPathAction.toString();
1745 configHome = webappsPathConfig.toString();
1749 public static String getConfigHome() {
1752 } catch (PAPException e) {
1759 private static void setConfigHome() {
1760 configHome = getConfigHome();
1763 public static String getActionHome() {
1766 } catch (PAPException e) {
1773 private static void setActionHome() {
1774 actionHome = getActionHome();
1777 public IntegrityAudit getIa() {
1781 public static String getPDPFile() {
1782 return XACMLPapServlet.pdpFile;
1785 public static String getPersistenceUnit() {
1786 return PERSISTENCE_UNIT;
1789 public static PAPPolicyEngine getPAPEngine() {
1793 public static PolicyDBDaoTransaction getDbDaoTransaction() {
1794 return policyDbDao.getNewTransaction();
1797 public static String getPapDbDriver() {
1801 public static void setPapDbDriver(String papDbDriver) {
1802 XACMLPapServlet.papDbDriver = papDbDriver;
1805 public static String getPapDbUrl() {
1809 public static void setPapDbUrl(String papDbUrl) {
1810 XACMLPapServlet.papDbUrl = papDbUrl;
1813 public static String getPapDbUser() {
1817 public static void setPapDbUser(String papDbUser) {
1818 XACMLPapServlet.papDbUser = papDbUser;
1821 public static String getPapDbPassword() {
1825 public static void setPapDbPassword(String papDbPassword) {
1826 XACMLPapServlet.papDbPd = papDbPassword;
1829 public static String getMsOnapName() {
1833 public static void setMsOnapName(String msOnapName) {
1834 XACMLPapServlet.msOnapName = msOnapName;
1837 public static String getMsPolicyName() {
1838 return msPolicyName;
1841 public static void setMsPolicyName(String msPolicyName) {
1842 XACMLPapServlet.msPolicyName = msPolicyName;
1845 public ONAPLoggingContext getBaseLoggingContext() {
1846 return baseLoggingContext;
1849 public void setBaseLoggingContext(ONAPLoggingContext baseLoggingContext) {
1850 this.baseLoggingContext = baseLoggingContext;