2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.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.Iterator;
44 import java.util.List;
45 import java.util.Properties;
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.ServletOutputStream;
57 import javax.servlet.annotation.WebInitParam;
58 import javax.servlet.annotation.WebServlet;
59 import javax.servlet.http.HttpServlet;
60 import javax.servlet.http.HttpServletRequest;
61 import javax.servlet.http.HttpServletResponse;
63 import org.apache.commons.io.IOUtils;
64 import org.onap.policy.common.ia.IntegrityAudit;
65 import org.onap.policy.common.im.AdministrativeStateException;
66 import org.onap.policy.common.im.ForwardProgressException;
67 import org.onap.policy.common.im.IntegrityMonitor;
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.PolicyUtils;
86 import org.onap.policy.xacml.api.XACMLErrorConstants;
87 import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
88 import org.onap.policy.xacml.api.pap.OnapPDP;
89 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
90 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
91 import org.onap.policy.xacml.std.pap.StdPAPPolicy;
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";
127 * List of Admin Console URLs.
128 * Used to send notifications when configuration changes.
130 * The CopyOnWriteArrayList *should* protect from concurrency errors.
131 * This list is seldom changed but often read, so the costs of this approach make sense.
133 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
135 private static String configHome;
136 private static String actionHome;
138 * This PAP instance's own URL.
139 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
141 private static String papURL = null;
142 // The heartbeat thread.
143 private static Heartbeat heartbeat = null;
144 private static Thread heartbeatThread = null;
145 //The entity manager factory for JPA access
146 private static EntityManagerFactory emf;
147 private static PolicyDBDao policyDBDao;
149 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
151 private static PAPPolicyEngine papEngine = null;
153 * These are the parameters needed for DB access from the PAP
155 private static int papIntegrityAuditPeriodSeconds = -1;
156 private static String papDbDriver = null;
157 private static String papDbUrl = null;
158 private static String papDbUser = null;
159 private static String papDbPassword = null;
160 private static String papResourceName = null;
161 private static String[] papDependencyGroupsFlatArray = null;
162 private static String environment = null;
163 private static String pdpFile = null;
165 private transient IntegrityMonitor im;
166 private transient IntegrityAudit ia;
168 //MicroService Model Properties
169 private static String msOnapName;
170 private static String msPolicyName;
172 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
173 * this servlet starts. Its configurable by the admin.
175 private static transient Thread initiateThread = null;
176 private transient ONAPLoggingContext baseLoggingContext = null;
179 * @see HttpServlet#HttpServlet()
181 public XACMLPapServlet() {
186 * @see Servlet#init(ServletConfig)
188 public void init(ServletConfig config) throws ServletException {
191 baseLoggingContext = new ONAPLoggingContext();
192 // fixed data that will be the same in all logging output goes here
194 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
195 baseLoggingContext.setServer(hostname);
196 } catch (UnknownHostException e) {
197 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
200 XACMLRest.xacmlInit(config);
201 // Load the properties
202 XACMLRest.loadXacmlProperties(null, null);
204 * Retrieve the property values
206 setCommonProperties();
207 String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
208 if(papSiteName == null){
209 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
210 throw new PAPException("papSiteName is null");
212 String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
213 if(papNodeType == null){
214 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
215 throw new PAPException("papNodeType is null");
217 //Integer will throw an exception of anything is missing or unrecognized
218 int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
219 int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
220 int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
221 //Boolean will default to false if anything is missing or unrecognized
222 boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
223 boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
224 String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
225 if(papDependencyGroups == null){
226 throw new PAPException("papDependencyGroups is null");
228 setPAPDependencyGroups(papDependencyGroups);
229 //Integer will throw an exception of anything is missing or unrecognized
230 int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
231 int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
232 int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
233 int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
234 LOGGER.debug("\n\n\n**************************************"
235 + "\n*************************************"
237 + "\n papDbDriver = " + papDbDriver
238 + "\n papDbUrl = " + papDbUrl
239 + "\n papDbUser = " + papDbUser
240 + "\n papDbPassword = " + papDbPassword
241 + "\n papTransWait = " + papTransWait
242 + "\n papTransTimeout = " + papTransTimeout
243 + "\n papAuditTimeout = " + papAuditTimeout
244 + "\n papAuditFlag = " + papAuditFlag
245 + "\n papFileSystemAudit = " + papFileSystemAudit
246 + "\n papResourceName = " + papResourceName
247 + "\n fpMonitorInterval = " + fpMonitorInterval
248 + "\n failedCounterThreshold = " + failedCounterThreshold
249 + "\n testTransInterval = " + testTransInterval
250 + "\n writeFpcInterval = " + writeFpcInterval
251 + "\n papSiteName = " + papSiteName
252 + "\n papNodeType = " + papNodeType
253 + "\n papDependencyGroupsList = " + papDependencyGroups
254 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
255 + "\n\n*************************************"
256 + "\n**************************************");
257 // Pull custom persistence settings
258 Properties properties;
260 properties = XACMLProperties.getProperties();
261 LOGGER.debug("\n\n\n**************************************"
262 + "\n**************************************"
264 + "properties = " + properties
265 + "\n\n**************************************");
266 } catch (IOException e) {
267 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
268 + "XACMLProperties.getProperties()");
269 throw new ServletException(e.getMessage(), e.getCause());
271 // Create an IntegrityMonitor
272 im = IntegrityMonitor.getInstance(papResourceName,properties);
273 // Create an IntegrityAudit
274 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
275 ia.startAuditThread();
276 // Create the entity manager factory
278 // we are about to call the PDPs and give them their configuration.
279 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
280 setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
281 //Create the policyDBDao
283 // Load our PAP engine, first create a factory
284 ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
285 // The factory knows how to go about creating a PAP Engine
286 setPAPEngine((PAPPolicyEngine) factory.newEngine());
287 PolicyDBDaoTransaction addNewGroup = null;
288 if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
290 addNewGroup = policyDBDao.getNewTransaction();
291 OnapPDPGroup group = papEngine.getDefaultGroup();
292 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
293 "automaticallyAdded");
294 addNewGroup.commitTransaction();
295 addNewGroup = policyDBDao.getNewTransaction();
296 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
297 addNewGroup.commitTransaction();
298 } catch (Exception e) {
299 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
300 " Error creating new default group in the database");
301 if (addNewGroup != null) {
302 addNewGroup.rollbackTransaction();
306 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
307 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
308 //get an AuditTransaction to lock out all other transactions
309 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
310 policyDBDao.auditLocalDatabase(XACMLPapServlet.papEngine);
311 //release the transaction lock
315 // Sanity check for URL.
316 if (XACMLPapServlet.papURL == null) {
317 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
319 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
320 // to all its known PDP nodes.
321 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
322 startInitiateThreadService(new Thread(this));
324 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
325 startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));
327 } catch (FactoryException | PAPException e) {
328 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
329 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
330 } catch (Exception e) {
331 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
332 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
336 private static void startInitiateThreadService(Thread thread) {
337 initiateThread = thread;
338 initiateThread.start();
341 private static void mapperWriteValue(ObjectMapper mapper, ServletOutputStream out, Object value) {
343 mapper.writeValue(out, value);
344 } catch (Exception e) {
349 private static void startHeartBeatService(Heartbeat heartbeat) {
350 XACMLPapServlet.heartbeat = heartbeat;
351 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
352 XACMLPapServlet.heartbeatThread.start();
355 private static void setPolicyDBDao() throws ServletException {
357 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
358 } catch (Exception e) {
359 throw new ServletException("Unable to Create Policy DBDao Instance",e);
363 private static void setEMF(Properties properties) throws ServletException {
364 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
366 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
368 throw new ServletException("Unable to create Entity Manager Factory");
372 private static void setPAPURL(String papURL) {
373 XACMLPapServlet.papURL = papURL;
376 private static void setPAPEngine(PAPPolicyEngine newEngine) {
377 XACMLPapServlet.papEngine = newEngine;
380 private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
382 //Now we have flattened the array into a simple comma-separated list
383 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
384 //clean up the entries
385 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
386 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
389 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
390 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
393 String msg = "integrity_audit_period_seconds ";
394 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
395 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
399 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
400 throw new PAPException(e);
404 private static void setCommonProperties() throws PAPException {
407 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
408 if(papDbDriver == null){
409 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
410 throw new PAPException("papDbDriver is null");
412 setPapDbDriver(papDbDriver);
413 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
414 if(papDbUrl == null){
415 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
416 throw new PAPException("papDbUrl is null");
418 setPapDbUrl(papDbUrl);
419 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
420 if(papDbUser == null){
421 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
422 throw new PAPException("papDbUser is null");
424 setPapDbUser(papDbUser);
425 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
426 if(papDbPassword == null){
427 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
428 throw new PAPException("papDbPassword is null");
430 setPapDbPassword(papDbPassword);
431 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
432 if(papResourceName == null){
433 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
434 throw new PAPException("papResourceName is null");
436 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
437 //Micro Service Properties
438 msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
439 setMsOnapName(msOnapName);
440 msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
441 setMsPolicyName(msPolicyName);
442 // PDPId File location
443 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
444 if (XACMLPapServlet.pdpFile == null) {
445 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
446 + XACMLRestProperties.PROP_PDP_IDFILE);
447 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
452 * Thread used only during PAP startup to initiate change messages to all known PDPs.
453 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
457 // send the current configuration to all the PDPs that we know about
462 * @see Servlet#destroy()
464 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
465 * For now we assume that we do care.
468 public void destroy() {
469 // Make sure our threads are destroyed
470 if (XACMLPapServlet.heartbeatThread != null) {
471 // stop the heartbeat
473 if (XACMLPapServlet.heartbeat != null) {
474 XACMLPapServlet.heartbeat.terminate();
476 XACMLPapServlet.heartbeatThread.interrupt();
477 XACMLPapServlet.heartbeatThread.join();
478 } catch (InterruptedException e) {
479 XACMLPapServlet.heartbeatThread.interrupt();
480 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
483 if (initiateThread != null) {
485 initiateThread.interrupt();
486 initiateThread.join();
487 } catch (InterruptedException e) {
488 initiateThread.interrupt();
489 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
496 * - PDP nodes to register themselves with the PAP, and
497 * - Admin Console to make changes in the PDP Groups.
499 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
501 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
502 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
503 loggingContext.transactionStarted();
504 loggingContext.setServiceName("PAP.post");
505 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
506 UUID requestID = UUID.randomUUID();
507 loggingContext.setRequestID(requestID.toString());
508 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
510 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
512 PolicyDBDaoTransaction pdpTransaction = null;
514 im.startTransaction();
515 } catch (AdministrativeStateException ae){
516 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
517 + " state of " + im.getStateManager().getAdminState()
518 + "\n Exception Message: " + ae.getMessage();
519 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
520 loggingContext.transactionEnded();
521 PolicyLogger.audit("Transaction Failed - See Error.log");
522 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
524 }catch (StandbyStatusException se) {
525 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
526 + " of " + im.getStateManager().getStandbyStatus()
527 + "\n Exception Message: " + se.getMessage();
528 LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
529 loggingContext.transactionEnded();
530 PolicyLogger.audit("Transaction Failed - See Error.log");
531 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
535 XACMLRest.dumpRequest(request);
536 // since getParameter reads the content string, explicitly get the content before doing that.
537 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
538 request.getInputStream();
539 String groupId = request.getParameter("groupId");
540 String apiflag = request.getParameter("apiflag");
541 if(groupId != null) {
542 // Is this from the Admin Console or API?
543 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
544 // this is from the API so we need to check the client credentials before processing the request
545 if(!authorizeRequest(request)){
546 String message = "PEP not Authorized for making this Request!!";
547 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
548 loggingContext.transactionEnded();
549 PolicyLogger.audit("Transaction Failed - See Error.log");
550 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
555 doACPost(request, response, groupId, loggingContext);
556 loggingContext.transactionEnded();
557 PolicyLogger.audit("Transaction Ended Successfully");
561 // Request is from a PDP asking for its config.
562 loggingContext.setServiceName("PDP:PAP.register");
564 String id = this.getPDPID(request);
565 String jmxport = this.getPDPJMX(request);
566 LOGGER.info("Request(doPost) from PDP coming up: " + id);
567 // Get the PDP Object
568 OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
571 LOGGER.info("Unknown PDP: " + id);
573 if(CheckPDP.validateID(id)){
574 pdpTransaction = policyDBDao.getNewTransaction();
576 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
577 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
578 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException e) {
579 pdpTransaction.rollbackTransaction();
580 String message = "Failed to create new PDP for id: " + id;
581 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
582 loggingContext.transactionEnded();
583 PolicyLogger.audit("Transaction Failed - See Error.log");
584 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
588 // get the PDP we just created
590 pdp = XACMLPapServlet.papEngine.getPDP(id);
591 }catch(PAPException e){
595 if(pdpTransaction != null){
596 pdpTransaction.rollbackTransaction();
598 String message = "Failed to create new PDP for id: " + id;
599 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
600 loggingContext.transactionEnded();
601 PolicyLogger.audit("Transaction Failed - See Error.log");
602 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
607 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
608 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
609 loggingContext.transactionEnded();
610 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
611 PolicyLogger.audit("Transaction Failed - See Error.log");
616 pdpTransaction.commitTransaction();
617 } catch(Exception e){
618 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
621 if (jmxport != null && jmxport != ""){
623 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
624 }catch(NumberFormatException e){
628 // Get the PDP's Group
629 OnapPDPGroup group =null;
631 group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
632 }catch(PAPException e){
636 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
637 loggingContext.transactionEnded();
638 PolicyLogger.audit("Transaction Failed - See Error.log");
639 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
643 // Determine what group the PDP node is in and get
644 // its policy/pip properties.
645 Properties policies = group.getPolicyProperties();
646 Properties pipconfig = group.getPipConfigProperties();
647 // Get the current policy/pip configuration that the PDP has
648 Properties pdpProperties = new Properties();
650 pdpProperties.load(request.getInputStream());
651 }catch(IOException e){
654 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
655 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
656 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
657 // Validate the node's properties
658 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
659 // Send back current configuration
660 if (isCurrent == false) {
661 // Tell the PDP we are sending back the current policies/pip config
662 LOGGER.info("PDP configuration NOT current.");
663 if (policies != null) {
664 // Put URL's into the properties in case the PDP needs to
666 this.populatePolicyURL(request.getRequestURL(), policies);
667 // Copy the properties to the output stream
669 policies.store(response.getOutputStream(), "");
670 }catch(IOException e){
674 if (pipconfig != null) {
675 // Copy the properties to the output stream
677 pipconfig.store(response.getOutputStream(), "");
678 }catch(IOException e){
682 // We are good - and we are sending them information
683 response.setStatus(HttpServletResponse.SC_OK);
685 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
686 }catch(PAPException e){
690 // Tell them they are good
691 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
693 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
694 }catch(PAPException e){
698 // tell the AC that something changed
700 loggingContext.transactionEnded();
701 auditLogger.info("Success");
702 PolicyLogger.audit("Transaction Ended Successfully");
703 } catch (PAPException | IOException | NumberFormatException e) {
704 if(pdpTransaction != null){
705 pdpTransaction.rollbackTransaction();
707 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
708 loggingContext.transactionEnded();
709 PolicyLogger.audit("Transaction Failed - See Error.log");
710 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
714 //Catch anything that fell through
715 loggingContext.transactionEnded();
716 PolicyLogger.audit("Transaction Ended");
720 private void setResponseError(HttpServletResponse response,int responseCode, String message) {
722 response.sendError(responseCode, message);
723 } catch (IOException e) {
724 LOGGER.error("Error setting Error response Header ", e);
730 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
732 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
733 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
734 loggingContext.transactionStarted();
735 loggingContext.setServiceName("PAP.get");
736 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
737 UUID requestID = UUID.randomUUID();
738 loggingContext.setRequestID(requestID.toString());
739 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
741 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
744 XACMLRest.dumpRequest(request);
745 String pathInfo = request.getRequestURI();
746 LOGGER.info("path info: " + pathInfo);
747 if (pathInfo != null){
748 //DO NOT do a im.startTransaction for the test request
749 if (pathInfo.equals("/pap/test")) {
751 testService(loggingContext, response);
752 } catch (IOException e) {
758 //This im.startTransaction() covers all other Get transactions
760 im.startTransaction();
761 } catch (AdministrativeStateException ae){
762 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
763 + " state of " + im.getStateManager().getAdminState()
764 + "\n Exception Message: " + ae.getMessage();
765 LOGGER.info(message, ae);
766 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
767 loggingContext.transactionEnded();
768 PolicyLogger.audit("Transaction Failed - See Error.log");
769 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
771 }catch (StandbyStatusException se) {
772 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
773 + " of " + im.getStateManager().getStandbyStatus()
774 + "\n Exception Message: " + se.getMessage();
775 LOGGER.info(message, se);
776 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
777 loggingContext.transactionEnded();
778 PolicyLogger.audit("Transaction Failed - See Error.log");
779 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
782 // Request from the API to get the gitPath
783 String apiflag = request.getParameter("apiflag");
785 if(authorizeRequest(request)){
786 APIRequestHandler apiRequestHandler = new APIRequestHandler();
787 apiRequestHandler.doGet(request,response, apiflag);
788 loggingContext.transactionEnded();
789 PolicyLogger.audit("Transaction Ended Successfully");
793 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
794 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
795 loggingContext.transactionEnded();
796 PolicyLogger.audit("Transaction Failed - See Error.log");
797 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
802 // Is this from the Admin Console?
803 String groupId = request.getParameter("groupId");
804 if (groupId != null) {
805 // this is from the Admin Console, so handle separately
806 doACGet(request, response, groupId, loggingContext);
807 loggingContext.transactionEnded();
808 PolicyLogger.audit("Transaction Ended Successfully");
813 String id = this.getPDPID(request);
814 LOGGER.info("doGet from: " + id);
815 // Get the PDP Object
818 pdp = XACMLPapServlet.papEngine.getPDP(id);
819 }catch(PAPException e){
824 // Check if request came from localhost
825 if (request.getRemoteHost().equals("localhost") ||
826 request.getRemoteHost().equals(request.getLocalAddr())) {
827 // Return status information - basically all the groups
828 loggingContext.setServiceName("PAP.getGroups");
829 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
830 // convert response object to JSON and include in the response
831 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), groups);
832 response.setHeader("content-type", "application/json");
833 response.setStatus(HttpServletResponse.SC_OK);
834 loggingContext.transactionEnded();
835 PolicyLogger.audit("Transaction Ended Successfully");
839 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
840 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
841 loggingContext.transactionEnded();
842 PolicyLogger.audit("Transaction Failed - See Error.log");
843 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
847 loggingContext.setServiceName("PAP.getPolicy");
848 // Get the PDP's Group
849 OnapPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
851 String message = "No group associated with pdp " + pdp.getId();
852 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
853 loggingContext.transactionEnded();
854 PolicyLogger.audit("Transaction Failed - See Error.log");
855 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
859 // Which policy do they want?
860 String policyId = request.getParameter("id");
861 if (policyId == null) {
862 String message = "Did not specify an id for the policy";
863 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
864 loggingContext.transactionEnded();
865 PolicyLogger.audit("Transaction Failed - See Error.log");
866 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
870 PDPPolicy policy = group.getPolicy(policyId);
871 if (policy == null) {
872 String message = "Unknown policy: " + policyId;
873 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
874 loggingContext.transactionEnded();
875 PolicyLogger.audit("Transaction Failed - See Error.log");
876 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
880 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
881 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
882 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
883 // Send the policy back
884 IOUtils.copy(is, os);
885 response.setStatus(HttpServletResponse.SC_OK);
886 loggingContext.transactionEnded();
887 auditLogger.info("Success");
888 PolicyLogger.audit("Transaction Ended Successfully");
889 } catch (IOException e) {
890 String message = "Failed to open policy id " + policyId;
892 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
893 loggingContext.transactionEnded();
894 PolicyLogger.audit("Transaction Failed - See Error.log");
895 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
897 } catch (PAPException | IOException e) {
899 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
900 loggingContext.transactionEnded();
901 PolicyLogger.audit("Transaction Failed - See Error.log");
902 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
906 loggingContext.transactionEnded();
907 PolicyLogger.audit("Transaction Ended");
912 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
914 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
915 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
916 loggingContext.transactionStarted();
917 loggingContext.setServiceName("PAP.put");
918 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
919 UUID requestID = UUID.randomUUID();
920 loggingContext.setRequestID(requestID.toString());
921 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
923 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
926 im.startTransaction();
927 } catch (AdministrativeStateException | StandbyStatusException e) {
928 String message = "PUT interface called for PAP " + papResourceName;
929 if (e instanceof AdministrativeStateException) {
930 message += " but it has an Administrative state of "
931 + im.getStateManager().getAdminState();
932 } else if (e instanceof StandbyStatusException) {
933 message += " but it has a Standby Status of "
934 + im.getStateManager().getStandbyStatus();
937 message += "\n Exception Message: " + e.getMessage();
939 LOGGER.info(message, e);
940 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
941 loggingContext.transactionEnded();
942 PolicyLogger.audit("Transaction Failed - See Error.log");
943 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
947 XACMLRest.dumpRequest(request);
948 //need to check if request is from the API or Admin console
949 String apiflag = request.getParameter("apiflag");
950 //This would occur if a PolicyDBDao notification was received
951 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
952 if(policyDBDaoRequestUrl != null){
953 String policyDBDaoRequestEntityId = request.getParameter("entityid");
954 //String policyDBDaoRequestEntityType = request.getParameter("entitytype");
955 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
956 String policyDBDaoRequestExtraData = request.getParameter("extradata");
957 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
958 setResponseError(response,400, "entityid or entitytype not supplied");
959 loggingContext.transactionEnded();
960 PolicyLogger.audit("Transaction Ended Successfully");
964 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
965 response.setStatus(200);
966 loggingContext.transactionEnded();
967 PolicyLogger.audit("Transaction Ended Successfully");
972 * Request for ImportService
974 String importService = request.getParameter("importService");
975 if (importService != null) {
976 if(authorizeRequest(request)){
977 APIRequestHandler apiRequestHandler = new APIRequestHandler();
978 apiRequestHandler.doPut(request, response, importService);
982 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
983 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
984 loggingContext.transactionEnded();
985 PolicyLogger.audit("Transaction Failed - See Error.log");
986 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
990 //This would occur if we received a notification of a policy rename from AC
991 String oldPolicyName = request.getParameter("oldPolicyName");
992 String newPolicyName = request.getParameter("newPolicyName");
993 if(oldPolicyName != null && newPolicyName != null){
994 if(LOGGER.isDebugEnabled()){
995 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
996 + "\npolicyToCreateUpdate = " + " ");
1000 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
1001 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
1002 if(LOGGER.isDebugEnabled()){
1003 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
1004 + "\npolicyToCreateUpdate = " + " ");
1006 } catch(UnsupportedEncodingException e){
1007 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1008 + "\npolicyToCreateUpdate = " + " ");
1009 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToCreateUpdate encoding not supported"
1010 + "\nfailure with the following exception: " + e);
1011 loggingContext.transactionEnded();
1012 PolicyLogger.audit("Transaction Failed - See error.log");
1013 im.endTransaction();
1016 //send it to PolicyDBDao
1017 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1019 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1020 }catch(Exception e){
1021 renameTransaction.rollbackTransaction();
1022 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1023 + "\nfailure with the following exception: " + e);
1024 loggingContext.transactionEnded();
1025 PolicyLogger.audit("Transaction Failed - See error.log");
1026 im.endTransaction();
1029 renameTransaction.commitTransaction();
1030 response.setStatus(HttpServletResponse.SC_OK);
1031 loggingContext.transactionEnded();
1032 PolicyLogger.audit("Transaction Ended Successfully");
1033 im.endTransaction();
1037 // See if this is Admin Console registering itself with us
1039 String acURLString = request.getParameter("adminConsoleURL");
1040 if (acURLString != null) {
1041 loggingContext.setServiceName("AC:PAP.register");
1042 // remember this Admin Console for future updates
1043 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1044 adminConsoleURLStringList.add(acURLString);
1046 if (LOGGER.isDebugEnabled()) {
1047 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1049 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1050 loggingContext.transactionEnded();
1051 auditLogger.info("Success");
1052 PolicyLogger.audit("Transaction Ended Successfully");
1053 im.endTransaction();
1057 * This is to update the PDP Group with the policy/policies being pushed
1058 * Part of a 2 step process to push policies to the PDP that can now be done
1059 * From both the Admin Console and the PolicyEngine API
1061 String groupId = request.getParameter("groupId");
1062 if (groupId != null) {
1064 if(!authorizeRequest(request)){
1065 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1066 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1067 loggingContext.transactionEnded();
1068 PolicyLogger.audit("Transaction Failed - See Error.log");
1069 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1072 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1073 updateGroupsFromAPI(request, response, groupId, loggingContext);
1074 loggingContext.transactionEnded();
1075 PolicyLogger.audit("Transaction Ended Successfully");
1076 im.endTransaction();
1080 // this is from the Admin Console, so handle separately
1081 doACPut(request, response, groupId, loggingContext);
1082 loggingContext.transactionEnded();
1083 PolicyLogger.audit("Transaction Ended Successfully");
1084 im.endTransaction();
1088 // Request is for policy validation and creation
1090 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1091 // this request is from the Admin Console
1092 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1093 savePolicyHandler.doPolicyAPIPut(request, response);
1094 loggingContext.transactionEnded();
1095 PolicyLogger.audit("Transaction Ended Successfully");
1096 im.endTransaction();
1098 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1099 // this request is from the Policy Creation API
1100 if(authorizeRequest(request)){
1101 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1102 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1103 loggingContext.transactionEnded();
1104 PolicyLogger.audit("Transaction Ended Successfully");
1105 im.endTransaction();
1108 String message = "PEP not Authorized for making this Request!!";
1109 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1110 loggingContext.transactionEnded();
1111 PolicyLogger.audit("Transaction Failed - See Error.log");
1112 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1113 im.endTransaction();
1117 // We do not expect anything from anywhere else.
1118 // This method is here in case we ever need to support other operations.
1119 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1120 loggingContext.transactionEnded();
1121 PolicyLogger.audit("Transaction Failed - See Error.log");
1122 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1123 loggingContext.transactionEnded();
1124 PolicyLogger.audit("Transaction Failed - See error.log");
1125 im.endTransaction();
1129 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1131 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1132 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1133 loggingContext.transactionStarted();
1134 loggingContext.setServiceName("PAP.delete");
1135 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1136 UUID requestID = UUID.randomUUID();
1137 loggingContext.setRequestID(requestID.toString());
1138 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1140 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1143 im.startTransaction();
1144 } catch (AdministrativeStateException ae){
1145 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1146 + " state of " + im.getStateManager().getAdminState()
1147 + "\n Exception Message: " + ae.getMessage();
1148 LOGGER.info(message, ae);
1149 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1150 loggingContext.transactionEnded();
1151 PolicyLogger.audit("Transaction Failed - See Error.log");
1152 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1154 }catch (StandbyStatusException se) {
1155 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1156 + " of " + im.getStateManager().getStandbyStatus()
1157 + "\n Exception Message: " + se.getMessage();
1158 LOGGER.info(message, se);
1159 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1160 loggingContext.transactionEnded();
1161 PolicyLogger.audit("Transaction Failed - See Error.log");
1162 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1165 XACMLRest.dumpRequest(request);
1166 String groupId = request.getParameter("groupId");
1167 String apiflag = request.getParameter("apiflag");
1168 if (groupId != null) {
1169 // Is this from the Admin Console or API?
1171 if(!authorizeRequest(request)){
1172 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1173 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1174 loggingContext.transactionEnded();
1175 PolicyLogger.audit("Transaction Failed - See Error.log");
1176 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1179 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1181 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1182 } catch (Exception e) {
1183 LOGGER.error("Exception Occured"+e);
1185 if(apiRequestHandler.getNewGroup()!=null){
1186 groupChanged(apiRequestHandler.getNewGroup());
1190 // this is from the Admin Console, so handle separately
1191 doACDelete(request, response, groupId, loggingContext);
1192 loggingContext.transactionEnded();
1193 PolicyLogger.audit("Transaction Ended Successfully");
1194 im.endTransaction();
1197 //Catch anything that fell through
1198 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1199 loggingContext.transactionEnded();
1200 PolicyLogger.audit("Transaction Failed - See Error.log");
1201 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1202 im.endTransaction();
1205 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1206 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1207 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1208 if (localRootPolicies == null || localReferencedPolicies == null) {
1209 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1212 // Compare the policies and pipconfig properties to the pdpProperties
1214 // the policy properties includes only xacml.rootPolicies and
1215 // xacml.referencedPolicies without any .url entries
1216 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1217 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1218 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1219 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1220 pdpPipConfig.equals(pipconfig)) {
1221 // The PDP is current
1224 } catch (Exception e) {
1225 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1226 // or if there are policies that do not have a corresponding ".url" property.
1227 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1228 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1233 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1234 String lists[] = new String[2];
1235 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1236 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1237 for (String list : lists) {
1238 if (list != null && list.isEmpty() == false) {
1239 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1240 String url = urlPath + "?id=" + id;
1241 LOGGER.info("Policy URL for " + id + ": " + url);
1242 policies.setProperty(id + ".url", url);
1248 protected String getPDPID(HttpServletRequest request) {
1249 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1250 if (pdpURL == null || pdpURL.isEmpty()) {
1251 // Should send back its port for identification
1252 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1258 protected String getPDPJMX(HttpServletRequest request) {
1259 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1260 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1261 // Should send back its port for identification
1262 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1269 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1274 * @param loggingContext
1275 * @throws ServletException
1276 * @throws IOException
1278 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1279 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1281 // for PUT operations the group may or may not need to exist before the operation can be done
1282 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1283 // get the request input stream content into a String
1285 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1286 scanner.useDelimiter("\\A");
1287 json = scanner.hasNext() ? scanner.next() : "";
1289 PolicyLogger.info("JSON request from PolicyEngine API: " + json);
1290 // convert Object sent as JSON into local object
1291 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1292 Set<PDPPolicy> policies = new HashSet<>();
1294 policies.add(policy);
1296 //Get the current policies from the Group and Add the new one
1297 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1298 currentPoliciesInGroup = group.getPolicies();
1299 //If the selected policy is in the group we must remove it because the name is default
1300 Iterator<PDPPolicy> policyIterator = policies.iterator();
1301 LOGGER.debug("policyIterator....." + policies);
1302 while (policyIterator.hasNext()) {
1303 PDPPolicy selPolicy = policyIterator.next();
1304 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
1305 if (existingPolicy.getId().equals(selPolicy.getId())) {
1306 group.removePolicyFromGroup(existingPolicy);
1307 LOGGER.debug("Removing policy: " + existingPolicy);
1312 //Update the PDP Group after removing old version of policy
1313 Set<PDPPolicy> updatedPoliciesInGroup = new HashSet<>();
1314 updatedPoliciesInGroup = group.getPolicies();
1315 //need to remove the policy with default name from group
1316 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
1317 if (updatedPolicy.getName().equalsIgnoreCase("default")) {
1318 group.removePolicyFromGroup(updatedPolicy);
1322 if(updatedPoliciesInGroup!=null){
1323 policies.addAll(updatedPoliciesInGroup);
1325 group.setPolicies(policies);
1326 // Assume that this is an update of an existing PDP Group
1327 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1329 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1330 } catch(Exception e){
1331 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1332 +"group="+group.getId());
1333 throw new PAPException(e.getMessage());
1335 papEngine.updateGroup(group);
1336 String policyId = "empty";
1338 policyId = policy.getId();
1340 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1341 response.addHeader("operation", "push");
1342 response.addHeader("policyId", policyId);
1343 response.addHeader("groupId", groupId);
1344 if (LOGGER.isDebugEnabled()) {
1345 LOGGER.debug("Group '" + group.getId() + "' updated");
1347 acPutTransaction.commitTransaction();
1349 // Group changed, which might include changing the policies
1350 groupChanged(group);
1351 loggingContext.transactionEnded();
1352 auditLogger.info("Success");
1354 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1355 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1356 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1357 LOGGER.debug("Precheck Successful.");
1361 PolicyLogger.audit("Transaction Ended Successfully");
1363 } catch (PAPException e) {
1364 acPutTransaction.rollbackTransaction();
1365 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1366 loggingContext.transactionEnded();
1367 PolicyLogger.audit("Transaction Failed - See Error.log");
1368 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1369 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1370 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1371 response.addHeader("error","addGroupError");
1372 response.addHeader("message", message);
1378 * Requests from the Admin Console for operations not on single specific objects
1383 * @param loggingContext
1384 * @throws ServletException
1385 * @throws IOException
1387 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1388 PolicyDBDaoTransaction doACPostTransaction = null;
1390 String groupName = request.getParameter("groupName");
1391 String groupDescription = request.getParameter("groupDescription");
1392 String apiflag = request.getParameter("apiflag");
1393 if (groupName != null && groupDescription != null) {
1394 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1395 loggingContext.setServiceName("AC:PAP.createGroup");
1396 String unescapedName = URLDecoder.decode(groupName, "UTF-8");
1397 String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1398 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1400 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1401 papEngine.newGroup(unescapedName, unescapedDescription);
1402 newGroupTransaction.commitTransaction();
1403 } catch (Exception e) {
1404 newGroupTransaction.rollbackTransaction();
1405 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1406 loggingContext.transactionEnded();
1408 PolicyLogger.audit("Transaction Failed - See Error.log");
1409 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1412 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1413 if (LOGGER.isDebugEnabled()) {
1414 LOGGER.debug("New Group '" + groupId + "' created");
1416 // tell the Admin Consoles there is a change
1418 // new group by definition has no PDPs, so no need to notify them of changes
1419 loggingContext.transactionEnded();
1420 PolicyLogger.audit("Transaction Failed - See Error.log");
1421 auditLogger.info("Success");
1422 PolicyLogger.audit("Transaction Ended Successfully");
1425 // for all remaining POST operations the group must exist before the operation can be done
1426 OnapPDPGroup group = papEngine.getGroup(groupId);
1427 if (group == null) {
1428 String message = "Unknown groupId '" + groupId + "'";
1429 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1430 loggingContext.transactionEnded();
1431 PolicyLogger.audit("Transaction Failed - See Error.log");
1433 response.addHeader("error", "unknownGroupId");
1434 response.addHeader("operation", "push");
1435 response.addHeader("message", message);
1436 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1438 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1442 // determine the operation needed based on the parameters in the request
1443 if (request.getParameter("policyId") != null) {
1444 // Args: group=<groupId> policy=<policyId> <= copy file
1445 // copy a policy from the request contents into a file in the group's directory on this machine
1447 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1449 loggingContext.setServiceName("AC:PAP.postPolicy");
1451 String policyId = request.getParameter("policyId");
1452 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1454 InputStream is = null;
1456 if (apiflag != null){
1457 // get the request content into a String if the request is from API
1459 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1460 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1461 scanner.useDelimiter("\\A");
1462 json = scanner.hasNext() ? scanner.next() : "";
1464 LOGGER.info("JSON request from API: " + json);
1465 // convert Object sent as JSON into local object
1466 ObjectMapper mapper = new ObjectMapper();
1467 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
1468 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
1469 temp = new File(policy.getLocation());
1470 is = new FileInputStream(temp);
1472 is = request.getInputStream();
1474 addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1475 if (apiflag != null){
1476 ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is);
1479 if (policyId.endsWith(".xml")) {
1480 name = policyId.replace(".xml", "");
1481 name = name.substring(0, name.lastIndexOf("."));
1483 ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is);
1485 if(is!=null && temp!=null){
1489 addPolicyToGroupTransaction.commitTransaction();
1490 } catch (Exception e) {
1491 addPolicyToGroupTransaction.rollbackTransaction();
1492 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1493 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1494 loggingContext.transactionEnded();
1495 PolicyLogger.audit("Transaction Failed - See Error.log");
1497 response.addHeader("error", "policyCopyError");
1498 response.addHeader("message", message);
1499 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1501 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1505 // policy file copied ok and the Group was updated on the PDP
1506 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1507 response.addHeader("operation", "push");
1508 response.addHeader("policyId", policyId);
1509 response.addHeader("groupId", groupId);
1510 if (LOGGER.isDebugEnabled()) {
1511 LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1513 loggingContext.transactionEnded();
1514 auditLogger.info("Success");
1515 PolicyLogger.audit("Transaction Ended Successfully");
1517 } else if (request.getParameter("default") != null) {
1518 // Args: group=<groupId> default=true <= make default
1519 // change the current default group to be the one identified in the request.
1520 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1521 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1522 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1523 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1525 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1526 papEngine.SetDefaultGroup(group);
1527 setDefaultGroupTransaction.commitTransaction();
1528 } catch (Exception e) {
1529 setDefaultGroupTransaction.rollbackTransaction();
1530 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1531 loggingContext.transactionEnded();
1533 PolicyLogger.audit("Transaction Failed - See Error.log");
1534 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1537 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1538 if (LOGGER.isDebugEnabled()) {
1539 LOGGER.debug("Group '" + groupId + "' set to be default");
1541 // Notify the Admin Consoles that something changed
1542 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1543 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1545 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1546 loggingContext.transactionEnded();
1547 auditLogger.info("Success");
1548 PolicyLogger.audit("Transaction Ended Successfully");
1550 } else if (request.getParameter("pdpId") != null) {
1551 doACPostTransaction = policyDBDao.getNewTransaction();
1552 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1553 loggingContext.setServiceName("AC:PAP.movePDP");
1554 String pdpId = request.getParameter("pdpId");
1555 OnapPDP pdp = papEngine.getPDP(pdpId);
1556 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1558 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1559 }catch(Exception e){
1560 doACPostTransaction.rollbackTransaction();
1561 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1562 " Error while moving pdp in the database: "
1563 +"pdp="+pdp.getId()+",to group="+group.getId());
1564 throw new PAPException(e.getMessage());
1566 papEngine.movePDP((OnapPDP) pdp, group);
1567 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1568 if (LOGGER.isDebugEnabled()) {
1569 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1571 // update the status of both the original group and the new one
1572 ((StdPDPGroup)originalGroup).resetStatus();
1573 ((StdPDPGroup)group).resetStatus();
1574 // Notify the Admin Consoles that something changed
1575 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1577 // Need to notify the PDP that it's config may have changed
1579 doACPostTransaction.commitTransaction();
1580 loggingContext.transactionEnded();
1581 auditLogger.info("Success");
1582 PolicyLogger.audit("Transaction Ended Successfully");
1585 } catch (PAPException e) {
1586 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1587 loggingContext.transactionEnded();
1588 PolicyLogger.audit("Transaction Failed - See Error.log");
1589 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1595 * Requests from the Admin Console to GET info about the Groups and PDPs
1600 * @param loggingContext
1601 * @throws ServletException
1602 * @throws IOException
1604 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1606 String parameterDefault = request.getParameter("default");
1607 String pdpId = request.getParameter("pdpId");
1608 String pdpGroup = request.getParameter("getPDPGroup");
1609 if ("".equals(groupId)) {
1610 // request IS from AC but does not identify a group by name
1611 if (parameterDefault != null) {
1612 // Request is for the Default group (whatever its id)
1613 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1614 OnapPDPGroup group = papEngine.getDefaultGroup();
1615 // convert response object to JSON and include in the response
1616 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), group);
1617 if (LOGGER.isDebugEnabled()) {
1618 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1620 response.setStatus(HttpServletResponse.SC_OK);
1621 response.setHeader("content-type", "application/json");
1622 response.getOutputStream().close();
1623 loggingContext.transactionEnded();
1624 auditLogger.info("Success");
1625 PolicyLogger.audit("Transaction Ended Successfully");
1627 } else if (pdpId != null) {
1628 // Request is related to a PDP
1629 if (pdpGroup == null) {
1630 // Request is for the (unspecified) group containing a given PDP
1631 loggingContext.setServiceName("AC:PAP.getPDP");
1632 OnapPDP pdp = papEngine.getPDP(pdpId);
1633 // convert response object to JSON and include in the response
1634 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), pdp);
1635 if (LOGGER.isDebugEnabled()) {
1636 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1638 response.setStatus(HttpServletResponse.SC_OK);
1639 response.setHeader("content-type", "application/json");
1640 response.getOutputStream().close();
1641 loggingContext.transactionEnded();
1642 auditLogger.info("Success");
1643 PolicyLogger.audit("Transaction Ended Successfully");
1646 // Request is for the group containing a given PDP
1647 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1648 OnapPDP pdp = papEngine.getPDP(pdpId);
1649 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
1650 // convert response object to JSON and include in the response
1651 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), group);
1652 if (LOGGER.isDebugEnabled()) {
1653 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1655 response.setStatus(HttpServletResponse.SC_OK);
1656 response.setHeader("content-type", "application/json");
1657 response.getOutputStream().close();
1658 loggingContext.transactionEnded();
1659 auditLogger.info("Success");
1660 PolicyLogger.audit("Transaction Ended Successfully");
1664 // request is for top-level properties about all groups
1665 loggingContext.setServiceName("AC:PAP.getAllGroups");
1666 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
1667 // convert response object to JSON and include in the response
1668 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), groups);
1669 if (LOGGER.isDebugEnabled()) {
1670 LOGGER.debug("GET All groups req");
1672 response.setStatus(HttpServletResponse.SC_OK);
1673 response.setHeader("content-type", "application/json");
1674 response.getOutputStream().close();
1675 loggingContext.transactionEnded();
1676 auditLogger.info("Success");
1677 PolicyLogger.audit("Transaction Ended Successfully");
1681 // for all other GET operations the group must exist before the operation can be done
1682 OnapPDPGroup group = papEngine.getGroup(groupId);
1683 if (group == null) {
1684 String message = "Unknown groupId '" + groupId + "'";
1685 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1686 loggingContext.transactionEnded();
1688 PolicyLogger.audit("Transaction Failed - See Error.log");
1689 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1692 // Figure out which request this is based on the parameters
1693 String policyId = request.getParameter("policyId");
1694 if (policyId != null) {
1695 // retrieve a policy
1696 loggingContext.setServiceName("AC:PAP.getPolicy");
1697 // convert response object to JSON and include in the response
1698 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1699 loggingContext.transactionEnded();
1700 PolicyLogger.audit("Transaction Failed - See Error.log");
1701 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1703 // No other parameters, so return the identified Group
1704 loggingContext.setServiceName("AC:PAP.getGroup");
1705 // convert response object to JSON and include in the response
1706 mapperWriteValue(new ObjectMapper(), response.getOutputStream(), group);
1707 if (LOGGER.isDebugEnabled()) {
1708 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1710 response.setStatus(HttpServletResponse.SC_OK);
1711 response.setHeader("content-type", "application/json");
1712 response.getOutputStream().close();
1713 loggingContext.transactionEnded();
1714 auditLogger.info("Success");
1715 PolicyLogger.audit("Transaction Ended Successfully");
1718 // Currently there are no other GET calls from the AC.
1719 // 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.
1720 // Other GETs that could be called:
1721 // Specific Group (groupId=<groupId>)
1722 // A Policy (groupId=<groupId> policyId=<policyId>)
1723 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1724 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1725 loggingContext.transactionEnded();
1726 PolicyLogger.audit("Transaction Failed - See Error.log");
1727 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1728 } catch (PAPException e) {
1729 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1730 loggingContext.transactionEnded();
1731 PolicyLogger.audit("Transaction Failed - See Error.log");
1732 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1738 * Requests from the Admin Console to create new items or update existing ones
1743 * @param loggingContext
1744 * @throws ServletException
1745 * @throws IOException
1747 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1748 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1750 // for PUT operations the group may or may not need to exist before the operation can be done
1751 OnapPDPGroup group = papEngine.getGroup(groupId);
1752 // determine the operation needed based on the parameters in the request
1753 // for remaining operations the group must exist before the operation can be done
1754 if (group == null) {
1755 String message = "Unknown groupId '" + groupId + "'";
1756 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1757 loggingContext.transactionEnded();
1758 PolicyLogger.audit("Transaction Failed - See Error.log");
1759 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1762 if (request.getParameter("policy") != null) {
1763 // 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)
1764 loggingContext.setServiceName("AC:PAP.putPolicy");
1765 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
1766 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1767 loggingContext.transactionEnded();
1768 PolicyLogger.audit("Transaction Failed - See Error.log");
1769 auditLogger.info("Success");
1770 PolicyLogger.audit("Transaction Ended Successfully");
1772 } else if (request.getParameter("pdpId") != null) {
1773 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
1774 String pdpId = request.getParameter("pdpId");
1775 if (papEngine.getPDP(pdpId) == null) {
1776 loggingContext.setServiceName("AC:PAP.createPDP");
1778 loggingContext.setServiceName("AC:PAP.updatePDP");
1780 // get the request content into a String
1782 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1783 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1784 scanner.useDelimiter("\\A");
1785 json = scanner.hasNext() ? scanner.next() : "";
1787 LOGGER.info("JSON request from AC: " + json);
1788 // convert Object sent as JSON into local object
1789 ObjectMapper mapper = new ObjectMapper();
1790 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
1791 if (pdpId == null ||
1792 objectFromJSON == null ||
1793 ! (objectFromJSON instanceof StdPDP) ||
1794 ((StdPDP)objectFromJSON).getId() == null ||
1795 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
1796 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
1797 loggingContext.transactionEnded();
1798 PolicyLogger.audit("Transaction Failed - See Error.log");
1799 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
1801 StdPDP pdp = (StdPDP) objectFromJSON;
1803 if (papEngine.getPDP(pdpId) == null) {
1804 // this is a request to create a new PDP object
1806 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
1807 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
1808 } catch(Exception e){
1809 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1810 +"pdp="+ (pdp.getId()) +",to group="+group.getId());
1811 throw new PAPException(e.getMessage());
1813 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
1816 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
1817 } catch(Exception e){
1818 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
1819 +"pdp="+ pdp.getId());
1820 throw new PAPException(e.getMessage());
1822 // this is a request to update the pdp
1823 papEngine.updatePDP(pdp);
1825 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1826 if (LOGGER.isDebugEnabled()) {
1827 LOGGER.debug("PDP '" + pdpId + "' created/updated");
1829 // adjust the group's state including the new PDP
1830 ((StdPDPGroup)group).resetStatus();
1831 // tell the Admin Consoles there is a change
1833 // this might affect the PDP, so notify it of the change
1835 acPutTransaction.commitTransaction();
1836 loggingContext.transactionEnded();
1837 auditLogger.info("Success");
1838 PolicyLogger.audit("Transaction Ended Successfully");
1842 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1843 +"pdp=null" + ",to group="+group.getId());
1844 throw new PAPException("PDP is null");
1845 } catch(Exception e){
1846 throw new PAPException("PDP is null" + e.getMessage() +e);
1849 } else if (request.getParameter("pipId") != null) {
1850 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
1851 loggingContext.setServiceName("AC:PAP.putPIP");
1852 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1853 loggingContext.transactionEnded();
1854 PolicyLogger.audit("Transaction Failed - See Error.log");
1855 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1858 // Assume that this is an update of an existing PDP Group
1859 // ARGS: group=<groupId> <= Update an Existing Group
1860 loggingContext.setServiceName("AC:PAP.updateGroup");
1861 // get the request content into a String
1863 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1864 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1865 scanner.useDelimiter("\\A");
1866 json = scanner.hasNext() ? scanner.next() : "";
1868 LOGGER.info("JSON request from AC: " + json);
1869 // convert Object sent as JSON into local object
1870 ObjectMapper mapper = new ObjectMapper();
1871 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
1872 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
1873 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
1874 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
1875 loggingContext.transactionEnded();
1876 PolicyLogger.audit("Transaction Failed - See Error.log");
1877 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, id="+group.getId() +" object="+objectFromJSON);
1879 // The Path on the PAP side is not carried on the RESTful interface with the AC
1880 // (because it is local to the PAP)
1881 // so we need to fill that in before submitting the group for update
1882 if(objectFromJSON != null){
1883 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
1886 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
1887 } catch(Exception e){
1888 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
1889 +"group="+group.getId());
1891 throw new PAPException(e.getMessage());
1894 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1895 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
1896 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
1897 LOGGER.debug("Precheck Successful.");
1900 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
1902 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1903 if (LOGGER.isDebugEnabled()) {
1904 LOGGER.debug("Group '" + group.getId() + "' updated");
1906 acPutTransaction.commitTransaction();
1907 // tell the Admin Consoles there is a change
1909 // Group changed, which might include changing the policies
1910 groupChanged(group);
1911 loggingContext.transactionEnded();
1912 auditLogger.info("Success");
1913 PolicyLogger.audit("Transaction Ended Successfully");
1916 } catch (PAPException e) {
1918 acPutTransaction.rollbackTransaction();
1919 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
1920 loggingContext.transactionEnded();
1921 PolicyLogger.audit("Transaction Failed - See Error.log");
1922 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1928 * Requests from the Admin Console to delete/remove items
1933 * @param loggingContext
1934 * @throws ServletException
1935 * @throws IOException
1937 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1938 //This code is to allow deletes to propagate to the database since delete is not implemented
1939 String isDeleteNotify = request.getParameter("isDeleteNotify");
1940 if(isDeleteNotify != null){
1941 String policyToDelete = request.getParameter("policyToDelete");
1943 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
1944 } catch(UnsupportedEncodingException e){
1945 LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
1946 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
1949 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
1951 deleteTransaction.deletePolicy(policyToDelete);
1952 } catch(Exception e){
1953 deleteTransaction.rollbackTransaction();
1954 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
1955 + "\nfailure with the following exception: " + e);
1958 deleteTransaction.commitTransaction();
1959 response.setStatus(HttpServletResponse.SC_OK);
1962 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
1964 // for all DELETE operations the group must exist before the operation can be done
1965 loggingContext.setServiceName("AC:PAP.delete");
1966 OnapPDPGroup group = papEngine.getGroup(groupId);
1967 if (group == null) {
1968 String message = "Unknown groupId '" + groupId + "'";
1969 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1970 loggingContext.transactionEnded();
1971 PolicyLogger.audit("Transaction Failed - See Error.log");
1972 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
1975 // determine the operation needed based on the parameters in the request
1976 if (request.getParameter("policy") != null) {
1977 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
1978 loggingContext.setServiceName("AC:PAP.deletePolicy");
1979 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1980 loggingContext.transactionEnded();
1981 PolicyLogger.audit("Transaction Failed - See Error.log");
1982 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1984 } else if (request.getParameter("pdpId") != null) {
1985 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
1986 String pdpId = request.getParameter("pdpId");
1987 OnapPDP pdp = papEngine.getPDP(pdpId);
1989 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
1990 } catch(Exception e){
1991 throw new PAPException(e);
1993 papEngine.removePDP((OnapPDP) pdp);
1994 // adjust the status of the group, which may have changed when we removed this PDP
1995 ((StdPDPGroup)group).resetStatus();
1996 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1998 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2000 removePdpOrGroupTransaction.commitTransaction();
2001 loggingContext.transactionEnded();
2002 auditLogger.info("Success");
2003 PolicyLogger.audit("Transaction Ended Successfully");
2005 } else if (request.getParameter("pipId") != null) {
2006 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2007 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2008 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2009 loggingContext.transactionEnded();
2010 PolicyLogger.audit("Transaction Failed - See Error.log");
2011 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2014 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
2015 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2016 OnapPDPGroup moveToGroup = null;
2017 if (moveToGroupId != null) {
2018 moveToGroup = papEngine.getGroup(moveToGroupId);
2020 // get list of PDPs in the group being deleted so we can notify them that they got changed
2021 Set<OnapPDP> movedPDPs = new HashSet<>();
2022 movedPDPs.addAll(group.getOnapPdps());
2023 // do the move/remove
2025 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2026 } catch(Exception e){
2027 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2028 throw new PAPException(e.getMessage());
2030 papEngine.removeGroup(group, moveToGroup);
2031 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2033 // notify any PDPs in the removed set that their config may have changed
2034 for (OnapPDP pdp : movedPDPs) {
2037 removePdpOrGroupTransaction.commitTransaction();
2038 loggingContext.transactionEnded();
2039 auditLogger.info("Success");
2040 PolicyLogger.audit("Transaction Ended Successfully");
2043 } catch (PAPException e) {
2044 removePdpOrGroupTransaction.rollbackTransaction();
2045 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2046 loggingContext.transactionEnded();
2047 PolicyLogger.audit("Transaction Failed - See Error.log");
2048 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2054 * Heartbeat thread - periodically check on PDPs' status
2056 * Heartbeat with all known PDPs.
2058 * Implementation note:
2060 * The PDPs are contacted Sequentially, not in Parallel.
2062 * If we did this in parallel using multiple threads we would simultaneously use
2066 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2067 * when user changes occur.
2068 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2070 * The Sequential operation does a heartbeat request to each PDP one at a time.
2071 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2072 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2073 * it could take a long time to cycle through all of the PDPs.
2074 * That means that this may not notice a PDP being down in a predictable time.
2076 private class Heartbeat implements Runnable {
2077 private PAPPolicyEngine papEngine;
2078 private Set<OnapPDP> pdps = new HashSet<>();
2079 private int heartbeatInterval;
2080 private int heartbeatTimeout;
2082 public volatile boolean isRunning = false;
2084 public synchronized boolean isRunning() {
2085 return this.isRunning;
2088 public synchronized void terminate() {
2089 this.isRunning = false;
2092 public Heartbeat(PAPPolicyEngine papEngine2) {
2093 papEngine = papEngine2;
2094 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2095 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2100 // Set ourselves as running
2101 synchronized(this) {
2102 this.isRunning = true;
2104 HashMap<String, URL> idToURLMap = new HashMap<>();
2106 while (this.isRunning()) {
2107 // Wait the given time
2108 Thread.sleep(heartbeatInterval);
2109 // get the list of PDPs (may have changed since last time)
2111 synchronized(papEngine) {
2113 for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2114 for (OnapPDP p : g.getOnapPdps()) {
2118 } catch (PAPException e) {
2119 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2122 // Check for shutdown
2123 if (this.isRunning() == false) {
2124 LOGGER.info("isRunning is false, getting out of loop.");
2127 // try to get the summary status from each PDP
2128 boolean changeSeen = false;
2129 for (OnapPDP pdp : pdps) {
2130 // Check for shutdown
2131 if (this.isRunning() == false) {
2132 LOGGER.info("isRunning is false, getting out of loop.");
2135 // the id of the PDP is its url (though we add a query parameter)
2136 URL pdpURL = idToURLMap.get(pdp.getId());
2137 if (pdpURL == null) {
2138 // haven't seen this PDP before
2139 String fullURLString = null;
2142 if(CheckPDP.validateID(pdp.getId())){
2143 fullURLString = pdp.getId() + "?type=hb";
2144 pdpURL = new URL(fullURLString);
2145 idToURLMap.put(pdp.getId(), pdpURL);
2147 } catch (MalformedURLException e) {
2148 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2152 // Do a GET with type HeartBeat
2153 String newStatus = "";
2154 HttpURLConnection connection = null;
2156 // Open up the connection
2158 connection = (HttpURLConnection)pdpURL.openConnection();
2159 // Setup our method and headers
2160 connection.setRequestMethod("GET");
2161 connection.setConnectTimeout(heartbeatTimeout);
2163 String encoding = CheckPDP.getEncoding(pdp.getId());
2164 if(encoding !=null){
2165 connection.setRequestProperty("Authorization", "Basic " + encoding);
2168 connection.connect();
2169 if (connection.getResponseCode() == 204) {
2170 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2171 if (LOGGER.isDebugEnabled()) {
2172 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2175 // anything else is an unexpected result
2176 newStatus = PDPStatus.Status.UNKNOWN.toString();
2177 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2180 } catch (UnknownHostException e) {
2181 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2182 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2183 } catch (SocketTimeoutException e) {
2184 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2185 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2186 } catch (ConnectException e) {
2187 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2188 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2189 } catch (Exception e) {
2190 newStatus = PDPStatus.Status.UNKNOWN.toString();
2191 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2193 // cleanup the connection
2194 if(connection != null)
2195 connection.disconnect();
2197 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2198 if (LOGGER.isDebugEnabled()) {
2199 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2202 setPDPSummaryStatus(pdp, newStatus);
2203 } catch (PAPException e) {
2204 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2209 // Check for shutdown
2210 if (this.isRunning() == false) {
2211 LOGGER.info("isRunning is false, getting out of loop.");
2214 // if any of the PDPs changed state, tell the ACs to update
2219 } catch (InterruptedException e) {
2220 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2222 Thread.currentThread().interrupt();
2228 * HELPER to change Group status when PDP status is changed
2229 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2231 private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2232 setPDPSummaryStatus(pdp, newStatus.toString());
2235 private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2236 synchronized(papEngine) {
2237 StdPDPStatus status = new StdPDPStatus();
2238 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2239 ((StdPDP)pdp).setStatus(status);
2240 // now adjust the group
2241 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2242 // if the PDP was just deleted it may transiently exist but not be in a group
2243 if (group != null) {
2244 group.resetStatus();
2250 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2251 * in the PDP group directories
2254 public void changed() {
2255 // all PDPs in all groups need to be updated/sync'd
2256 Set<OnapPDPGroup> groups;
2258 groups = papEngine.getOnapPDPGroups();
2259 } catch (PAPException e) {
2260 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2261 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2263 for (OnapPDPGroup group : groups) {
2264 groupChanged(group);
2269 public void groupChanged(OnapPDPGroup group) {
2270 // all PDPs within one group need to be updated/sync'd
2271 for (OnapPDP pdp : group.getOnapPdps()) {
2277 public void pdpChanged(OnapPDP pdp) {
2278 // kick off a thread to do an event notification for each PDP.
2279 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2280 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2281 Thread t = new Thread(new UpdatePDPThread(pdp));
2282 if(CheckPDP.validateID(pdp.getId())){
2287 private class UpdatePDPThread implements Runnable {
2288 private OnapPDP pdp;
2289 private String requestId;
2291 public UpdatePDPThread(OnapPDP pdp) {
2296 // send the current configuration to one PDP
2297 HttpURLConnection connection = null;
2298 // get a new logging context for the thread
2299 ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
2301 loggingContext.setServiceName("PAP:PDP.putConfig");
2302 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2303 if ((requestId == null) || (requestId == "")) {
2304 UUID requestID = UUID.randomUUID();
2305 loggingContext.setRequestID(requestID.toString());
2306 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2308 loggingContext.setRequestID(requestId);
2309 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2311 loggingContext.transactionStarted();
2312 // the Id of the PDP is its URL
2313 if (LOGGER.isDebugEnabled()) {
2314 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2316 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2317 //TODO (need to change "cache=", implying getting some input saying which to change)
2318 URL url = new URL(pdp.getId() + "?cache=all");
2319 // Open up the connection
2320 connection = (HttpURLConnection)url.openConnection();
2321 // Setup our method and headers
2322 connection.setRequestMethod("PUT");
2324 String encoding = CheckPDP.getEncoding(pdp.getId());
2325 if(encoding !=null){
2326 connection.setRequestProperty("Authorization", "Basic " + encoding);
2328 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2329 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2330 connection.setInstanceFollowRedirects(true);
2331 connection.setDoOutput(true);
2332 try (OutputStream os = connection.getOutputStream()) {
2333 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2334 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2335 if (group == null) {
2336 // create blank properties files
2337 Properties policyProperties = new Properties();
2338 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2339 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2340 policyProperties.store(os, "");
2341 Properties pipProps = new Properties();
2342 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2343 pipProps.store(os, "");
2345 // send properties from the current group
2346 group.getPolicyProperties().store(os, "");
2347 Properties policyLocations = new Properties();
2348 for (PDPPolicy policy : group.getPolicies()) {
2349 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2351 policyLocations.store(os, "");
2352 group.getPipConfigProperties().store(os, "");
2354 } catch (Exception e) {
2355 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2356 // Since this is a server-side error, it probably does not reflect a problem on the client,
2357 // so do not change the PDP status.
2361 connection.connect();
2362 if (connection.getResponseCode() == 204) {
2363 LOGGER.info("Success. We are configured correctly.");
2364 loggingContext.transactionEnded();
2365 auditLogger.info("Success. PDP is configured correctly.");
2366 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2367 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2368 } else if (connection.getResponseCode() == 200) {
2369 LOGGER.info("Success. PDP needs to update its configuration.");
2370 loggingContext.transactionEnded();
2371 auditLogger.info("Success. PDP needs to update its configuration.");
2372 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2373 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2375 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2376 loggingContext.transactionEnded();
2377 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2378 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2379 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2381 } catch (Exception e) {
2383 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2384 loggingContext.transactionEnded();
2385 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2387 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2388 } catch (PAPException e1) {
2390 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2391 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2394 // cleanup the connection
2395 if(connection != null){
2396 connection.disconnect();
2398 // tell the AC to update it's status info
2405 * RESTful Interface from PAP to ACs notifying them of changes
2407 private void notifyAC() {
2408 // kick off a thread to do one event notification for all registered ACs
2409 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2410 // as part of processing this message on their end.
2411 Thread t = new Thread(new NotifyACThread());
2415 private class NotifyACThread implements Runnable {
2417 List<String> disconnectedACs = new ArrayList<>();
2418 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2419 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2420 for (String acURL : adminConsoleURLStringList) {
2421 HttpURLConnection connection = null;
2423 acURL += "?PAPNotification=true";
2424 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2425 //TODO - If so, put correct parameters into the Query string here
2426 acURL += "&objectType=all" + "&action=update";
2427 if (LOGGER.isDebugEnabled()) {
2428 LOGGER.debug("creating url for id '" + acURL + "'");
2430 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2431 //TODO (need to change "cache=", implying getting some input saying which to change)
2432 URL url = new URL(acURL );
2433 // Open up the connection
2434 connection = (HttpURLConnection)url.openConnection();
2435 // Setup our method and headers
2436 connection.setRequestMethod("PUT");
2437 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2438 // Adding this in. It seems the HttpUrlConnection class does NOT
2439 // properly forward our headers for POST re-direction. It does so
2440 // for a GET re-direction.
2441 // So we need to handle this ourselves.
2442 //TODO - is this needed for a PUT? seems better to leave in for now?
2443 connection.setInstanceFollowRedirects(false);
2444 // Do not include any data in the PUT because this is just a
2445 // notification to the AC.
2446 // The AC will use GETs back to the PAP to get what it needs
2447 // to fill in the screens.
2449 connection.connect();
2450 if (connection.getResponseCode() == 204) {
2451 LOGGER.info("Success. We updated correctly.");
2453 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2456 } catch (Exception e) {
2457 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2458 disconnectedACs.add(acURL);
2460 // cleanup the connection
2461 if(connection != null)
2462 connection.disconnect();
2465 // remove any ACs that are no longer connected
2466 if (disconnectedACs.size() > 0) {
2467 adminConsoleURLStringList.removeAll(disconnectedACs);
2472 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2473 LOGGER.info("Test request received");
2475 im.evaluateSanity();
2476 //If we make it this far, all is well
2477 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2478 LOGGER.info(message);
2479 loggingContext.transactionEnded();
2480 PolicyLogger.audit("Transaction Failed - See Error.log");
2481 response.setStatus(HttpServletResponse.SC_OK);
2483 }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2485 if (e instanceof ForwardProgressException) {
2486 submsg = " is not making forward progress.";
2487 } else if (e instanceof AdministrativeStateException) {
2488 submsg = " Administrative State is LOCKED.";
2490 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2493 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2494 + " Exception Message: " + e.getMessage();
2495 LOGGER.info(message, e);
2496 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2497 loggingContext.transactionEnded();
2498 PolicyLogger.audit("Transaction Failed - See Error.log");
2499 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2501 }catch (Exception e) {
2502 //A subsystem is not making progress, is locked, standby or is not responding
2503 String eMsg = e.getMessage();
2505 eMsg = "No Exception Message";
2507 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2508 + " Exception Message: " + eMsg;
2509 LOGGER.info(message, e);
2510 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2511 loggingContext.transactionEnded();
2512 PolicyLogger.audit("Transaction Failed - See Error.log");
2513 //Get the specific list of subsystems that failed
2514 String ssFailureList = null;
2515 for(String failedSS : papDependencyGroupsFlatArray){
2516 if(eMsg.contains(failedSS)){
2517 if(ssFailureList == null){
2518 ssFailureList = failedSS;
2520 ssFailureList = ssFailureList.concat(","+failedSS);
2524 if(ssFailureList == null){
2525 ssFailureList = "UnknownSubSystem";
2527 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2528 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2534 * Authorizing the PEP Requests.
2536 private boolean authorizeRequest(HttpServletRequest request) {
2537 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2538 // Check if the Client is Authorized.
2539 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2546 private static void loadWebapps() throws PAPException{
2547 if(actionHome == null || configHome == null){
2548 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2550 if (webappsPath == null) {
2551 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2552 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2554 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2555 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2556 if (Files.notExists(webappsPathConfig)) {
2558 Files.createDirectories(webappsPathConfig);
2559 } catch (IOException e) {
2560 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2561 + webappsPathConfig.toAbsolutePath().toString());
2564 if (Files.notExists(webappsPathAction)) {
2566 Files.createDirectories(webappsPathAction);
2567 } catch (IOException e) {
2568 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2569 + webappsPathAction.toAbsolutePath().toString(), e);
2572 actionHome = webappsPathAction.toString();
2573 configHome = webappsPathConfig.toString();
2577 public static String getConfigHome(){
2580 } catch (PAPException e) {
2587 private static void setConfigHome(){
2588 configHome = getConfigHome();
2591 public static String getActionHome(){
2594 } catch (PAPException e) {
2601 private static void setActionHome(){
2602 actionHome = getActionHome();
2605 public static EntityManagerFactory getEmf() {
2609 public IntegrityAudit getIa() {
2613 public static String getPDPFile(){
2614 return XACMLPapServlet.pdpFile;
2617 public static String getPersistenceUnit(){
2618 return PERSISTENCE_UNIT;
2621 public static PAPPolicyEngine getPAPEngine(){
2625 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2626 return policyDBDao.getNewTransaction();
2628 public static String getPapDbDriver() {
2632 public static void setPapDbDriver(String papDbDriver) {
2633 XACMLPapServlet.papDbDriver = papDbDriver;
2636 public static String getPapDbUrl() {
2640 public static void setPapDbUrl(String papDbUrl) {
2641 XACMLPapServlet.papDbUrl = papDbUrl;
2644 public static String getPapDbUser() {
2648 public static void setPapDbUser(String papDbUser) {
2649 XACMLPapServlet.papDbUser = papDbUser;
2652 public static String getPapDbPassword() {
2653 return papDbPassword;
2656 public static void setPapDbPassword(String papDbPassword) {
2657 XACMLPapServlet.papDbPassword = papDbPassword;
2660 public static String getMsOnapName() {
2664 public static void setMsOnapName(String msOnapName) {
2665 XACMLPapServlet.msOnapName = msOnapName;
2668 public static String getMsPolicyName() {
2669 return msPolicyName;
2672 public static void setMsPolicyName(String msPolicyName) {
2673 XACMLPapServlet.msPolicyName = msPolicyName;