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;
46 import java.util.Scanner;
48 import java.util.UUID;
49 import java.util.concurrent.CopyOnWriteArrayList;
51 import javax.persistence.EntityManagerFactory;
52 import javax.persistence.Persistence;
53 import javax.persistence.PersistenceException;
54 import javax.servlet.Servlet;
55 import javax.servlet.ServletConfig;
56 import javax.servlet.ServletException;
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, HttpServletResponse response, Object value) {
343 mapper.writeValue(response.getOutputStream(), 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();
788 apiRequestHandler.doGet(request,response, apiflag);
789 }catch(IOException e){
792 loggingContext.transactionEnded();
793 PolicyLogger.audit("Transaction Ended Successfully");
797 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
798 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
799 loggingContext.transactionEnded();
800 PolicyLogger.audit("Transaction Failed - See Error.log");
801 setResponseError(response, HttpServletResponse.SC_FORBIDDEN, message);
806 // Is this from the Admin Console?
807 String groupId = request.getParameter("groupId");
808 if (groupId != null) {
809 // this is from the Admin Console, so handle separately
811 doACGet(request, response, groupId, loggingContext);
812 } catch(IOException e){
815 loggingContext.transactionEnded();
816 PolicyLogger.audit("Transaction Ended Successfully");
821 String id = this.getPDPID(request);
822 LOGGER.info("doGet from: " + id);
823 // Get the PDP Object
826 pdp = XACMLPapServlet.papEngine.getPDP(id);
827 }catch(PAPException e){
832 // Check if request came from localhost
833 if (request.getRemoteHost().equals("localhost") ||
834 request.getRemoteHost().equals(request.getLocalAddr())) {
835 // Return status information - basically all the groups
836 loggingContext.setServiceName("PAP.getGroups");
837 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
838 // convert response object to JSON and include in the response
839 mapperWriteValue(new ObjectMapper(), response, groups);
840 response.setHeader("content-type", "application/json");
841 response.setStatus(HttpServletResponse.SC_OK);
842 loggingContext.transactionEnded();
843 PolicyLogger.audit("Transaction Ended Successfully");
847 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
848 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
849 loggingContext.transactionEnded();
850 PolicyLogger.audit("Transaction Failed - See Error.log");
851 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
855 loggingContext.setServiceName("PAP.getPolicy");
856 // Get the PDP's Group
857 OnapPDPGroup group = null;
859 group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
860 } catch (PAPException e) {
864 String message = "No group associated with pdp " + pdp.getId();
865 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
866 loggingContext.transactionEnded();
867 PolicyLogger.audit("Transaction Failed - See Error.log");
868 setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
872 // Which policy do they want?
873 String policyId = request.getParameter("id");
874 if (policyId == null) {
875 String message = "Did not specify an id for the policy";
876 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
877 loggingContext.transactionEnded();
878 PolicyLogger.audit("Transaction Failed - See Error.log");
879 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
883 PDPPolicy policy = group.getPolicy(policyId);
884 if (policy == null) {
885 String message = "Unknown policy: " + policyId;
886 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
887 loggingContext.transactionEnded();
888 PolicyLogger.audit("Transaction Failed - See Error.log");
889 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
894 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
895 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
896 } catch (PAPException| IOException e){
899 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
900 // Send the policy back
901 IOUtils.copy(is, os);
902 response.setStatus(HttpServletResponse.SC_OK);
903 loggingContext.transactionEnded();
904 auditLogger.info("Success");
905 PolicyLogger.audit("Transaction Ended Successfully");
906 } catch (IOException e) {
907 String message = "Failed to open policy id " + policyId;
909 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
910 loggingContext.transactionEnded();
911 PolicyLogger.audit("Transaction Failed - See Error.log");
912 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
914 } catch (PAPException e) {
916 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
917 loggingContext.transactionEnded();
918 PolicyLogger.audit("Transaction Failed - See Error.log");
919 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
923 loggingContext.transactionEnded();
924 PolicyLogger.audit("Transaction Ended");
929 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
931 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
932 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
933 loggingContext.transactionStarted();
934 loggingContext.setServiceName("PAP.put");
935 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
936 UUID requestID = UUID.randomUUID();
937 loggingContext.setRequestID(requestID.toString());
938 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
940 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
943 im.startTransaction();
944 } catch (AdministrativeStateException | StandbyStatusException e) {
945 String message = "PUT interface called for PAP " + papResourceName;
946 if (e instanceof AdministrativeStateException) {
947 message += " but it has an Administrative state of "
948 + im.getStateManager().getAdminState();
949 } else if (e instanceof StandbyStatusException) {
950 message += " but it has a Standby Status of "
951 + im.getStateManager().getStandbyStatus();
954 message += "\n Exception Message: " + e.getMessage();
956 LOGGER.info(message, e);
957 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
958 loggingContext.transactionEnded();
959 PolicyLogger.audit("Transaction Failed - See Error.log");
960 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
964 XACMLRest.dumpRequest(request);
965 //need to check if request is from the API or Admin console
966 String apiflag = request.getParameter("apiflag");
967 //This would occur if a PolicyDBDao notification was received
968 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
969 if(policyDBDaoRequestUrl != null){
970 String policyDBDaoRequestEntityId = request.getParameter("entityid");
971 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
972 String policyDBDaoRequestExtraData = request.getParameter("extradata");
973 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
974 setResponseError(response,400, "entityid or entitytype not supplied");
975 loggingContext.transactionEnded();
976 PolicyLogger.audit("Transaction Ended Successfully");
980 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
981 response.setStatus(200);
982 loggingContext.transactionEnded();
983 PolicyLogger.audit("Transaction Ended Successfully");
988 * Request for ImportService
990 String importService = request.getParameter("importService");
991 if (importService != null) {
992 if(authorizeRequest(request)){
993 APIRequestHandler apiRequestHandler = new APIRequestHandler();
995 apiRequestHandler.doPut(request, response, importService);
996 }catch(IOException e){
1002 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1003 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
1004 loggingContext.transactionEnded();
1005 PolicyLogger.audit("Transaction Failed - See Error.log");
1006 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1010 //This would occur if we received a notification of a policy rename from AC
1011 String oldPolicyName = request.getParameter("oldPolicyName");
1012 String newPolicyName = request.getParameter("newPolicyName");
1013 if(oldPolicyName != null && newPolicyName != null){
1014 if(LOGGER.isDebugEnabled()){
1015 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
1016 + "\npolicyToCreateUpdate = " + " ");
1020 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
1021 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
1022 if(LOGGER.isDebugEnabled()){
1023 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
1024 + "\npolicyToCreateUpdate = " + " ");
1026 } catch(UnsupportedEncodingException e){
1027 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
1028 + "\npolicyToCreateUpdate = " + " ");
1029 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToCreateUpdate encoding not supported"
1030 + "\nfailure with the following exception: " + e);
1031 loggingContext.transactionEnded();
1032 PolicyLogger.audit("Transaction Failed - See error.log");
1033 im.endTransaction();
1036 //send it to PolicyDBDao
1037 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1039 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1040 }catch(Exception e){
1041 renameTransaction.rollbackTransaction();
1042 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1043 + "\nfailure with the following exception: " + e);
1044 loggingContext.transactionEnded();
1045 PolicyLogger.audit("Transaction Failed - See error.log");
1046 im.endTransaction();
1049 renameTransaction.commitTransaction();
1050 response.setStatus(HttpServletResponse.SC_OK);
1051 loggingContext.transactionEnded();
1052 PolicyLogger.audit("Transaction Ended Successfully");
1053 im.endTransaction();
1057 // See if this is Admin Console registering itself with us
1059 String acURLString = request.getParameter("adminConsoleURL");
1060 if (acURLString != null) {
1061 loggingContext.setServiceName("AC:PAP.register");
1062 // remember this Admin Console for future updates
1063 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1064 adminConsoleURLStringList.add(acURLString);
1066 if (LOGGER.isDebugEnabled()) {
1067 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1069 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1070 loggingContext.transactionEnded();
1071 auditLogger.info("Success");
1072 PolicyLogger.audit("Transaction Ended Successfully");
1073 im.endTransaction();
1077 * This is to update the PDP Group with the policy/policies being pushed
1078 * Part of a 2 step process to push policies to the PDP that can now be done
1079 * From both the Admin Console and the PolicyEngine API
1081 String groupId = request.getParameter("groupId");
1082 if (groupId != null) {
1084 if(!authorizeRequest(request)){
1085 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1086 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1087 loggingContext.transactionEnded();
1088 PolicyLogger.audit("Transaction Failed - See Error.log");
1089 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1092 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1094 updateGroupsFromAPI(request, response, groupId, loggingContext);
1095 }catch(IOException e){
1098 loggingContext.transactionEnded();
1099 PolicyLogger.audit("Transaction Ended Successfully");
1100 im.endTransaction();
1104 // this is from the Admin Console, so handle separately
1106 doACPut(request, response, groupId, loggingContext);
1107 } catch (IOException e) {
1110 loggingContext.transactionEnded();
1111 PolicyLogger.audit("Transaction Ended Successfully");
1112 im.endTransaction();
1116 // Request is for policy validation and creation
1118 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1119 // this request is from the Admin Console
1120 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1122 savePolicyHandler.doPolicyAPIPut(request, response);
1123 } catch (IOException e) {
1126 loggingContext.transactionEnded();
1127 PolicyLogger.audit("Transaction Ended Successfully");
1128 im.endTransaction();
1130 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1131 // this request is from the Policy Creation API
1132 if(authorizeRequest(request)){
1133 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1135 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1136 } catch (IOException e) {
1139 loggingContext.transactionEnded();
1140 PolicyLogger.audit("Transaction Ended Successfully");
1141 im.endTransaction();
1144 String message = "PEP not Authorized for making this Request!!";
1145 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1146 loggingContext.transactionEnded();
1147 PolicyLogger.audit("Transaction Failed - See Error.log");
1148 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1149 im.endTransaction();
1153 // We do not expect anything from anywhere else.
1154 // This method is here in case we ever need to support other operations.
1155 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1156 loggingContext.transactionEnded();
1157 PolicyLogger.audit("Transaction Failed - See Error.log");
1158 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1159 loggingContext.transactionEnded();
1160 PolicyLogger.audit("Transaction Failed - See error.log");
1161 im.endTransaction();
1165 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1167 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1168 ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1169 loggingContext.transactionStarted();
1170 loggingContext.setServiceName("PAP.delete");
1171 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1172 UUID requestID = UUID.randomUUID();
1173 loggingContext.setRequestID(requestID.toString());
1174 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1176 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1179 im.startTransaction();
1180 } catch (AdministrativeStateException ae){
1181 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1182 + " state of " + im.getStateManager().getAdminState()
1183 + "\n Exception Message: " + ae.getMessage();
1184 LOGGER.info(message, ae);
1185 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1186 loggingContext.transactionEnded();
1187 PolicyLogger.audit("Transaction Failed - See Error.log");
1188 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1190 }catch (StandbyStatusException se) {
1191 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1192 + " of " + im.getStateManager().getStandbyStatus()
1193 + "\n Exception Message: " + se.getMessage();
1194 LOGGER.info(message, se);
1195 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1196 loggingContext.transactionEnded();
1197 PolicyLogger.audit("Transaction Failed - See Error.log");
1198 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1201 XACMLRest.dumpRequest(request);
1202 String groupId = request.getParameter("groupId");
1203 String apiflag = request.getParameter("apiflag");
1204 if (groupId != null) {
1205 // Is this from the Admin Console or API?
1207 if(!authorizeRequest(request)){
1208 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1209 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1210 loggingContext.transactionEnded();
1211 PolicyLogger.audit("Transaction Failed - See Error.log");
1212 setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
1215 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1217 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1218 } catch (Exception e) {
1219 LOGGER.error("Exception Occured"+e);
1221 if(apiRequestHandler.getNewGroup()!=null){
1222 groupChanged(apiRequestHandler.getNewGroup());
1226 // this is from the Admin Console, so handle separately
1228 doACDelete(request, response, groupId, loggingContext);
1229 } catch (IOException e) {
1232 loggingContext.transactionEnded();
1233 PolicyLogger.audit("Transaction Ended Successfully");
1234 im.endTransaction();
1237 //Catch anything that fell through
1238 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1239 loggingContext.transactionEnded();
1240 PolicyLogger.audit("Transaction Failed - See Error.log");
1241 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1242 im.endTransaction();
1245 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1246 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1247 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1248 if (localRootPolicies == null || localReferencedPolicies == null) {
1249 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1252 // Compare the policies and pipconfig properties to the pdpProperties
1254 // the policy properties includes only xacml.rootPolicies and
1255 // xacml.referencedPolicies without any .url entries
1256 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1257 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1258 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1259 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1260 pdpPipConfig.equals(pipconfig)) {
1261 // The PDP is current
1264 } catch (Exception e) {
1265 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1266 // or if there are policies that do not have a corresponding ".url" property.
1267 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1268 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1273 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1274 String lists[] = new String[2];
1275 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1276 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1277 for (String list : lists) {
1278 if (list != null && list.isEmpty() == false) {
1279 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1280 String url = urlPath + "?id=" + id;
1281 LOGGER.info("Policy URL for " + id + ": " + url);
1282 policies.setProperty(id + ".url", url);
1288 protected String getPDPID(HttpServletRequest request) {
1289 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1290 if (pdpURL == null || pdpURL.isEmpty()) {
1291 // Should send back its port for identification
1292 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1298 protected String getPDPJMX(HttpServletRequest request) {
1299 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1300 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1301 // Should send back its port for identification
1302 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1309 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1314 * @param loggingContext
1315 * @throws ServletException
1316 * @throws IOException
1318 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1319 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1321 // for PUT operations the group may or may not need to exist before the operation can be done
1322 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1323 // get the request input stream content into a String
1325 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1326 scanner.useDelimiter("\\A");
1327 json = scanner.hasNext() ? scanner.next() : "";
1329 PolicyLogger.info("JSON request from PolicyEngine API: " + json);
1330 // convert Object sent as JSON into local object
1331 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1332 Set<PDPPolicy> policies = new HashSet<>();
1334 policies.add(policy);
1336 //Get the current policies from the Group and Add the new one
1337 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1338 currentPoliciesInGroup = group.getPolicies();
1339 //If the selected policy is in the group we must remove it because the name is default
1340 Iterator<PDPPolicy> policyIterator = policies.iterator();
1341 LOGGER.debug("policyIterator....." + policies);
1342 while (policyIterator.hasNext()) {
1343 PDPPolicy selPolicy = policyIterator.next();
1344 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
1345 if (existingPolicy.getId().equals(selPolicy.getId())) {
1346 group.removePolicyFromGroup(existingPolicy);
1347 LOGGER.debug("Removing policy: " + existingPolicy);
1352 //Update the PDP Group after removing old version of policy
1353 Set<PDPPolicy> updatedPoliciesInGroup = new HashSet<>();
1354 updatedPoliciesInGroup = group.getPolicies();
1355 //need to remove the policy with default name from group
1356 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
1357 if (updatedPolicy.getName().equalsIgnoreCase("default")) {
1358 group.removePolicyFromGroup(updatedPolicy);
1362 if(updatedPoliciesInGroup!=null){
1363 policies.addAll(updatedPoliciesInGroup);
1365 group.setPolicies(policies);
1366 // Assume that this is an update of an existing PDP Group
1367 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1369 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1370 } catch(Exception e){
1371 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1372 +"group="+group.getId());
1373 throw new PAPException(e.getMessage());
1375 papEngine.updateGroup(group);
1376 String policyId = "empty";
1378 policyId = policy.getId();
1380 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1381 response.addHeader("operation", "push");
1382 response.addHeader("policyId", policyId);
1383 response.addHeader("groupId", groupId);
1384 if (LOGGER.isDebugEnabled()) {
1385 LOGGER.debug("Group '" + group.getId() + "' updated");
1387 acPutTransaction.commitTransaction();
1389 // Group changed, which might include changing the policies
1390 groupChanged(group);
1391 loggingContext.transactionEnded();
1392 auditLogger.info("Success");
1394 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1395 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1396 if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
1397 LOGGER.debug("Precheck Successful.");
1401 PolicyLogger.audit("Transaction Ended Successfully");
1403 } catch (PAPException e) {
1404 acPutTransaction.rollbackTransaction();
1405 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1406 loggingContext.transactionEnded();
1407 PolicyLogger.audit("Transaction Failed - See Error.log");
1408 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1409 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1410 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1411 response.addHeader("error","addGroupError");
1412 response.addHeader("message", message);
1418 * Requests from the Admin Console for operations not on single specific objects
1423 * @param loggingContext
1424 * @throws ServletException
1425 * @throws IOException
1427 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException {
1428 PolicyDBDaoTransaction doACPostTransaction = null;
1430 String groupName = request.getParameter("groupName");
1431 String groupDescription = request.getParameter("groupDescription");
1432 String apiflag = request.getParameter("apiflag");
1433 if (groupName != null && groupDescription != null) {
1434 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1435 loggingContext.setServiceName("AC:PAP.createGroup");
1436 String unescapedName = null;
1437 String unescapedDescription = null;
1439 unescapedName = URLDecoder.decode(groupName, "UTF-8");
1440 unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1441 } catch (UnsupportedEncodingException e) {
1444 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1446 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1447 papEngine.newGroup(unescapedName, unescapedDescription);
1448 newGroupTransaction.commitTransaction();
1449 } catch (Exception e) {
1450 newGroupTransaction.rollbackTransaction();
1451 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1452 loggingContext.transactionEnded();
1454 PolicyLogger.audit("Transaction Failed - See Error.log");
1455 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create new group '" + groupId + "'");
1458 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1459 if (LOGGER.isDebugEnabled()) {
1460 LOGGER.debug("New Group '" + groupId + "' created");
1462 // tell the Admin Consoles there is a change
1464 // new group by definition has no PDPs, so no need to notify them of changes
1465 loggingContext.transactionEnded();
1466 PolicyLogger.audit("Transaction Failed - See Error.log");
1467 auditLogger.info("Success");
1468 PolicyLogger.audit("Transaction Ended Successfully");
1471 // for all remaining POST operations the group must exist before the operation can be done
1472 OnapPDPGroup group = null;
1474 group = papEngine.getGroup(groupId);
1475 } catch (PAPException e){
1478 if (group == null) {
1479 String message = "Unknown groupId '" + groupId + "'";
1480 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1481 loggingContext.transactionEnded();
1482 PolicyLogger.audit("Transaction Failed - See Error.log");
1484 response.addHeader("error", "unknownGroupId");
1485 response.addHeader("operation", "push");
1486 response.addHeader("message", message);
1487 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1489 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1493 // determine the operation needed based on the parameters in the request
1494 if (request.getParameter("policyId") != null) {
1495 // Args: group=<groupId> policy=<policyId> <= copy file
1496 // copy a policy from the request contents into a file in the group's directory on this machine
1498 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1500 loggingContext.setServiceName("AC:PAP.postPolicy");
1502 String policyId = request.getParameter("policyId");
1503 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1505 InputStream is = null;
1507 if (apiflag != null){
1508 // get the request content into a String if the request is from API
1510 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1511 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1512 scanner.useDelimiter("\\A");
1513 json = scanner.hasNext() ? scanner.next() : "";
1515 LOGGER.info("JSON request from API: " + json);
1516 // convert Object sent as JSON into local object
1517 ObjectMapper mapper = new ObjectMapper();
1518 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
1519 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
1520 temp = new File(policy.getLocation());
1521 is = new FileInputStream(temp);
1523 is = request.getInputStream();
1525 addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1526 if (apiflag != null){
1527 ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is);
1530 if (policyId.endsWith(".xml")) {
1531 name = policyId.replace(".xml", "");
1532 name = name.substring(0, name.lastIndexOf("."));
1534 ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is);
1536 if(is!=null && temp!=null){
1540 addPolicyToGroupTransaction.commitTransaction();
1541 } catch (Exception e) {
1542 addPolicyToGroupTransaction.rollbackTransaction();
1543 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1544 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1545 loggingContext.transactionEnded();
1546 PolicyLogger.audit("Transaction Failed - See Error.log");
1548 response.addHeader("error", "policyCopyError");
1549 response.addHeader("message", message);
1550 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1552 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1556 // policy file copied ok and the Group was updated on the PDP
1557 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1558 response.addHeader("operation", "push");
1559 response.addHeader("policyId", policyId);
1560 response.addHeader("groupId", groupId);
1561 if (LOGGER.isDebugEnabled()) {
1562 LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1564 loggingContext.transactionEnded();
1565 auditLogger.info("Success");
1566 PolicyLogger.audit("Transaction Ended Successfully");
1568 } else if (request.getParameter("default") != null) {
1569 // Args: group=<groupId> default=true <= make default
1570 // change the current default group to be the one identified in the request.
1571 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1572 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1573 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1574 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1576 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1577 papEngine.setDefaultGroup(group);
1578 setDefaultGroupTransaction.commitTransaction();
1579 } catch (Exception e) {
1580 setDefaultGroupTransaction.rollbackTransaction();
1581 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1582 loggingContext.transactionEnded();
1584 PolicyLogger.audit("Transaction Failed - See Error.log");
1585 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to set group '" + groupId + "' to default");
1588 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1589 if (LOGGER.isDebugEnabled()) {
1590 LOGGER.debug("Group '" + groupId + "' set to be default");
1592 // Notify the Admin Consoles that something changed
1593 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1594 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1596 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1597 loggingContext.transactionEnded();
1598 auditLogger.info("Success");
1599 PolicyLogger.audit("Transaction Ended Successfully");
1601 } else if (request.getParameter("pdpId") != null) {
1602 doACPostTransaction = policyDBDao.getNewTransaction();
1603 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1604 loggingContext.setServiceName("AC:PAP.movePDP");
1605 String pdpId = request.getParameter("pdpId");
1606 OnapPDP pdp = papEngine.getPDP(pdpId);
1607 OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
1609 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1610 }catch(Exception e){
1611 doACPostTransaction.rollbackTransaction();
1612 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1613 " Error while moving pdp in the database: "
1614 +"pdp="+pdp.getId()+",to group="+group.getId());
1615 throw new PAPException(e.getMessage());
1617 papEngine.movePDP((OnapPDP) pdp, group);
1618 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1619 if (LOGGER.isDebugEnabled()) {
1620 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1622 // update the status of both the original group and the new one
1623 ((StdPDPGroup)originalGroup).resetStatus();
1624 ((StdPDPGroup)group).resetStatus();
1625 // Notify the Admin Consoles that something changed
1626 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1628 // Need to notify the PDP that it's config may have changed
1630 doACPostTransaction.commitTransaction();
1631 loggingContext.transactionEnded();
1632 auditLogger.info("Success");
1633 PolicyLogger.audit("Transaction Ended Successfully");
1636 } catch (PAPException e) {
1637 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1638 loggingContext.transactionEnded();
1639 PolicyLogger.audit("Transaction Failed - See Error.log");
1640 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1646 * Requests from the Admin Console to GET info about the Groups and PDPs
1651 * @param loggingContext
1652 * @throws ServletException
1653 * @throws IOException
1655 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1657 String parameterDefault = request.getParameter("default");
1658 String pdpId = request.getParameter("pdpId");
1659 String pdpGroup = request.getParameter("getPDPGroup");
1660 if ("".equals(groupId)) {
1661 // request IS from AC but does not identify a group by name
1662 if (parameterDefault != null) {
1663 // Request is for the Default group (whatever its id)
1664 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1665 OnapPDPGroup group = papEngine.getDefaultGroup();
1666 // convert response object to JSON and include in the response
1667 mapperWriteValue(new ObjectMapper(), response, group);
1668 if (LOGGER.isDebugEnabled()) {
1669 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1671 response.setStatus(HttpServletResponse.SC_OK);
1672 response.setHeader("content-type", "application/json");
1674 response.getOutputStream().close();
1675 } catch (IOException e){
1678 loggingContext.transactionEnded();
1679 auditLogger.info("Success");
1680 PolicyLogger.audit("Transaction Ended Successfully");
1682 } else if (pdpId != null) {
1683 // Request is related to a PDP
1684 if (pdpGroup == null) {
1685 // Request is for the (unspecified) group containing a given PDP
1686 loggingContext.setServiceName("AC:PAP.getPDP");
1689 pdp = papEngine.getPDP(pdpId);
1690 }catch(PAPException e){
1693 // convert response object to JSON and include in the response
1694 mapperWriteValue(new ObjectMapper(), response, pdp);
1695 if (LOGGER.isDebugEnabled()) {
1696 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1698 response.setStatus(HttpServletResponse.SC_OK);
1699 response.setHeader("content-type", "application/json");
1701 response.getOutputStream().close();
1702 } catch (IOException e){
1705 loggingContext.transactionEnded();
1706 auditLogger.info("Success");
1707 PolicyLogger.audit("Transaction Ended Successfully");
1710 // Request is for the group containing a given PDP
1711 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1712 OnapPDPGroup group =null;
1714 OnapPDP pdp = papEngine.getPDP(pdpId);
1715 group = papEngine.getPDPGroup((OnapPDP) pdp);
1716 }catch(PAPException e){
1719 // convert response object to JSON and include in the response
1720 mapperWriteValue(new ObjectMapper(), response, group);
1721 if (LOGGER.isDebugEnabled()) {
1722 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1724 response.setStatus(HttpServletResponse.SC_OK);
1725 response.setHeader("content-type", "application/json");
1727 response.getOutputStream().close();
1728 } catch (IOException e){
1731 loggingContext.transactionEnded();
1732 auditLogger.info("Success");
1733 PolicyLogger.audit("Transaction Ended Successfully");
1737 // request is for top-level properties about all groups
1738 loggingContext.setServiceName("AC:PAP.getAllGroups");
1739 Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
1740 // convert response object to JSON and include in the response
1741 mapperWriteValue(new ObjectMapper(), response, groups);
1742 if (LOGGER.isDebugEnabled()) {
1743 LOGGER.debug("GET All groups req");
1745 response.setStatus(HttpServletResponse.SC_OK);
1746 response.setHeader("content-type", "application/json");
1748 response.getOutputStream().close();
1749 } catch (IOException e){
1752 loggingContext.transactionEnded();
1753 auditLogger.info("Success");
1754 PolicyLogger.audit("Transaction Ended Successfully");
1758 // for all other GET operations the group must exist before the operation can be done
1759 OnapPDPGroup group = null;
1761 group = papEngine.getGroup(groupId);
1762 } catch(PAPException e){
1765 if (group == null) {
1766 String message = "Unknown groupId '" + groupId + "'";
1767 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1768 loggingContext.transactionEnded();
1769 PolicyLogger.audit("Transaction Failed - See Error.log");
1770 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1773 // Figure out which request this is based on the parameters
1774 String policyId = request.getParameter("policyId");
1775 if (policyId != null) {
1776 // retrieve a policy
1777 loggingContext.setServiceName("AC:PAP.getPolicy");
1778 // convert response object to JSON and include in the response
1779 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1780 loggingContext.transactionEnded();
1781 PolicyLogger.audit("Transaction Failed - See Error.log");
1782 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1784 // No other parameters, so return the identified Group
1785 loggingContext.setServiceName("AC:PAP.getGroup");
1786 // convert response object to JSON and include in the response
1787 mapperWriteValue(new ObjectMapper(), response, group);
1788 if (LOGGER.isDebugEnabled()) {
1789 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1791 response.setStatus(HttpServletResponse.SC_OK);
1792 response.setHeader("content-type", "application/json");
1794 response.getOutputStream().close();
1795 } catch (IOException e){
1798 loggingContext.transactionEnded();
1799 auditLogger.info("Success");
1800 PolicyLogger.audit("Transaction Ended Successfully");
1803 // Currently there are no other GET calls from the AC.
1804 // 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.
1805 // Other GETs that could be called:
1806 // Specific Group (groupId=<groupId>)
1807 // A Policy (groupId=<groupId> policyId=<policyId>)
1808 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1809 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1810 loggingContext.transactionEnded();
1811 PolicyLogger.audit("Transaction Failed - See Error.log");
1812 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1813 } catch (PAPException e) {
1814 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1815 loggingContext.transactionEnded();
1816 PolicyLogger.audit("Transaction Failed - See Error.log");
1817 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1823 * Requests from the Admin Console to create new items or update existing ones
1828 * @param loggingContext
1829 * @throws ServletException
1830 * @throws IOException
1832 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
1833 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1835 // for PUT operations the group may or may not need to exist before the operation can be done
1836 OnapPDPGroup group = papEngine.getGroup(groupId);
1837 // determine the operation needed based on the parameters in the request
1838 // for remaining operations the group must exist before the operation can be done
1839 if (group == null) {
1840 String message = "Unknown groupId '" + groupId + "'";
1841 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1842 loggingContext.transactionEnded();
1843 PolicyLogger.audit("Transaction Failed - See Error.log");
1844 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
1847 if (request.getParameter("policy") != null) {
1848 // 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)
1849 loggingContext.setServiceName("AC:PAP.putPolicy");
1850 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
1851 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1852 loggingContext.transactionEnded();
1853 PolicyLogger.audit("Transaction Failed - See Error.log");
1854 auditLogger.info("Success");
1855 PolicyLogger.audit("Transaction Ended Successfully");
1857 } else if (request.getParameter("pdpId") != null) {
1858 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
1859 String pdpId = request.getParameter("pdpId");
1860 if (papEngine.getPDP(pdpId) == null) {
1861 loggingContext.setServiceName("AC:PAP.createPDP");
1863 loggingContext.setServiceName("AC:PAP.updatePDP");
1865 // get the request content into a String
1867 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1869 Scanner scanner = new Scanner(request.getInputStream());
1870 scanner.useDelimiter("\\A");
1871 json = scanner.hasNext() ? scanner.next() : "";
1873 }catch(IOException e){
1876 LOGGER.info("JSON request from AC: " + json);
1877 // convert Object sent as JSON into local object
1878 ObjectMapper mapper = new ObjectMapper();
1879 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
1880 if (pdpId == null ||
1881 objectFromJSON == null ||
1882 ! (objectFromJSON instanceof StdPDP) ||
1883 ((StdPDP)objectFromJSON).getId() == null ||
1884 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
1885 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
1886 loggingContext.transactionEnded();
1887 PolicyLogger.audit("Transaction Failed - See Error.log");
1888 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
1890 StdPDP pdp = (StdPDP) objectFromJSON;
1892 OnapPDP oPDP = null;
1894 oPDP = papEngine.getPDP(pdpId);
1895 }catch (PAPException e){
1899 // this is a request to create a new PDP object
1901 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(),
1902 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
1903 } catch(Exception e){
1904 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1905 +"pdp="+ (pdp.getId()) +",to group="+group.getId());
1906 throw new PAPException(e.getMessage());
1909 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
1910 }catch(PAPException e){
1915 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
1916 } catch(Exception e){
1917 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
1918 +"pdp="+ pdp.getId());
1919 throw new PAPException(e.getMessage());
1921 // this is a request to update the pdp
1923 papEngine.updatePDP(pdp);
1924 }catch(PAPException e){
1928 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1929 if (LOGGER.isDebugEnabled()) {
1930 LOGGER.debug("PDP '" + pdpId + "' created/updated");
1932 // adjust the group's state including the new PDP
1933 ((StdPDPGroup)group).resetStatus();
1934 // tell the Admin Consoles there is a change
1936 // this might affect the PDP, so notify it of the change
1938 acPutTransaction.commitTransaction();
1939 loggingContext.transactionEnded();
1940 auditLogger.info("Success");
1941 PolicyLogger.audit("Transaction Ended Successfully");
1945 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1946 +"pdp=null" + ",to group="+group.getId());
1947 throw new PAPException("PDP is null");
1948 } catch(Exception e){
1949 throw new PAPException("PDP is null" + e.getMessage() +e);
1952 } else if (request.getParameter("pipId") != null) {
1953 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
1954 loggingContext.setServiceName("AC:PAP.putPIP");
1955 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1956 loggingContext.transactionEnded();
1957 PolicyLogger.audit("Transaction Failed - See Error.log");
1958 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1961 // Assume that this is an update of an existing PDP Group
1962 // ARGS: group=<groupId> <= Update an Existing Group
1963 loggingContext.setServiceName("AC:PAP.updateGroup");
1964 // get the request content into a String
1966 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1968 Scanner scanner = new Scanner(request.getInputStream());
1969 scanner.useDelimiter("\\A");
1970 json = scanner.hasNext() ? scanner.next() : "";
1972 }catch(IOException e){
1975 LOGGER.info("JSON request from AC: " + json);
1976 // convert Object sent as JSON into local object
1977 ObjectMapper mapper = new ObjectMapper();
1978 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
1979 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
1980 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
1981 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
1982 loggingContext.transactionEnded();
1983 PolicyLogger.audit("Transaction Failed - See Error.log");
1984 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, id="+group.getId() +" object="+objectFromJSON);
1986 // The Path on the PAP side is not carried on the RESTful interface with the AC
1987 // (because it is local to the PAP)
1988 // so we need to fill that in before submitting the group for update
1989 if(objectFromJSON != null){
1990 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
1993 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
1994 } catch(Exception e){
1995 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
1996 +"group="+group.getId());
1998 throw new PAPException(e.getMessage());
2001 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
2002 OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
2003 if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {
2004 LOGGER.debug("Precheck Successful.");
2007 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
2008 }catch(PAPException e){
2011 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2012 if (LOGGER.isDebugEnabled()) {
2013 LOGGER.debug("Group '" + group.getId() + "' updated");
2015 acPutTransaction.commitTransaction();
2016 // tell the Admin Consoles there is a change
2018 // Group changed, which might include changing the policies
2019 groupChanged(group);
2020 loggingContext.transactionEnded();
2021 auditLogger.info("Success");
2022 PolicyLogger.audit("Transaction Ended Successfully");
2025 } catch (PAPException e) {
2027 acPutTransaction.rollbackTransaction();
2028 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
2029 loggingContext.transactionEnded();
2030 PolicyLogger.audit("Transaction Failed - See Error.log");
2031 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2037 * Requests from the Admin Console to delete/remove items
2042 * @param loggingContext
2043 * @throws ServletException
2044 * @throws IOException
2046 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
2047 //This code is to allow deletes to propagate to the database since delete is not implemented
2048 String isDeleteNotify = request.getParameter("isDeleteNotify");
2049 if(isDeleteNotify != null){
2050 String policyToDelete = request.getParameter("policyToDelete");
2052 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
2053 } catch(UnsupportedEncodingException e){
2054 LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
2055 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
2058 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
2060 deleteTransaction.deletePolicy(policyToDelete);
2061 } catch(Exception e){
2062 deleteTransaction.rollbackTransaction();
2063 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
2064 + "\nfailure with the following exception: " + e);
2067 deleteTransaction.commitTransaction();
2068 response.setStatus(HttpServletResponse.SC_OK);
2071 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
2073 // for all DELETE operations the group must exist before the operation can be done
2074 loggingContext.setServiceName("AC:PAP.delete");
2075 OnapPDPGroup group = papEngine.getGroup(groupId);
2076 if (group == null) {
2077 String message = "Unknown groupId '" + groupId + "'";
2078 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
2079 loggingContext.transactionEnded();
2080 PolicyLogger.audit("Transaction Failed - See Error.log");
2081 setResponseError(response,HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
2084 // determine the operation needed based on the parameters in the request
2085 if (request.getParameter("policy") != null) {
2086 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
2087 loggingContext.setServiceName("AC:PAP.deletePolicy");
2088 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2089 loggingContext.transactionEnded();
2090 PolicyLogger.audit("Transaction Failed - See Error.log");
2091 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2093 } else if (request.getParameter("pdpId") != null) {
2094 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
2095 String pdpId = request.getParameter("pdpId");
2096 OnapPDP pdp = papEngine.getPDP(pdpId);
2098 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
2099 } catch(Exception e){
2100 throw new PAPException(e);
2103 papEngine.removePDP((OnapPDP) pdp);
2104 }catch(PAPException e){
2107 // adjust the status of the group, which may have changed when we removed this PDP
2108 ((StdPDPGroup)group).resetStatus();
2109 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2111 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
2113 removePdpOrGroupTransaction.commitTransaction();
2114 loggingContext.transactionEnded();
2115 auditLogger.info("Success");
2116 PolicyLogger.audit("Transaction Ended Successfully");
2118 } else if (request.getParameter("pipId") != null) {
2119 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
2120 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
2121 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
2122 loggingContext.transactionEnded();
2123 PolicyLogger.audit("Transaction Failed - See Error.log");
2124 setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
2127 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
2128 String moveToGroupId = request.getParameter("movePDPsToGroupId");
2129 OnapPDPGroup moveToGroup = null;
2130 if (moveToGroupId != null) {
2132 moveToGroup = papEngine.getGroup(moveToGroupId);
2133 }catch(PAPException e){
2137 // get list of PDPs in the group being deleted so we can notify them that they got changed
2138 Set<OnapPDP> movedPDPs = new HashSet<>();
2139 movedPDPs.addAll(group.getOnapPdps());
2140 // do the move/remove
2142 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2143 } catch(Exception e){
2144 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2145 throw new PAPException(e.getMessage());
2148 papEngine.removeGroup(group, moveToGroup);
2149 }catch(PAPException e){
2152 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2154 // notify any PDPs in the removed set that their config may have changed
2155 for (OnapPDP pdp : movedPDPs) {
2158 removePdpOrGroupTransaction.commitTransaction();
2159 loggingContext.transactionEnded();
2160 auditLogger.info("Success");
2161 PolicyLogger.audit("Transaction Ended Successfully");
2164 } catch (PAPException e) {
2165 removePdpOrGroupTransaction.rollbackTransaction();
2166 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2167 loggingContext.transactionEnded();
2168 PolicyLogger.audit("Transaction Failed - See Error.log");
2169 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
2175 * Heartbeat thread - periodically check on PDPs' status
2177 * Heartbeat with all known PDPs.
2179 * Implementation note:
2181 * The PDPs are contacted Sequentially, not in Parallel.
2183 * If we did this in parallel using multiple threads we would simultaneously use
2187 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2188 * when user changes occur.
2189 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2191 * The Sequential operation does a heartbeat request to each PDP one at a time.
2192 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2193 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2194 * it could take a long time to cycle through all of the PDPs.
2195 * That means that this may not notice a PDP being down in a predictable time.
2197 private class Heartbeat implements Runnable {
2198 private PAPPolicyEngine papEngine;
2199 private Set<OnapPDP> pdps = new HashSet<>();
2200 private int heartbeatInterval;
2201 private int heartbeatTimeout;
2203 public volatile boolean isRunning = false;
2205 public synchronized boolean isRunning() {
2206 return this.isRunning;
2209 public synchronized void terminate() {
2210 this.isRunning = false;
2213 public Heartbeat(PAPPolicyEngine papEngine2) {
2214 papEngine = papEngine2;
2215 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2216 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2221 // Set ourselves as running
2222 synchronized(this) {
2223 this.isRunning = true;
2225 HashMap<String, URL> idToURLMap = new HashMap<>();
2227 while (this.isRunning()) {
2228 // Wait the given time
2229 Thread.sleep(heartbeatInterval);
2230 // get the list of PDPs (may have changed since last time)
2232 synchronized(papEngine) {
2234 for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
2235 for (OnapPDP p : g.getOnapPdps()) {
2239 } catch (PAPException e) {
2240 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2243 // Check for shutdown
2244 if (this.isRunning() == false) {
2245 LOGGER.info("isRunning is false, getting out of loop.");
2248 // try to get the summary status from each PDP
2249 boolean changeSeen = false;
2250 for (OnapPDP pdp : pdps) {
2251 // Check for shutdown
2252 if (this.isRunning() == false) {
2253 LOGGER.info("isRunning is false, getting out of loop.");
2256 // the id of the PDP is its url (though we add a query parameter)
2257 URL pdpURL = idToURLMap.get(pdp.getId());
2258 if (pdpURL == null) {
2259 // haven't seen this PDP before
2260 String fullURLString = null;
2263 if(CheckPDP.validateID(pdp.getId())){
2264 fullURLString = pdp.getId() + "?type=hb";
2265 pdpURL = new URL(fullURLString);
2266 idToURLMap.put(pdp.getId(), pdpURL);
2268 } catch (MalformedURLException e) {
2269 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2273 // Do a GET with type HeartBeat
2274 String newStatus = "";
2275 HttpURLConnection connection = null;
2277 // Open up the connection
2279 connection = (HttpURLConnection)pdpURL.openConnection();
2280 // Setup our method and headers
2281 connection.setRequestMethod("GET");
2282 connection.setConnectTimeout(heartbeatTimeout);
2284 String encoding = CheckPDP.getEncoding(pdp.getId());
2285 if(encoding !=null){
2286 connection.setRequestProperty("Authorization", "Basic " + encoding);
2289 connection.connect();
2290 if (connection.getResponseCode() == 204) {
2291 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2292 if (LOGGER.isDebugEnabled()) {
2293 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2296 // anything else is an unexpected result
2297 newStatus = PDPStatus.Status.UNKNOWN.toString();
2298 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2301 } catch (UnknownHostException e) {
2302 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2303 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2304 } catch (SocketTimeoutException e) {
2305 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2306 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2307 } catch (ConnectException e) {
2308 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2309 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2310 } catch (Exception e) {
2311 newStatus = PDPStatus.Status.UNKNOWN.toString();
2312 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2314 // cleanup the connection
2315 if(connection != null)
2316 connection.disconnect();
2318 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2319 if (LOGGER.isDebugEnabled()) {
2320 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2323 setPDPSummaryStatus(pdp, newStatus);
2324 } catch (PAPException e) {
2325 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2330 // Check for shutdown
2331 if (this.isRunning() == false) {
2332 LOGGER.info("isRunning is false, getting out of loop.");
2335 // if any of the PDPs changed state, tell the ACs to update
2340 } catch (InterruptedException e) {
2341 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2343 Thread.currentThread().interrupt();
2349 * HELPER to change Group status when PDP status is changed
2350 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2352 private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2353 setPDPSummaryStatus(pdp, newStatus.toString());
2356 private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException {
2357 synchronized(papEngine) {
2358 StdPDPStatus status = new StdPDPStatus();
2359 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2360 ((StdPDP)pdp).setStatus(status);
2361 // now adjust the group
2362 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp);
2363 // if the PDP was just deleted it may transiently exist but not be in a group
2364 if (group != null) {
2365 group.resetStatus();
2371 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2372 * in the PDP group directories
2375 public void changed() {
2376 // all PDPs in all groups need to be updated/sync'd
2377 Set<OnapPDPGroup> groups;
2379 groups = papEngine.getOnapPDPGroups();
2380 } catch (PAPException e) {
2381 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2382 throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2384 for (OnapPDPGroup group : groups) {
2385 groupChanged(group);
2390 public void groupChanged(OnapPDPGroup group) {
2391 // all PDPs within one group need to be updated/sync'd
2392 for (OnapPDP pdp : group.getOnapPdps()) {
2398 public void pdpChanged(OnapPDP pdp) {
2399 // kick off a thread to do an event notification for each PDP.
2400 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2401 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2402 Thread t = new Thread(new UpdatePDPThread(pdp));
2403 if(CheckPDP.validateID(pdp.getId())){
2408 private class UpdatePDPThread implements Runnable {
2409 private OnapPDP pdp;
2410 private String requestId;
2412 public UpdatePDPThread(OnapPDP pdp) {
2417 // send the current configuration to one PDP
2418 HttpURLConnection connection = null;
2419 // get a new logging context for the thread
2420 ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
2422 loggingContext.setServiceName("PAP:PDP.putConfig");
2423 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2424 if ((requestId == null) || (requestId == "")) {
2425 UUID requestID = UUID.randomUUID();
2426 loggingContext.setRequestID(requestID.toString());
2427 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2429 loggingContext.setRequestID(requestId);
2430 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2432 loggingContext.transactionStarted();
2433 // the Id of the PDP is its URL
2434 if (LOGGER.isDebugEnabled()) {
2435 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2437 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2438 //TODO (need to change "cache=", implying getting some input saying which to change)
2439 URL url = new URL(pdp.getId() + "?cache=all");
2440 // Open up the connection
2441 connection = (HttpURLConnection)url.openConnection();
2442 // Setup our method and headers
2443 connection.setRequestMethod("PUT");
2445 String encoding = CheckPDP.getEncoding(pdp.getId());
2446 if(encoding !=null){
2447 connection.setRequestProperty("Authorization", "Basic " + encoding);
2449 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2450 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2451 connection.setInstanceFollowRedirects(true);
2452 connection.setDoOutput(true);
2453 try (OutputStream os = connection.getOutputStream()) {
2454 OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp);
2455 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2456 if (group == null) {
2457 // create blank properties files
2458 Properties policyProperties = new Properties();
2459 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2460 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2461 policyProperties.store(os, "");
2462 Properties pipProps = new Properties();
2463 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2464 pipProps.store(os, "");
2466 // send properties from the current group
2467 group.getPolicyProperties().store(os, "");
2468 Properties policyLocations = new Properties();
2469 for (PDPPolicy policy : group.getPolicies()) {
2470 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2472 policyLocations.store(os, "");
2473 group.getPipConfigProperties().store(os, "");
2475 } catch (Exception e) {
2476 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2477 // Since this is a server-side error, it probably does not reflect a problem on the client,
2478 // so do not change the PDP status.
2482 connection.connect();
2483 if (connection.getResponseCode() == 204) {
2484 LOGGER.info("Success. We are configured correctly.");
2485 loggingContext.transactionEnded();
2486 auditLogger.info("Success. PDP is configured correctly.");
2487 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2488 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2489 } else if (connection.getResponseCode() == 200) {
2490 LOGGER.info("Success. PDP needs to update its configuration.");
2491 loggingContext.transactionEnded();
2492 auditLogger.info("Success. PDP needs to update its configuration.");
2493 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2494 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2496 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2497 loggingContext.transactionEnded();
2498 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2499 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2500 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2502 } catch (Exception e) {
2504 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2505 loggingContext.transactionEnded();
2506 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2508 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2509 } catch (PAPException e1) {
2511 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2512 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2515 // cleanup the connection
2516 if(connection != null){
2517 connection.disconnect();
2519 // tell the AC to update it's status info
2526 * RESTful Interface from PAP to ACs notifying them of changes
2528 private void notifyAC() {
2529 // kick off a thread to do one event notification for all registered ACs
2530 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2531 // as part of processing this message on their end.
2532 Thread t = new Thread(new NotifyACThread());
2536 private class NotifyACThread implements Runnable {
2538 List<String> disconnectedACs = new ArrayList<>();
2539 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2540 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2541 for (String acURL : adminConsoleURLStringList) {
2542 HttpURLConnection connection = null;
2544 acURL += "?PAPNotification=true";
2545 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2546 //TODO - If so, put correct parameters into the Query string here
2547 acURL += "&objectType=all" + "&action=update";
2548 if (LOGGER.isDebugEnabled()) {
2549 LOGGER.debug("creating url for id '" + acURL + "'");
2551 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2552 //TODO (need to change "cache=", implying getting some input saying which to change)
2553 URL url = new URL(acURL );
2554 // Open up the connection
2555 connection = (HttpURLConnection)url.openConnection();
2556 // Setup our method and headers
2557 connection.setRequestMethod("PUT");
2558 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2559 // Adding this in. It seems the HttpUrlConnection class does NOT
2560 // properly forward our headers for POST re-direction. It does so
2561 // for a GET re-direction.
2562 // So we need to handle this ourselves.
2563 //TODO - is this needed for a PUT? seems better to leave in for now?
2564 connection.setInstanceFollowRedirects(false);
2565 // Do not include any data in the PUT because this is just a
2566 // notification to the AC.
2567 // The AC will use GETs back to the PAP to get what it needs
2568 // to fill in the screens.
2570 connection.connect();
2571 if (connection.getResponseCode() == 204) {
2572 LOGGER.info("Success. We updated correctly.");
2574 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2577 } catch (Exception e) {
2578 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2579 disconnectedACs.add(acURL);
2581 // cleanup the connection
2582 if(connection != null)
2583 connection.disconnect();
2586 // remove any ACs that are no longer connected
2587 if (disconnectedACs.size() > 0) {
2588 adminConsoleURLStringList.removeAll(disconnectedACs);
2593 private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2594 LOGGER.info("Test request received");
2596 im.evaluateSanity();
2597 //If we make it this far, all is well
2598 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2599 LOGGER.info(message);
2600 loggingContext.transactionEnded();
2601 PolicyLogger.audit("Transaction Failed - See Error.log");
2602 response.setStatus(HttpServletResponse.SC_OK);
2604 }catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e){
2606 if (e instanceof ForwardProgressException) {
2607 submsg = " is not making forward progress.";
2608 } else if (e instanceof AdministrativeStateException) {
2609 submsg = " Administrative State is LOCKED.";
2611 submsg = " Standby Status is NOT PROVIDING SERVICE.";
2614 String message = "GET:/pap/test called and PAP " + papResourceName + submsg
2615 + " Exception Message: " + e.getMessage();
2616 LOGGER.info(message, e);
2617 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2618 loggingContext.transactionEnded();
2619 PolicyLogger.audit("Transaction Failed - See Error.log");
2620 setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2622 }catch (Exception e) {
2623 //A subsystem is not making progress, is locked, standby or is not responding
2624 String eMsg = e.getMessage();
2626 eMsg = "No Exception Message";
2628 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2629 + " Exception Message: " + eMsg;
2630 LOGGER.info(message, e);
2631 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2632 loggingContext.transactionEnded();
2633 PolicyLogger.audit("Transaction Failed - See Error.log");
2634 //Get the specific list of subsystems that failed
2635 String ssFailureList = null;
2636 for(String failedSS : papDependencyGroupsFlatArray){
2637 if(eMsg.contains(failedSS)){
2638 if(ssFailureList == null){
2639 ssFailureList = failedSS;
2641 ssFailureList = ssFailureList.concat(","+failedSS);
2645 if(ssFailureList == null){
2646 ssFailureList = "UnknownSubSystem";
2648 response.addHeader("X-ONAP-SubsystemFailure", ssFailureList);
2649 setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2655 * Authorizing the PEP Requests.
2657 private boolean authorizeRequest(HttpServletRequest request) {
2658 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2659 // Check if the Client is Authorized.
2660 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2667 private static void loadWebapps() throws PAPException{
2668 if(actionHome == null || configHome == null){
2669 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2671 if (webappsPath == null) {
2672 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2673 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2675 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2676 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2677 if (Files.notExists(webappsPathConfig)) {
2679 Files.createDirectories(webappsPathConfig);
2680 } catch (IOException e) {
2681 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Failed to create config directory: "
2682 + webappsPathConfig.toAbsolutePath().toString());
2685 if (Files.notExists(webappsPathAction)) {
2687 Files.createDirectories(webappsPathAction);
2688 } catch (IOException e) {
2689 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
2690 + webappsPathAction.toAbsolutePath().toString(), e);
2693 actionHome = webappsPathAction.toString();
2694 configHome = webappsPathConfig.toString();
2698 public static String getConfigHome(){
2701 } catch (PAPException e) {
2708 private static void setConfigHome(){
2709 configHome = getConfigHome();
2712 public static String getActionHome(){
2715 } catch (PAPException e) {
2722 private static void setActionHome(){
2723 actionHome = getActionHome();
2726 public static EntityManagerFactory getEmf() {
2730 public IntegrityAudit getIa() {
2734 public static String getPDPFile(){
2735 return XACMLPapServlet.pdpFile;
2738 public static String getPersistenceUnit(){
2739 return PERSISTENCE_UNIT;
2742 public static PAPPolicyEngine getPAPEngine(){
2746 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2747 return policyDBDao.getNewTransaction();
2749 public static String getPapDbDriver() {
2753 public static void setPapDbDriver(String papDbDriver) {
2754 XACMLPapServlet.papDbDriver = papDbDriver;
2757 public static String getPapDbUrl() {
2761 public static void setPapDbUrl(String papDbUrl) {
2762 XACMLPapServlet.papDbUrl = papDbUrl;
2765 public static String getPapDbUser() {
2769 public static void setPapDbUser(String papDbUser) {
2770 XACMLPapServlet.papDbUser = papDbUser;
2773 public static String getPapDbPassword() {
2774 return papDbPassword;
2777 public static void setPapDbPassword(String papDbPassword) {
2778 XACMLPapServlet.papDbPassword = papDbPassword;
2781 public static String getMsOnapName() {
2785 public static void setMsOnapName(String msOnapName) {
2786 XACMLPapServlet.msOnapName = msOnapName;
2789 public static String getMsPolicyName() {
2790 return msPolicyName;
2793 public static void setMsPolicyName(String msPolicyName) {
2794 XACMLPapServlet.msPolicyName = msPolicyName;