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.openecomp.policy.pap.xacml.rest;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.UnsupportedEncodingException;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.InetAddress;
32 import java.net.MalformedURLException;
33 import java.net.SocketTimeoutException;
35 import java.net.URLDecoder;
36 import java.net.UnknownHostException;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Properties;
47 import java.util.UUID;
48 import java.util.concurrent.CopyOnWriteArrayList;
50 import javax.persistence.EntityManagerFactory;
51 import javax.persistence.Persistence;
52 import javax.persistence.PersistenceException;
53 import javax.servlet.Servlet;
54 import javax.servlet.ServletConfig;
55 import javax.servlet.ServletException;
56 import javax.servlet.annotation.WebInitParam;
57 import javax.servlet.annotation.WebServlet;
58 import javax.servlet.http.HttpServlet;
59 import javax.servlet.http.HttpServletRequest;
60 import javax.servlet.http.HttpServletResponse;
62 import org.apache.commons.io.IOUtils;
63 import org.openecomp.policy.common.ia.IntegrityAudit;
64 import org.openecomp.policy.common.im.AdministrativeStateException;
65 import org.openecomp.policy.common.im.ForwardProgressException;
66 import org.openecomp.policy.common.im.IntegrityMonitor;
67 import org.openecomp.policy.common.im.IntegrityMonitorProperties;
68 import org.openecomp.policy.common.im.StandbyStatusException;
69 import org.openecomp.policy.common.logging.ECOMPLoggingContext;
70 import org.openecomp.policy.common.logging.ECOMPLoggingUtils;
71 import org.openecomp.policy.common.logging.eelf.MessageCodes;
72 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
73 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
74 import org.openecomp.policy.common.logging.flexlogger.Logger;
75 import org.openecomp.policy.pap.xacml.rest.components.AutoPushPolicy;
76 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao;
77 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
78 import org.openecomp.policy.pap.xacml.rest.handler.APIRequestHandler;
79 import org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler;
80 import org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler;
81 import org.openecomp.policy.pap.xacml.restAuth.CheckPDP;
82 import org.openecomp.policy.rest.XACMLRest;
83 import org.openecomp.policy.rest.XACMLRestProperties;
84 import org.openecomp.policy.utils.PolicyUtils;
85 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
86 import org.openecomp.policy.xacml.api.pap.ECOMPPapEngineFactory;
87 import org.openecomp.policy.xacml.api.pap.EcompPDP;
88 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
89 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
90 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
91 import org.openecomp.policy.xacml.std.pap.StdPDP;
92 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
93 import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
94 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
95 import org.openecomp.policy.xacml.std.pap.StdPDPStatus;
97 import com.att.research.xacml.api.pap.PAPException;
98 import com.att.research.xacml.api.pap.PDPPolicy;
99 import com.att.research.xacml.api.pap.PDPStatus;
100 import com.att.research.xacml.util.FactoryException;
101 import com.att.research.xacml.util.XACMLProperties;
102 import com.fasterxml.jackson.databind.ObjectMapper;
103 import com.google.common.base.Splitter;
106 * Servlet implementation class XacmlPapServlet
109 description = "Implements the XACML PAP RESTful API.",
110 urlPatterns = { "/" },
113 @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
115 public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
116 private static final long serialVersionUID = 1L;
117 private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class);
118 // audit (transaction) LOGGER
119 private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
120 //Persistence Unit for JPA
121 private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
122 private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
124 private static final String ENVIRONMENT_HEADER = "Environment";
126 * List of Admin Console URLs.
127 * Used to send notifications when configuration changes.
129 * The CopyOnWriteArrayList *should* protect from concurrency errors.
130 * This list is seldom changed but often read, so the costs of this approach make sense.
132 private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<String>();
134 private static String CONFIG_HOME;
135 private static String ACTION_HOME;
137 * This PAP instance's own URL.
138 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process.
140 private static String papURL = null;
141 // The heartbeat thread.
142 private static Heartbeat heartbeat = null;
143 private static Thread heartbeatThread = null;
144 //The entity manager factory for JPA access
145 private static EntityManagerFactory emf;
146 private static PolicyDBDao policyDBDao;
148 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
150 private static PAPPolicyEngine papEngine = null;
152 * These are the parameters needed for DB access from the PAP
154 private static int papIntegrityAuditPeriodSeconds = -1;
155 public static String papDbDriver = null;
156 public static String papDbUrl = null;
157 public static String papDbUser = null;
158 public static String papDbPassword = null;
159 private static Integer papTransWait = null;
160 private static Integer papTransTimeout = null;
161 private static Integer papAuditTimeout = null;
162 private static Boolean papAuditFlag = null;
163 private static Boolean papFileSystemAudit = null;
164 private static Boolean autoPushFlag = false;
165 private static String papResourceName = null;
166 private static Integer fpMonitorInterval = null;
167 private static Integer failedCounterThreshold = null;
168 private static Integer testTransInterval = null;
169 private static Integer writeFpcInterval = null;
170 private static String papSiteName=null;
171 private static String papNodeType=null;
172 private static String papDependencyGroups = null;
173 private static String[] papDependencyGroupsFlatArray = null;
174 private static String environment = null;
175 private static String pdpFile = null;
177 private String storedRequestId = null;
178 private IntegrityMonitor im;
179 private IntegrityAudit ia;
181 //MicroService Model Properties
182 public static String msEcompName;
183 public static String msPolicyName;
185 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
186 * this servlet starts. Its configurable by the admin.
188 private Thread initiateThread = null;
189 private ECOMPLoggingContext baseLoggingContext = null;
190 private AutoPushPolicy autoPushPolicy;
193 * @see HttpServlet#HttpServlet()
195 public XACMLPapServlet() {
200 * @see Servlet#init(ServletConfig)
202 public void init(ServletConfig config) throws ServletException {
205 baseLoggingContext = new ECOMPLoggingContext();
206 // fixed data that will be the same in all logging output goes here
208 String hostname = InetAddress.getLocalHost().getCanonicalHostName();
209 baseLoggingContext.setServer(hostname);
210 } catch (UnknownHostException e) {
211 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging");
214 XACMLRest.xacmlInit(config);
215 // Load the properties
216 XACMLRest.loadXacmlProperties(null, null);
218 * Retrieve the property values
220 CONFIG_HOME = getConfigHome();
221 ACTION_HOME = getActionHome();
222 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
223 if(papDbDriver == null){
224 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
225 throw new PAPException("papDbDriver is null");
227 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
228 if(papDbUrl == null){
229 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
230 throw new PAPException("papDbUrl is null");
232 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
233 if(papDbUser == null){
234 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
235 throw new PAPException("papDbUser is null");
237 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
238 if(papDbPassword == null){
239 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
240 throw new PAPException("papDbPassword is null");
242 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
243 if(papResourceName == null){
244 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
245 throw new PAPException("papResourceName is null");
247 papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
248 if(papSiteName == null){
249 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
250 throw new PAPException("papSiteName is null");
252 papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
253 if(papNodeType == null){
254 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
255 throw new PAPException("papNodeType is null");
257 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
258 //Integer will throw an exception of anything is missing or unrecognized
259 papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
260 papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
261 papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
262 //Boolean will default to false if anything is missing or unrecognized
263 papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
264 papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
266 autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG));
267 // if Auto push then Load with properties.
271 file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE);
272 if(file.endsWith(".properties")){
273 autoPushPolicy = new AutoPushPolicy(file);
275 throw new PAPException();
278 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE );
279 LOGGER.info("Overriding the autoPushFlag to False...");
280 autoPushFlag = false;
283 papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
284 if(papDependencyGroups == null){
285 throw new PAPException("papDependencyGroups is null");
288 //Now we have flattened the array into a simple comma-separated list
289 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
290 //clean up the entries
291 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
292 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
295 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
296 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
299 String msg = "integrity_audit_period_seconds ";
300 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
301 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
305 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
308 //Integer will throw an exception of anything is missing or unrecognized
309 fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
310 failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
311 testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
312 writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
313 LOGGER.debug("\n\n\n**************************************"
314 + "\n**************************************"
316 + "\n papDbDriver = " + papDbDriver
317 + "\n papDbUrl = " + papDbUrl
318 + "\n papDbUser = " + papDbUser
319 + "\n papDbPassword = " + papDbPassword
320 + "\n papTransWait = " + papTransWait
321 + "\n papTransTimeout = " + papTransTimeout
322 + "\n papAuditTimeout = " + papAuditTimeout
323 + "\n papAuditFlag = " + papAuditFlag
324 + "\n papFileSystemAudit = " + papFileSystemAudit
325 + "\n autoPushFlag = " + autoPushFlag
326 + "\n papResourceName = " + papResourceName
327 + "\n fpMonitorInterval = " + fpMonitorInterval
328 + "\n failedCounterThreshold = " + failedCounterThreshold
329 + "\n testTransInterval = " + testTransInterval
330 + "\n writeFpcInterval = " + writeFpcInterval
331 + "\n papSiteName = " + papSiteName
332 + "\n papNodeType = " + papNodeType
333 + "\n papDependencyGroupsList = " + papDependencyGroups
334 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
335 + "\n\n**************************************"
336 + "\n**************************************");
337 // Pull custom persistence settings
338 Properties properties;
340 properties = XACMLProperties.getProperties();
341 LOGGER.debug("\n\n\n**************************************"
342 + "\n**************************************"
344 + "properties = " + properties
345 + "\n\n**************************************");
346 } catch (IOException e) {
347 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
348 + "XACMLProperties.getProperties()");
349 throw new ServletException(e.getMessage(), e.getCause());
351 //Micro Service Properties
352 msEcompName=properties.getProperty("xacml.policy.msEcompName");
353 msPolicyName=properties.getProperty("xacml.policy.msPolicyName");
354 // PDPId File location
355 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
356 if (XACMLPapServlet.pdpFile == null) {
357 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
358 + XACMLRestProperties.PROP_PDP_IDFILE);
359 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
361 // Create an IntegrityMonitor
362 im = IntegrityMonitor.getInstance(papResourceName,properties);
363 // Create an IntegrityAudit
364 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
365 ia.startAuditThread();
366 // Create the entity manager factory
367 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
369 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
371 throw new ServletException("Unable to create Entity Manager Factory");
373 // we are about to call the PDPs and give them their configuration.
374 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
375 XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
376 //Create the policyDBDao
377 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
378 // Load our PAP engine, first create a factory
379 ECOMPPapEngineFactory factory = ECOMPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
380 // The factory knows how to go about creating a PAP Engine
381 XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine();
382 PolicyDBDaoTransaction addNewGroup = null;
384 if(((org.openecomp.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){
385 addNewGroup = policyDBDao.getNewTransaction();
386 EcompPDPGroup group = papEngine.getDefaultGroup();
387 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
388 addNewGroup.commitTransaction();
389 addNewGroup = policyDBDao.getNewTransaction();
390 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
391 addNewGroup.commitTransaction();
393 } catch(Exception e){
394 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database");
395 if(addNewGroup != null){
396 addNewGroup.rollbackTransaction();
399 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
400 // Sanity check for URL.
401 if (XACMLPapServlet.papURL == null) {
402 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
404 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
405 // to all its known PDP nodes.
406 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
407 this.initiateThread = new Thread(this);
408 this.initiateThread.start();
410 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
411 XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine);
412 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
413 XACMLPapServlet.heartbeatThread.start();
415 } catch (FactoryException | PAPException e) {
416 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
417 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
418 } catch (Exception e) {
419 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
420 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
425 * Thread used only during PAP startup to initiate change messages to all known PDPs.
426 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
430 // send the current configuration to all the PDPs that we know about
435 * @see Servlet#destroy()
437 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
438 * For now we assume that we do care.
440 public void destroy() {
441 // Make sure our threads are destroyed
442 if (XACMLPapServlet.heartbeatThread != null) {
443 // stop the heartbeat
445 if (XACMLPapServlet.heartbeat != null) {
446 XACMLPapServlet.heartbeat.terminate();
448 XACMLPapServlet.heartbeatThread.interrupt();
449 XACMLPapServlet.heartbeatThread.join();
450 } catch (InterruptedException e) {
451 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
454 if (this.initiateThread != null) {
456 this.initiateThread.interrupt();
457 this.initiateThread.join();
458 } catch (InterruptedException e) {
459 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
466 * - PDP nodes to register themselves with the PAP, and
467 * - Admin Console to make changes in the PDP Groups.
469 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
471 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
472 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
473 loggingContext.transactionStarted();
474 loggingContext.setServiceName("PAP.post");
475 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
476 UUID requestID = UUID.randomUUID();
477 loggingContext.setRequestID(requestID.toString());
478 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
480 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
482 PolicyDBDaoTransaction pdpTransaction = null;
484 im.startTransaction();
485 } catch (AdministrativeStateException ae){
486 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
487 + " state of " + im.getStateManager().getAdminState()
488 + "\n Exception Message: " + ae.getMessage();
489 LOGGER.info(message);
490 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
491 loggingContext.transactionEnded();
492 PolicyLogger.audit("Transaction Failed - See Error.log");
493 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
495 }catch (StandbyStatusException se) {
496 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
497 + " of " + im.getStateManager().getStandbyStatus()
498 + "\n Exception Message: " + se.getMessage();
499 LOGGER.info(message);
500 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
501 loggingContext.transactionEnded();
502 PolicyLogger.audit("Transaction Failed - See Error.log");
503 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
507 XACMLRest.dumpRequest(request);
508 // since getParameter reads the content string, explicitly get the content before doing that.
509 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
510 request.getInputStream();
511 String groupId = request.getParameter("groupId");
512 String apiflag = request.getParameter("apiflag");
513 if(groupId != null) {
514 // Is this from the Admin Console or API?
515 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
516 // this is from the API so we need to check the client credentials before processing the request
517 if(!authorizeRequest(request)){
518 String message = "PEP not Authorized for making this Request!!";
519 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
520 loggingContext.transactionEnded();
521 PolicyLogger.audit("Transaction Failed - See Error.log");
522 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
527 doACPost(request, response, groupId, loggingContext);
528 loggingContext.transactionEnded();
529 PolicyLogger.audit("Transaction Ended Successfully");
533 // Request is from a PDP asking for its config.
534 loggingContext.setServiceName("PDP:PAP.register");
536 String id = this.getPDPID(request);
537 String jmxport = this.getPDPJMX(request);
538 LOGGER.info("Request(doPost) from PDP coming up: " + id);
539 // Get the PDP Object
540 EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
543 LOGGER.info("Unknown PDP: " + id);
545 if(CheckPDP.validateID(id)){
546 pdpTransaction = policyDBDao.getNewTransaction();
548 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
549 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
550 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) {
551 pdpTransaction.rollbackTransaction();
552 String message = "Failed to create new PDP for id: " + id;
553 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
554 loggingContext.transactionEnded();
555 PolicyLogger.audit("Transaction Failed - See Error.log");
556 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
560 // get the PDP we just created
561 pdp = XACMLPapServlet.papEngine.getPDP(id);
563 if(pdpTransaction != null){
564 pdpTransaction.rollbackTransaction();
566 String message = "Failed to create new PDP for id: " + id;
567 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
568 loggingContext.transactionEnded();
569 PolicyLogger.audit("Transaction Failed - See Error.log");
570 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
575 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
576 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
577 loggingContext.transactionEnded();
578 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
579 PolicyLogger.audit("Transaction Failed - See Error.log");
584 pdpTransaction.commitTransaction();
585 } catch(Exception e){
586 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
589 if (jmxport != null && jmxport != ""){
590 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
592 // Get the PDP's Group
593 EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp);
595 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
596 loggingContext.transactionEnded();
597 PolicyLogger.audit("Transaction Failed - See Error.log");
598 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
602 // Determine what group the PDP node is in and get
603 // its policy/pip properties.
604 Properties policies = group.getPolicyProperties();
605 Properties pipconfig = group.getPipConfigProperties();
606 // Get the current policy/pip configuration that the PDP has
607 Properties pdpProperties = new Properties();
608 pdpProperties.load(request.getInputStream());
609 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
610 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
611 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
612 // Validate the node's properties
613 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
614 // Send back current configuration
615 if (isCurrent == false) {
616 // Tell the PDP we are sending back the current policies/pip config
617 LOGGER.info("PDP configuration NOT current.");
618 if (policies != null) {
619 // Put URL's into the properties in case the PDP needs to
621 this.populatePolicyURL(request.getRequestURL(), policies);
622 // Copy the properties to the output stream
623 policies.store(response.getOutputStream(), "");
625 if (pipconfig != null) {
626 // Copy the properties to the output stream
627 pipconfig.store(response.getOutputStream(), "");
629 // We are good - and we are sending them information
630 response.setStatus(HttpServletResponse.SC_OK);
631 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
633 // Tell them they are good
634 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
635 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
637 // tell the AC that something changed
639 loggingContext.transactionEnded();
640 auditLogger.info("Success");
641 PolicyLogger.audit("Transaction Ended Successfully");
642 } catch (PAPException e) {
643 if(pdpTransaction != null){
644 pdpTransaction.rollbackTransaction();
646 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
647 loggingContext.transactionEnded();
648 PolicyLogger.audit("Transaction Failed - See Error.log");
649 response.sendError(500, e.getMessage());
653 //Catch anything that fell through
654 loggingContext.transactionEnded();
655 PolicyLogger.audit("Transaction Ended");
660 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
662 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
663 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
664 loggingContext.transactionStarted();
665 loggingContext.setServiceName("PAP.get");
666 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
667 UUID requestID = UUID.randomUUID();
668 loggingContext.setRequestID(requestID.toString());
669 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
671 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
674 XACMLRest.dumpRequest(request);
675 String pathInfo = request.getRequestURI();
676 LOGGER.info("path info: " + pathInfo);
677 if (pathInfo != null){
678 //DO NOT do a im.startTransaction for the test request
679 if (pathInfo.equals("/pap/test")) {
680 testService(loggingContext, response);
684 //This im.startTransaction() covers all other Get transactions
686 im.startTransaction();
687 } catch (AdministrativeStateException ae){
688 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
689 + " state of " + im.getStateManager().getAdminState()
690 + "\n Exception Message: " + ae.getMessage();
691 LOGGER.info(message);
692 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
693 loggingContext.transactionEnded();
694 PolicyLogger.audit("Transaction Failed - See Error.log");
695 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
697 }catch (StandbyStatusException se) {
698 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
699 + " of " + im.getStateManager().getStandbyStatus()
700 + "\n Exception Message: " + se.getMessage();
701 LOGGER.info(message);
702 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
703 loggingContext.transactionEnded();
704 PolicyLogger.audit("Transaction Failed - See Error.log");
705 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
708 // Request from the API to get the gitPath
709 String apiflag = request.getParameter("apiflag");
711 if(authorizeRequest(request)){
712 APIRequestHandler apiRequestHandler = new APIRequestHandler();
713 apiRequestHandler.doGet(request,response, apiflag);
714 loggingContext.transactionEnded();
715 PolicyLogger.audit("Transaction Ended Successfully");
719 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
720 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
721 loggingContext.transactionEnded();
722 PolicyLogger.audit("Transaction Failed - See Error.log");
723 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
728 // Is this from the Admin Console?
729 String groupId = request.getParameter("groupId");
730 if (groupId != null) {
731 // this is from the Admin Console, so handle separately
732 doACGet(request, response, groupId, loggingContext);
733 loggingContext.transactionEnded();
734 PolicyLogger.audit("Transaction Ended Successfully");
739 String id = this.getPDPID(request);
740 LOGGER.info("doGet from: " + id);
741 // Get the PDP Object
742 EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
745 // Check if request came from localhost
746 if (request.getRemoteHost().equals("localhost") ||
747 request.getRemoteHost().equals("127.0.0.1") ||
748 request.getRemoteHost().equals(request.getLocalAddr())) {
749 // Return status information - basically all the groups
750 loggingContext.setServiceName("PAP.getGroups");
751 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
752 // convert response object to JSON and include in the response
753 ObjectMapper mapper = new ObjectMapper();
754 mapper.writeValue(response.getOutputStream(), groups);
755 response.setHeader("content-type", "application/json");
756 response.setStatus(HttpServletResponse.SC_OK);
757 loggingContext.transactionEnded();
758 PolicyLogger.audit("Transaction Ended Successfully");
762 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
763 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
764 loggingContext.transactionEnded();
765 PolicyLogger.audit("Transaction Failed - See Error.log");
766 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
770 loggingContext.setServiceName("PAP.getPolicy");
771 // Get the PDP's Group
772 EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp);
774 String message = "No group associated with pdp " + pdp.getId();
775 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
776 loggingContext.transactionEnded();
777 PolicyLogger.audit("Transaction Failed - See Error.log");
778 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
782 // Which policy do they want?
783 String policyId = request.getParameter("id");
784 if (policyId == null) {
785 String message = "Did not specify an id for the policy";
786 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
787 loggingContext.transactionEnded();
788 PolicyLogger.audit("Transaction Failed - See Error.log");
789 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
793 PDPPolicy policy = group.getPolicy(policyId);
794 if (policy == null) {
795 String message = "Unknown policy: " + policyId;
796 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
797 loggingContext.transactionEnded();
798 PolicyLogger.audit("Transaction Failed - See Error.log");
799 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
803 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
804 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
805 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
806 // Send the policy back
807 IOUtils.copy(is, os);
808 response.setStatus(HttpServletResponse.SC_OK);
809 loggingContext.transactionEnded();
810 auditLogger.info("Success");
811 PolicyLogger.audit("Transaction Ended Successfully");
812 } catch (IOException e) {
813 String message = "Failed to open policy id " + policyId;
814 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
815 loggingContext.transactionEnded();
816 PolicyLogger.audit("Transaction Failed - See Error.log");
817 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
819 } catch (PAPException e) {
820 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
821 loggingContext.transactionEnded();
822 PolicyLogger.audit("Transaction Failed - See Error.log");
823 response.sendError(500, e.getMessage());
827 loggingContext.transactionEnded();
828 PolicyLogger.audit("Transaction Ended");
833 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
835 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
836 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
837 storedRequestId = loggingContext.getRequestID();
838 loggingContext.transactionStarted();
839 loggingContext.setServiceName("PAP.put");
840 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
841 UUID requestID = UUID.randomUUID();
842 loggingContext.setRequestID(requestID.toString());
843 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
845 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
848 im.startTransaction();
849 } catch (AdministrativeStateException ae){
850 String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative"
851 + " state of " + im.getStateManager().getAdminState()
852 + "\n Exception Message: " + ae.getMessage();
853 LOGGER.info(message);
854 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
855 loggingContext.transactionEnded();
856 PolicyLogger.audit("Transaction Failed - See Error.log");
857 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
859 }catch (StandbyStatusException se) {
860 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
861 + " of " + im.getStateManager().getStandbyStatus()
862 + "\n Exception Message: " + se.getMessage();
863 LOGGER.info(message);
864 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
865 loggingContext.transactionEnded();
866 PolicyLogger.audit("Transaction Failed - See Error.log");
867 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
870 XACMLRest.dumpRequest(request);
871 //need to check if request is from the API or Admin console
872 String apiflag = request.getParameter("apiflag");
873 //This would occur if a PolicyDBDao notification was received
874 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
875 if(policyDBDaoRequestUrl != null){
876 String policyDBDaoRequestEntityId = request.getParameter("entityid");
877 //String policyDBDaoRequestEntityType = request.getParameter("entitytype");
878 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
879 String policyDBDaoRequestExtraData = request.getParameter("extradata");
880 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
881 response.sendError(400, "entityid or entitytype not supplied");
882 loggingContext.transactionEnded();
883 PolicyLogger.audit("Transaction Ended Successfully");
887 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
888 response.setStatus(200);
889 loggingContext.transactionEnded();
890 PolicyLogger.audit("Transaction Ended Successfully");
894 //This would occur if we received a notification of a policy creation or update
895 String policyToCreateUpdate = request.getParameter("policyToCreateUpdate");
896 if(policyToCreateUpdate != null){
897 if(LOGGER.isDebugEnabled()){
898 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
899 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
903 policyToCreateUpdate = URLDecoder.decode(policyToCreateUpdate, "UTF-8");
904 if(LOGGER.isDebugEnabled()){
905 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
906 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
908 } catch(UnsupportedEncodingException e){
909 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
910 + "\npolicyToCreateUpdate = " + policyToCreateUpdate);
911 response.sendError(500,"policyToCreateUpdate encoding not supported"
912 + "\nfailure with the following exception: " + e);
913 loggingContext.transactionEnded();
914 PolicyLogger.audit("Transaction Failed - See error.log");
918 //send it to PolicyDBDao
919 PolicyDBDaoTransaction createUpdateTransaction = policyDBDao.getNewTransaction();
921 createUpdateTransaction.createPolicy(policyToCreateUpdate, "XACMLPapServlet.doPut");
923 createUpdateTransaction.rollbackTransaction();
924 response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
925 + "\nfailure with the following exception: " + e);
926 loggingContext.transactionEnded();
927 PolicyLogger.audit("Transaction Failed - See error.log");
931 createUpdateTransaction.commitTransaction();
932 // Before sending Ok. Lets call AutoPush.
934 Set<StdPDPGroup> changedGroups = autoPushPolicy.checkGroupsToPush(policyToCreateUpdate, XACMLPapServlet.papEngine);
935 if(!changedGroups.isEmpty()){
936 for(StdPDPGroup group: changedGroups){
938 papEngine.updateGroup(group);
939 if (LOGGER.isDebugEnabled()) {
940 LOGGER.debug("Group '" + group.getId() + "' updated");
943 // Group changed, which might include changing the policies
946 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Failed to Push policy. ");
951 response.setStatus(HttpServletResponse.SC_OK);
952 loggingContext.transactionEnded();
953 PolicyLogger.audit("Transaction Ended Successfully");
958 * Request for ImportService
960 String importService = request.getParameter("importService");
961 if (importService != null) {
962 if(authorizeRequest(request)){
963 APIRequestHandler apiRequestHandler = new APIRequestHandler();
964 apiRequestHandler.doPut(request, response, importService);
968 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
969 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
970 loggingContext.transactionEnded();
971 PolicyLogger.audit("Transaction Failed - See Error.log");
972 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
976 //This would occur if we received a notification of a policy rename from AC
977 String oldPolicyName = request.getParameter("oldPolicyName");
978 String newPolicyName = request.getParameter("newPolicyName");
979 if(oldPolicyName != null && newPolicyName != null){
980 if(LOGGER.isDebugEnabled()){
981 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
982 + "\npolicyToCreateUpdate = " + " ");
986 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
987 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
988 if(LOGGER.isDebugEnabled()){
989 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
990 + "\npolicyToCreateUpdate = " + " ");
992 } catch(UnsupportedEncodingException e){
993 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
994 + "\npolicyToCreateUpdate = " + " ");
995 response.sendError(500,"policyToCreateUpdate encoding not supported"
996 + "\nfailure with the following exception: " + e);
997 loggingContext.transactionEnded();
998 PolicyLogger.audit("Transaction Failed - See error.log");
1002 //send it to PolicyDBDao
1003 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
1005 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
1006 }catch(Exception e){
1007 renameTransaction.rollbackTransaction();
1008 response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
1009 + "\nfailure with the following exception: " + e);
1010 loggingContext.transactionEnded();
1011 PolicyLogger.audit("Transaction Failed - See error.log");
1012 im.endTransaction();
1015 renameTransaction.commitTransaction();
1016 response.setStatus(HttpServletResponse.SC_OK);
1017 loggingContext.transactionEnded();
1018 PolicyLogger.audit("Transaction Ended Successfully");
1019 im.endTransaction();
1023 // See if this is Admin Console registering itself with us
1025 String acURLString = request.getParameter("adminConsoleURL");
1026 if (acURLString != null) {
1027 loggingContext.setServiceName("AC:PAP.register");
1028 // remember this Admin Console for future updates
1029 if ( ! adminConsoleURLStringList.contains(acURLString)) {
1030 adminConsoleURLStringList.add(acURLString);
1032 if (LOGGER.isDebugEnabled()) {
1033 LOGGER.debug("Admin Console registering with URL: " + acURLString);
1035 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1036 loggingContext.transactionEnded();
1037 auditLogger.info("Success");
1038 PolicyLogger.audit("Transaction Ended Successfully");
1039 im.endTransaction();
1043 * This is to update the PDP Group with the policy/policies being pushed
1044 * Part of a 2 step process to push policies to the PDP that can now be done
1045 * From both the Admin Console and the PolicyEngine API
1047 String groupId = request.getParameter("groupId");
1048 if (groupId != null) {
1050 if(!authorizeRequest(request)){
1051 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1052 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1053 loggingContext.transactionEnded();
1054 PolicyLogger.audit("Transaction Failed - See Error.log");
1055 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1058 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1059 updateGroupsFromAPI(request, response, groupId, loggingContext);
1060 loggingContext.transactionEnded();
1061 PolicyLogger.audit("Transaction Ended Successfully");
1062 im.endTransaction();
1066 // this is from the Admin Console, so handle separately
1067 doACPut(request, response, groupId, loggingContext);
1068 loggingContext.transactionEnded();
1069 PolicyLogger.audit("Transaction Ended Successfully");
1070 im.endTransaction();
1074 // Request is for policy validation and creation
1076 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1077 // this request is from the Admin Console
1078 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1079 savePolicyHandler.doPolicyAPIPut(request, response);
1080 loggingContext.transactionEnded();
1081 PolicyLogger.audit("Transaction Ended Successfully");
1082 im.endTransaction();
1084 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1085 // this request is from the Policy Creation API
1086 if(authorizeRequest(request)){
1087 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1088 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1089 loggingContext.transactionEnded();
1090 PolicyLogger.audit("Transaction Ended Successfully");
1091 im.endTransaction();
1094 String message = "PEP not Authorized for making this Request!!";
1095 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1096 loggingContext.transactionEnded();
1097 PolicyLogger.audit("Transaction Failed - See Error.log");
1098 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1099 im.endTransaction();
1103 // We do not expect anything from anywhere else.
1104 // This method is here in case we ever need to support other operations.
1105 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1106 loggingContext.transactionEnded();
1107 PolicyLogger.audit("Transaction Failed - See Error.log");
1108 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1109 loggingContext.transactionEnded();
1110 PolicyLogger.audit("Transaction Failed - See error.log");
1111 im.endTransaction();
1115 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1117 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1118 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1119 loggingContext.transactionStarted();
1120 loggingContext.setServiceName("PAP.delete");
1121 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1122 UUID requestID = UUID.randomUUID();
1123 loggingContext.setRequestID(requestID.toString());
1124 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1126 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1129 im.startTransaction();
1130 } catch (AdministrativeStateException ae){
1131 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1132 + " state of " + im.getStateManager().getAdminState()
1133 + "\n Exception Message: " + ae.getMessage();
1134 LOGGER.info(message);
1135 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1136 loggingContext.transactionEnded();
1137 PolicyLogger.audit("Transaction Failed - See Error.log");
1138 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1140 }catch (StandbyStatusException se) {
1141 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1142 + " of " + im.getStateManager().getStandbyStatus()
1143 + "\n Exception Message: " + se.getMessage();
1144 LOGGER.info(message);
1145 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1146 loggingContext.transactionEnded();
1147 PolicyLogger.audit("Transaction Failed - See Error.log");
1148 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1151 XACMLRest.dumpRequest(request);
1152 String groupId = request.getParameter("groupId");
1153 String apiflag = request.getParameter("apiflag");
1154 if (groupId != null) {
1155 // Is this from the Admin Console or API?
1157 if(!authorizeRequest(request)){
1158 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1159 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1160 loggingContext.transactionEnded();
1161 PolicyLogger.audit("Transaction Failed - See Error.log");
1162 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1165 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1167 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1168 } catch (Exception e) {
1169 LOGGER.error("Exception Occured"+e);
1171 if(apiRequestHandler.getNewGroup()!=null){
1172 groupChanged(apiRequestHandler.getNewGroup());
1176 // this is from the Admin Console, so handle separately
1177 doACDelete(request, response, groupId, loggingContext);
1178 loggingContext.transactionEnded();
1179 PolicyLogger.audit("Transaction Ended Successfully");
1180 im.endTransaction();
1183 //Catch anything that fell through
1184 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1185 loggingContext.transactionEnded();
1186 PolicyLogger.audit("Transaction Failed - See Error.log");
1187 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1188 im.endTransaction();
1191 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1192 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1193 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1194 if (localRootPolicies == null || localReferencedPolicies == null) {
1195 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1198 // Compare the policies and pipconfig properties to the pdpProperties
1200 // the policy properties includes only xacml.rootPolicies and
1201 // xacml.referencedPolicies without any .url entries
1202 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1203 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1204 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1205 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1206 pdpPipConfig.equals(pipconfig)) {
1207 // The PDP is current
1210 } catch (Exception e) {
1211 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1212 // or if there are policies that do not have a corresponding ".url" property.
1213 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1214 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1219 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1220 String lists[] = new String[2];
1221 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1222 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1223 for (String list : lists) {
1224 if (list != null && list.isEmpty() == false) {
1225 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1226 String url = urlPath + "?id=" + id;
1227 LOGGER.info("Policy URL for " + id + ": " + url);
1228 policies.setProperty(id + ".url", url);
1234 protected String getPDPID(HttpServletRequest request) {
1235 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1236 if (pdpURL == null || pdpURL.isEmpty()) {
1237 // Should send back its port for identification
1238 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1244 protected String getPDPJMX(HttpServletRequest request) {
1245 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1246 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1247 // Should send back its port for identification
1248 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1255 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1260 * @param loggingContext
1261 * @throws ServletException
1262 * @throws IOException
1264 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws IOException {
1265 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1267 // for PUT operations the group may or may not need to exist before the operation can be done
1268 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1269 // get the request input stream content into a String
1271 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1272 scanner.useDelimiter("\\A");
1273 json = scanner.hasNext() ? scanner.next() : "";
1275 PolicyLogger.info("JSON request from PolicyEngine API: " + json);
1276 // convert Object sent as JSON into local object
1277 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1278 Set<PDPPolicy> policies = new HashSet<>();
1280 policies.add(policy);
1282 //Get the current policies from the Group and Add the new one
1283 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1284 currentPoliciesInGroup = group.getPolicies();
1285 //If the selected policy is in the group we must remove it because the name is default
1286 Iterator<PDPPolicy> policyIterator = policies.iterator();
1287 LOGGER.debug("policyIterator....." + policies);
1288 while (policyIterator.hasNext()) {
1289 PDPPolicy selPolicy = policyIterator.next();
1290 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
1291 if (existingPolicy.getId().equals(selPolicy.getId())) {
1292 group.removePolicyFromGroup(existingPolicy);
1293 LOGGER.debug("Removing policy: " + existingPolicy);
1298 //Update the PDP Group after removing old version of policy
1299 Set<PDPPolicy> updatedPoliciesInGroup = new HashSet<>();
1300 updatedPoliciesInGroup = group.getPolicies();
1301 //need to remove the policy with default name from group
1302 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
1303 if (updatedPolicy.getName().equalsIgnoreCase("default")) {
1304 group.removePolicyFromGroup(updatedPolicy);
1308 if(updatedPoliciesInGroup!=null){
1309 policies.addAll(updatedPoliciesInGroup);
1311 group.setPolicies(policies);
1312 // Assume that this is an update of an existing PDP Group
1313 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1315 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1316 } catch(Exception e){
1317 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1318 +"group="+group.getId());
1319 throw new PAPException(e.getMessage());
1321 papEngine.updateGroup(group);
1322 String policyId = "empty";
1324 policyId = policy.getId();
1326 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1327 response.addHeader("operation", "push");
1328 response.addHeader("policyId", policyId);
1329 response.addHeader("groupId", groupId);
1330 if (LOGGER.isDebugEnabled()) {
1331 LOGGER.debug("Group '" + group.getId() + "' updated");
1333 acPutTransaction.commitTransaction();
1335 // Group changed, which might include changing the policies
1336 groupChanged(group);
1337 loggingContext.transactionEnded();
1338 auditLogger.info("Success");
1340 if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
1341 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1342 if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) {
1343 LOGGER.debug("Precheck Successful.");
1347 PolicyLogger.audit("Transaction Ended Successfully");
1349 } catch (PAPException e) {
1350 acPutTransaction.rollbackTransaction();
1351 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1352 loggingContext.transactionEnded();
1353 PolicyLogger.audit("Transaction Failed - See Error.log");
1354 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1355 response.sendError(500, e.getMessage());
1356 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1357 response.addHeader("error","addGroupError");
1358 response.addHeader("message", message);
1364 * Requests from the Admin Console for operations not on single specific objects
1369 * @param loggingContext
1370 * @throws ServletException
1371 * @throws IOException
1373 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1374 PolicyDBDaoTransaction doACPostTransaction = null;
1376 String groupName = request.getParameter("groupName");
1377 String groupDescription = request.getParameter("groupDescription");
1378 String apiflag = request.getParameter("apiflag");
1379 if (groupName != null && groupDescription != null) {
1380 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1381 loggingContext.setServiceName("AC:PAP.createGroup");
1382 String unescapedName = URLDecoder.decode(groupName, "UTF-8");
1383 String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1384 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1386 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1387 papEngine.newGroup(unescapedName, unescapedDescription);
1388 newGroupTransaction.commitTransaction();
1389 } catch (Exception e) {
1390 newGroupTransaction.rollbackTransaction();
1391 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1392 loggingContext.transactionEnded();
1394 PolicyLogger.audit("Transaction Failed - See Error.log");
1395 response.sendError(500, "Unable to create new group '" + groupId + "'");
1398 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1399 if (LOGGER.isDebugEnabled()) {
1400 LOGGER.debug("New Group '" + groupId + "' created");
1402 // tell the Admin Consoles there is a change
1404 // new group by definition has no PDPs, so no need to notify them of changes
1405 loggingContext.transactionEnded();
1406 PolicyLogger.audit("Transaction Failed - See Error.log");
1407 auditLogger.info("Success");
1408 PolicyLogger.audit("Transaction Ended Successfully");
1411 // for all remaining POST operations the group must exist before the operation can be done
1412 EcompPDPGroup group = papEngine.getGroup(groupId);
1413 if (group == null) {
1414 String message = "Unknown groupId '" + groupId + "'";
1415 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1416 loggingContext.transactionEnded();
1417 PolicyLogger.audit("Transaction Failed - See Error.log");
1419 response.addHeader("error", "unknownGroupId");
1420 response.addHeader("operation", "push");
1421 response.addHeader("message", message);
1422 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1424 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1428 // determine the operation needed based on the parameters in the request
1429 if (request.getParameter("policyId") != null) {
1430 // Args: group=<groupId> policy=<policyId> <= copy file
1431 // copy a policy from the request contents into a file in the group's directory on this machine
1433 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1435 loggingContext.setServiceName("AC:PAP.postPolicy");
1437 String policyId = request.getParameter("policyId");
1438 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1440 InputStream is = null;
1442 if (apiflag != null){
1443 // get the request content into a String if the request is from API
1445 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1446 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1447 scanner.useDelimiter("\\A");
1448 json = scanner.hasNext() ? scanner.next() : "";
1450 LOGGER.info("JSON request from API: " + json);
1451 // convert Object sent as JSON into local object
1452 ObjectMapper mapper = new ObjectMapper();
1453 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
1454 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
1455 temp = new File(policy.getLocation());
1456 is = new FileInputStream(temp);
1458 is = request.getInputStream();
1460 addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1461 if (apiflag != null){
1462 ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is);
1465 if (policyId.endsWith(".xml")) {
1466 name = policyId.replace(".xml", "");
1467 name = name.substring(0, name.lastIndexOf("."));
1469 ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is);
1471 if(is!=null && temp!=null){
1475 addPolicyToGroupTransaction.commitTransaction();
1476 } catch (Exception e) {
1477 addPolicyToGroupTransaction.rollbackTransaction();
1478 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1479 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1480 loggingContext.transactionEnded();
1481 PolicyLogger.audit("Transaction Failed - See Error.log");
1483 response.addHeader("error", "policyCopyError");
1484 response.addHeader("message", message);
1485 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1487 response.sendError(500, message);
1491 // policy file copied ok and the Group was updated on the PDP
1492 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1493 response.addHeader("operation", "push");
1494 response.addHeader("policyId", policyId);
1495 response.addHeader("groupId", groupId);
1496 if (LOGGER.isDebugEnabled()) {
1497 LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1499 loggingContext.transactionEnded();
1500 auditLogger.info("Success");
1501 PolicyLogger.audit("Transaction Ended Successfully");
1503 } else if (request.getParameter("default") != null) {
1504 // Args: group=<groupId> default=true <= make default
1505 // change the current default group to be the one identified in the request.
1506 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1507 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1508 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1509 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1511 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1512 papEngine.SetDefaultGroup(group);
1513 setDefaultGroupTransaction.commitTransaction();
1514 } catch (Exception e) {
1515 setDefaultGroupTransaction.rollbackTransaction();
1516 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1517 loggingContext.transactionEnded();
1519 PolicyLogger.audit("Transaction Failed - See Error.log");
1520 response.sendError(500, "Unable to set group '" + groupId + "' to default");
1523 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1524 if (LOGGER.isDebugEnabled()) {
1525 LOGGER.debug("Group '" + groupId + "' set to be default");
1527 // Notify the Admin Consoles that something changed
1528 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1529 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1531 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1532 loggingContext.transactionEnded();
1533 auditLogger.info("Success");
1534 PolicyLogger.audit("Transaction Ended Successfully");
1536 } else if (request.getParameter("pdpId") != null) {
1537 doACPostTransaction = policyDBDao.getNewTransaction();
1538 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1539 loggingContext.setServiceName("AC:PAP.movePDP");
1540 String pdpId = request.getParameter("pdpId");
1541 EcompPDP pdp = papEngine.getPDP(pdpId);
1542 EcompPDPGroup originalGroup = papEngine.getPDPGroup((EcompPDP) pdp);
1544 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1545 }catch(Exception e){
1546 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1547 " Error while moving pdp in the database: "
1548 +"pdp="+pdp.getId()+",to group="+group.getId());
1549 throw new PAPException(e.getMessage());
1551 papEngine.movePDP((EcompPDP) pdp, group);
1552 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1553 if (LOGGER.isDebugEnabled()) {
1554 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1556 // update the status of both the original group and the new one
1557 ((StdPDPGroup)originalGroup).resetStatus();
1558 ((StdPDPGroup)group).resetStatus();
1559 // Notify the Admin Consoles that something changed
1560 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1562 // Need to notify the PDP that it's config may have changed
1564 doACPostTransaction.commitTransaction();
1565 loggingContext.transactionEnded();
1566 auditLogger.info("Success");
1567 PolicyLogger.audit("Transaction Ended Successfully");
1570 } catch (PAPException e) {
1571 if(doACPostTransaction != null){
1572 doACPostTransaction.rollbackTransaction();
1574 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1575 loggingContext.transactionEnded();
1576 PolicyLogger.audit("Transaction Failed - See Error.log");
1577 response.sendError(500, e.getMessage());
1583 * Requests from the Admin Console to GET info about the Groups and PDPs
1588 * @param loggingContext
1589 * @throws ServletException
1590 * @throws IOException
1592 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1594 String parameterDefault = request.getParameter("default");
1595 String pdpId = request.getParameter("pdpId");
1596 String pdpGroup = request.getParameter("getPDPGroup");
1597 if ("".equals(groupId)) {
1598 // request IS from AC but does not identify a group by name
1599 if (parameterDefault != null) {
1600 // Request is for the Default group (whatever its id)
1601 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1602 EcompPDPGroup group = papEngine.getDefaultGroup();
1603 // convert response object to JSON and include in the response
1604 ObjectMapper mapper = new ObjectMapper();
1605 mapper.writeValue(response.getOutputStream(), group);
1606 if (LOGGER.isDebugEnabled()) {
1607 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1609 response.setStatus(HttpServletResponse.SC_OK);
1610 response.setHeader("content-type", "application/json");
1611 response.getOutputStream().close();
1612 loggingContext.transactionEnded();
1613 auditLogger.info("Success");
1614 PolicyLogger.audit("Transaction Ended Successfully");
1616 } else if (pdpId != null) {
1617 // Request is related to a PDP
1618 if (pdpGroup == null) {
1619 // Request is for the (unspecified) group containing a given PDP
1620 loggingContext.setServiceName("AC:PAP.getPDP");
1621 EcompPDP pdp = papEngine.getPDP(pdpId);
1622 // convert response object to JSON and include in the response
1623 ObjectMapper mapper = new ObjectMapper();
1624 mapper.writeValue(response.getOutputStream(), pdp);
1625 if (LOGGER.isDebugEnabled()) {
1626 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1628 response.setStatus(HttpServletResponse.SC_OK);
1629 response.setHeader("content-type", "application/json");
1630 response.getOutputStream().close();
1631 loggingContext.transactionEnded();
1632 auditLogger.info("Success");
1633 PolicyLogger.audit("Transaction Ended Successfully");
1636 // Request is for the group containing a given PDP
1637 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1638 EcompPDP pdp = papEngine.getPDP(pdpId);
1639 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
1640 // convert response object to JSON and include in the response
1641 ObjectMapper mapper = new ObjectMapper();
1642 mapper.writeValue(response.getOutputStream(), group);
1643 if (LOGGER.isDebugEnabled()) {
1644 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1646 response.setStatus(HttpServletResponse.SC_OK);
1647 response.setHeader("content-type", "application/json");
1648 response.getOutputStream().close();
1649 loggingContext.transactionEnded();
1650 auditLogger.info("Success");
1651 PolicyLogger.audit("Transaction Ended Successfully");
1655 // request is for top-level properties about all groups
1656 loggingContext.setServiceName("AC:PAP.getAllGroups");
1657 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
1658 // convert response object to JSON and include in the response
1659 ObjectMapper mapper = new ObjectMapper();
1660 mapper.writeValue(response.getOutputStream(), groups);
1661 if (LOGGER.isDebugEnabled()) {
1662 LOGGER.debug("GET All groups req");
1664 response.setStatus(HttpServletResponse.SC_OK);
1665 response.setHeader("content-type", "application/json");
1666 response.getOutputStream().close();
1667 loggingContext.transactionEnded();
1668 auditLogger.info("Success");
1669 PolicyLogger.audit("Transaction Ended Successfully");
1673 // for all other GET operations the group must exist before the operation can be done
1674 EcompPDPGroup group = papEngine.getGroup(groupId);
1675 if (group == null) {
1676 String message = "Unknown groupId '" + groupId + "'";
1677 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1678 loggingContext.transactionEnded();
1680 PolicyLogger.audit("Transaction Failed - See Error.log");
1681 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1684 // Figure out which request this is based on the parameters
1685 String policyId = request.getParameter("policyId");
1686 if (policyId != null) {
1687 // retrieve a policy
1688 loggingContext.setServiceName("AC:PAP.getPolicy");
1689 // convert response object to JSON and include in the response
1690 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1691 loggingContext.transactionEnded();
1692 PolicyLogger.audit("Transaction Failed - See Error.log");
1693 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1695 // No other parameters, so return the identified Group
1696 loggingContext.setServiceName("AC:PAP.getGroup");
1697 // convert response object to JSON and include in the response
1698 ObjectMapper mapper = new ObjectMapper();
1699 mapper.writeValue(response.getOutputStream(), group);
1700 if (LOGGER.isDebugEnabled()) {
1701 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1703 response.setStatus(HttpServletResponse.SC_OK);
1704 response.setHeader("content-type", "application/json");
1705 response.getOutputStream().close();
1706 loggingContext.transactionEnded();
1707 auditLogger.info("Success");
1708 PolicyLogger.audit("Transaction Ended Successfully");
1711 // Currently there are no other GET calls from the AC.
1712 // 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.
1713 // Other GETs that could be called:
1714 // Specific Group (groupId=<groupId>)
1715 // A Policy (groupId=<groupId> policyId=<policyId>)
1716 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1717 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1718 loggingContext.transactionEnded();
1719 PolicyLogger.audit("Transaction Failed - See Error.log");
1720 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1721 } catch (PAPException e) {
1722 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1723 loggingContext.transactionEnded();
1724 PolicyLogger.audit("Transaction Failed - See Error.log");
1725 response.sendError(500, e.getMessage());
1731 * Requests from the Admin Console to create new items or update existing ones
1736 * @param loggingContext
1737 * @throws ServletException
1738 * @throws IOException
1740 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1741 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1743 // for PUT operations the group may or may not need to exist before the operation can be done
1744 EcompPDPGroup group = papEngine.getGroup(groupId);
1745 // determine the operation needed based on the parameters in the request
1746 // for remaining operations the group must exist before the operation can be done
1747 if (group == null) {
1748 String message = "Unknown groupId '" + groupId + "'";
1749 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1750 loggingContext.transactionEnded();
1751 PolicyLogger.audit("Transaction Failed - See Error.log");
1752 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1755 if (request.getParameter("policy") != null) {
1756 // 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)
1757 loggingContext.setServiceName("AC:PAP.putPolicy");
1758 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
1759 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1760 loggingContext.transactionEnded();
1761 PolicyLogger.audit("Transaction Failed - See Error.log");
1762 auditLogger.info("Success");
1763 PolicyLogger.audit("Transaction Ended Successfully");
1765 } else if (request.getParameter("pdpId") != null) {
1766 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
1767 String pdpId = request.getParameter("pdpId");
1768 if (papEngine.getPDP(pdpId) == null) {
1769 loggingContext.setServiceName("AC:PAP.createPDP");
1771 loggingContext.setServiceName("AC:PAP.updatePDP");
1773 // get the request content into a String
1775 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1776 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1777 scanner.useDelimiter("\\A");
1778 json = scanner.hasNext() ? scanner.next() : "";
1780 LOGGER.info("JSON request from AC: " + json);
1781 // convert Object sent as JSON into local object
1782 ObjectMapper mapper = new ObjectMapper();
1783 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
1784 if (pdpId == null ||
1785 objectFromJSON == null ||
1786 ! (objectFromJSON instanceof StdPDP) ||
1787 ((StdPDP)objectFromJSON).getId() == null ||
1788 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
1789 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
1790 loggingContext.transactionEnded();
1791 PolicyLogger.audit("Transaction Failed - See Error.log");
1792 response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
1794 StdPDP pdp = (StdPDP) objectFromJSON;
1795 if (papEngine.getPDP(pdpId) == null) {
1796 // this is a request to create a new PDP object
1798 acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
1799 } catch(Exception e){
1800 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1801 +"pdp="+pdp.getId()+",to group="+group.getId());
1802 throw new PAPException(e.getMessage());
1804 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
1807 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
1808 } catch(Exception e){
1809 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
1810 +"pdp="+pdp.getId());
1811 throw new PAPException(e.getMessage());
1813 // this is a request to update the pdp
1814 papEngine.updatePDP(pdp);
1816 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1817 if (LOGGER.isDebugEnabled()) {
1818 LOGGER.debug("PDP '" + pdpId + "' created/updated");
1820 // adjust the group's state including the new PDP
1821 ((StdPDPGroup)group).resetStatus();
1822 // tell the Admin Consoles there is a change
1824 // this might affect the PDP, so notify it of the change
1826 acPutTransaction.commitTransaction();
1827 loggingContext.transactionEnded();
1828 auditLogger.info("Success");
1829 PolicyLogger.audit("Transaction Ended Successfully");
1831 } else if (request.getParameter("pipId") != null) {
1832 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
1833 loggingContext.setServiceName("AC:PAP.putPIP");
1834 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1835 loggingContext.transactionEnded();
1836 PolicyLogger.audit("Transaction Failed - See Error.log");
1837 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1840 // Assume that this is an update of an existing PDP Group
1841 // ARGS: group=<groupId> <= Update an Existing Group
1842 loggingContext.setServiceName("AC:PAP.updateGroup");
1843 // get the request content into a String
1845 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1846 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1847 scanner.useDelimiter("\\A");
1848 json = scanner.hasNext() ? scanner.next() : "";
1850 LOGGER.info("JSON request from AC: " + json);
1851 // convert Object sent as JSON into local object
1852 ObjectMapper mapper = new ObjectMapper();
1853 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
1854 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
1855 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
1856 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
1857 loggingContext.transactionEnded();
1858 PolicyLogger.audit("Transaction Failed - See Error.log");
1859 response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON);
1861 // The Path on the PAP side is not carried on the RESTful interface with the AC
1862 // (because it is local to the PAP)
1863 // so we need to fill that in before submitting the group for update
1864 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
1866 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
1867 } catch(Exception e){
1868 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
1869 +"group="+group.getId());
1870 throw new PAPException(e.getMessage());
1873 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1874 EcompPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
1875 if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) {
1876 LOGGER.debug("Precheck Successful.");
1879 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
1881 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1882 if (LOGGER.isDebugEnabled()) {
1883 LOGGER.debug("Group '" + group.getId() + "' updated");
1885 acPutTransaction.commitTransaction();
1886 // tell the Admin Consoles there is a change
1888 // Group changed, which might include changing the policies
1889 groupChanged(group);
1890 loggingContext.transactionEnded();
1891 auditLogger.info("Success");
1892 PolicyLogger.audit("Transaction Ended Successfully");
1895 } catch (PAPException e) {
1896 acPutTransaction.rollbackTransaction();
1897 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
1898 loggingContext.transactionEnded();
1899 PolicyLogger.audit("Transaction Failed - See Error.log");
1900 response.sendError(500, e.getMessage());
1906 * Requests from the Admin Console to delete/remove items
1911 * @param loggingContext
1912 * @throws ServletException
1913 * @throws IOException
1915 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1916 //This code is to allow deletes to propagate to the database since delete is not implemented
1917 String isDeleteNotify = request.getParameter("isDeleteNotify");
1918 if(isDeleteNotify != null){
1919 String policyToDelete = request.getParameter("policyToDelete");
1921 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
1922 } catch(UnsupportedEncodingException e){
1923 PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8");
1924 response.sendError(500,"policyToDelete encoding not supported");
1927 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
1929 deleteTransaction.deletePolicy(policyToDelete);
1930 } catch(Exception e){
1931 deleteTransaction.rollbackTransaction();
1932 response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) "
1933 + "\nfailure with the following exception: " + e);
1936 deleteTransaction.commitTransaction();
1937 response.setStatus(HttpServletResponse.SC_OK);
1940 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
1942 // for all DELETE operations the group must exist before the operation can be done
1943 loggingContext.setServiceName("AC:PAP.delete");
1944 EcompPDPGroup group = papEngine.getGroup(groupId);
1945 if (group == null) {
1946 String message = "Unknown groupId '" + groupId + "'";
1947 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1948 loggingContext.transactionEnded();
1949 PolicyLogger.audit("Transaction Failed - See Error.log");
1950 response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
1953 // determine the operation needed based on the parameters in the request
1954 if (request.getParameter("policy") != null) {
1955 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
1956 loggingContext.setServiceName("AC:PAP.deletePolicy");
1957 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1958 loggingContext.transactionEnded();
1959 PolicyLogger.audit("Transaction Failed - See Error.log");
1960 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1962 } else if (request.getParameter("pdpId") != null) {
1963 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
1964 String pdpId = request.getParameter("pdpId");
1965 EcompPDP pdp = papEngine.getPDP(pdpId);
1967 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
1968 } catch(Exception e){
1969 throw new PAPException();
1971 papEngine.removePDP((EcompPDP) pdp);
1972 // adjust the status of the group, which may have changed when we removed this PDP
1973 ((StdPDPGroup)group).resetStatus();
1974 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1976 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
1978 removePdpOrGroupTransaction.commitTransaction();
1979 loggingContext.transactionEnded();
1980 auditLogger.info("Success");
1981 PolicyLogger.audit("Transaction Ended Successfully");
1983 } else if (request.getParameter("pipId") != null) {
1984 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
1985 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
1986 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1987 loggingContext.transactionEnded();
1988 PolicyLogger.audit("Transaction Failed - See Error.log");
1989 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1992 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
1993 String moveToGroupId = request.getParameter("movePDPsToGroupId");
1994 EcompPDPGroup moveToGroup = null;
1995 if (moveToGroupId != null) {
1996 moveToGroup = papEngine.getGroup(moveToGroupId);
1998 // get list of PDPs in the group being deleted so we can notify them that they got changed
1999 Set<EcompPDP> movedPDPs = new HashSet<>();
2000 movedPDPs.addAll(group.getEcompPdps());
2001 // do the move/remove
2003 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
2004 } catch(Exception e){
2005 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
2006 throw new PAPException(e.getMessage());
2008 papEngine.removeGroup(group, moveToGroup);
2009 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
2011 // notify any PDPs in the removed set that their config may have changed
2012 for (EcompPDP pdp : movedPDPs) {
2015 removePdpOrGroupTransaction.commitTransaction();
2016 loggingContext.transactionEnded();
2017 auditLogger.info("Success");
2018 PolicyLogger.audit("Transaction Ended Successfully");
2021 } catch (PAPException e) {
2022 removePdpOrGroupTransaction.rollbackTransaction();
2023 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
2024 loggingContext.transactionEnded();
2025 PolicyLogger.audit("Transaction Failed - See Error.log");
2026 response.sendError(500, e.getMessage());
2032 * Heartbeat thread - periodically check on PDPs' status
2034 * Heartbeat with all known PDPs.
2036 * Implementation note:
2038 * The PDPs are contacted Sequentially, not in Parallel.
2040 * If we did this in parallel using multiple threads we would simultaneously use
2044 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2045 * when user changes occur.
2046 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2048 * The Sequential operation does a heartbeat request to each PDP one at a time.
2049 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2050 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2051 * it could take a long time to cycle through all of the PDPs.
2052 * That means that this may not notice a PDP being down in a predictable time.
2054 private class Heartbeat implements Runnable {
2055 private PAPPolicyEngine papEngine;
2056 private Set<EcompPDP> pdps = new HashSet<>();
2057 private int heartbeatInterval;
2058 private int heartbeatTimeout;
2060 public volatile boolean isRunning = false;
2062 public synchronized boolean isRunning() {
2063 return this.isRunning;
2066 public synchronized void terminate() {
2067 this.isRunning = false;
2070 public Heartbeat(PAPPolicyEngine papEngine2) {
2071 papEngine = papEngine2;
2072 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2073 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2078 // Set ourselves as running
2079 synchronized(this) {
2080 this.isRunning = true;
2082 HashMap<String, URL> idToURLMap = new HashMap<>();
2084 while (this.isRunning()) {
2085 // Wait the given time
2086 Thread.sleep(heartbeatInterval);
2087 // get the list of PDPs (may have changed since last time)
2089 synchronized(papEngine) {
2091 for (EcompPDPGroup g : papEngine.getEcompPDPGroups()) {
2092 for (EcompPDP p : g.getEcompPdps()) {
2096 } catch (PAPException e) {
2097 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2100 // Check for shutdown
2101 if (this.isRunning() == false) {
2102 LOGGER.info("isRunning is false, getting out of loop.");
2105 // try to get the summary status from each PDP
2106 boolean changeSeen = false;
2107 for (EcompPDP pdp : pdps) {
2108 // Check for shutdown
2109 if (this.isRunning() == false) {
2110 LOGGER.info("isRunning is false, getting out of loop.");
2113 // the id of the PDP is its url (though we add a query parameter)
2114 URL pdpURL = idToURLMap.get(pdp.getId());
2115 if (pdpURL == null) {
2116 // haven't seen this PDP before
2117 String fullURLString = null;
2120 if(CheckPDP.validateID(pdp.getId())){
2121 fullURLString = pdp.getId() + "?type=hb";
2122 pdpURL = new URL(fullURLString);
2123 idToURLMap.put(pdp.getId(), pdpURL);
2125 } catch (MalformedURLException e) {
2126 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2130 // Do a GET with type HeartBeat
2131 String newStatus = "";
2132 HttpURLConnection connection = null;
2134 // Open up the connection
2135 connection = (HttpURLConnection)pdpURL.openConnection();
2136 // Setup our method and headers
2137 connection.setRequestMethod("GET");
2138 connection.setConnectTimeout(heartbeatTimeout);
2140 String encoding = CheckPDP.getEncoding(pdp.getId());
2141 if(encoding !=null){
2142 connection.setRequestProperty("Authorization", "Basic " + encoding);
2145 connection.connect();
2146 if (connection.getResponseCode() == 204) {
2147 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2148 if (LOGGER.isDebugEnabled()) {
2149 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2152 // anything else is an unexpected result
2153 newStatus = PDPStatus.Status.UNKNOWN.toString();
2154 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2156 } catch (UnknownHostException e) {
2157 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2158 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2159 } catch (SocketTimeoutException e) {
2160 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2161 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2162 } catch (ConnectException e) {
2163 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2164 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2165 } catch (Exception e) {
2166 newStatus = PDPStatus.Status.UNKNOWN.toString();
2167 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2169 // cleanup the connection
2170 connection.disconnect();
2172 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2173 if (LOGGER.isDebugEnabled()) {
2174 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2177 setPDPSummaryStatus(pdp, newStatus);
2178 } catch (PAPException e) {
2179 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2184 // Check for shutdown
2185 if (this.isRunning() == false) {
2186 LOGGER.info("isRunning is false, getting out of loop.");
2189 // if any of the PDPs changed state, tell the ACs to update
2194 } catch (InterruptedException e) {
2195 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2202 * HELPER to change Group status when PDP status is changed
2203 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2205 private void setPDPSummaryStatus(EcompPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2206 setPDPSummaryStatus(pdp, newStatus.toString());
2209 private void setPDPSummaryStatus(EcompPDP pdp, String newStatus) throws PAPException {
2210 synchronized(papEngine) {
2211 StdPDPStatus status = new StdPDPStatus();
2212 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2213 ((StdPDP)pdp).setStatus(status);
2214 // now adjust the group
2215 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((EcompPDP) pdp);
2216 // if the PDP was just deleted it may transiently exist but not be in a group
2217 if (group != null) {
2218 group.resetStatus();
2224 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2225 * in the PDP group directories
2228 public void changed() {
2229 // all PDPs in all groups need to be updated/sync'd
2230 Set<EcompPDPGroup> groups;
2232 groups = papEngine.getEcompPDPGroups();
2233 } catch (PAPException e) {
2234 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2235 throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2237 for (EcompPDPGroup group : groups) {
2238 groupChanged(group);
2243 public void groupChanged(EcompPDPGroup group) {
2244 // all PDPs within one group need to be updated/sync'd
2245 for (EcompPDP pdp : group.getEcompPdps()) {
2251 public void pdpChanged(EcompPDP pdp) {
2252 // kick off a thread to do an event notification for each PDP.
2253 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2254 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2255 Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId));
2256 if(CheckPDP.validateID(pdp.getId())){
2261 private class UpdatePDPThread implements Runnable {
2262 private EcompPDP pdp;
2263 private String requestId;
2265 public UpdatePDPThread(EcompPDP pdp, String storedRequestId) {
2267 requestId = storedRequestId;
2271 // send the current configuration to one PDP
2272 HttpURLConnection connection = null;
2273 // get a new logging context for the thread
2274 ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext);
2276 loggingContext.setServiceName("PAP:PDP.putConfig");
2277 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2278 if ((requestId == null) || (requestId == "")) {
2279 UUID requestID = UUID.randomUUID();
2280 loggingContext.setRequestID(requestID.toString());
2281 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2283 loggingContext.setRequestID(requestId);
2284 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2286 loggingContext.transactionStarted();
2287 // the Id of the PDP is its URL
2288 if (LOGGER.isDebugEnabled()) {
2289 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2291 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2292 //TODO (need to change "cache=", implying getting some input saying which to change)
2293 URL url = new URL(pdp.getId() + "?cache=all");
2294 // Open up the connection
2295 connection = (HttpURLConnection)url.openConnection();
2296 // Setup our method and headers
2297 connection.setRequestMethod("PUT");
2299 String encoding = CheckPDP.getEncoding(pdp.getId());
2300 if(encoding !=null){
2301 connection.setRequestProperty("Authorization", "Basic " + encoding);
2303 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2304 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2305 storedRequestId = null;
2306 connection.setInstanceFollowRedirects(true);
2307 connection.setDoOutput(true);
2308 try (OutputStream os = connection.getOutputStream()) {
2309 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
2310 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2311 if (group == null) {
2312 // create blank properties files
2313 Properties policyProperties = new Properties();
2314 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2315 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2316 policyProperties.store(os, "");
2317 Properties pipProps = new Properties();
2318 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2319 pipProps.store(os, "");
2321 // send properties from the current group
2322 group.getPolicyProperties().store(os, "");
2323 Properties policyLocations = new Properties();
2324 for (PDPPolicy policy : group.getPolicies()) {
2325 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2327 policyLocations.store(os, "");
2328 group.getPipConfigProperties().store(os, "");
2330 } catch (Exception e) {
2331 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2332 // Since this is a server-side error, it probably does not reflect a problem on the client,
2333 // so do not change the PDP status.
2337 connection.connect();
2338 if (connection.getResponseCode() == 204) {
2339 LOGGER.info("Success. We are configured correctly.");
2340 loggingContext.transactionEnded();
2341 auditLogger.info("Success. PDP is configured correctly.");
2342 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2343 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2344 } else if (connection.getResponseCode() == 200) {
2345 LOGGER.info("Success. PDP needs to update its configuration.");
2346 loggingContext.transactionEnded();
2347 auditLogger.info("Success. PDP needs to update its configuration.");
2348 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2349 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2351 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2352 loggingContext.transactionEnded();
2353 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2354 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2355 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2357 } catch (Exception e) {
2358 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2359 loggingContext.transactionEnded();
2360 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2362 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2363 } catch (PAPException e1) {
2364 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2365 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2368 // cleanup the connection
2369 connection.disconnect();
2370 // tell the AC to update it's status info
2377 * RESTful Interface from PAP to ACs notifying them of changes
2379 private void notifyAC() {
2380 // kick off a thread to do one event notification for all registered ACs
2381 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2382 // as part of processing this message on their end.
2383 Thread t = new Thread(new NotifyACThread());
2387 private class NotifyACThread implements Runnable {
2389 List<String> disconnectedACs = new ArrayList<>();
2390 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2391 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2392 for (String acURL : adminConsoleURLStringList) {
2393 HttpURLConnection connection = null;
2395 acURL += "?PAPNotification=true";
2396 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2397 //TODO - If so, put correct parameters into the Query string here
2398 acURL += "&objectType=all" + "&action=update";
2399 if (LOGGER.isDebugEnabled()) {
2400 LOGGER.debug("creating url for id '" + acURL + "'");
2402 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2403 //TODO (need to change "cache=", implying getting some input saying which to change)
2404 URL url = new URL(acURL );
2405 // Open up the connection
2406 connection = (HttpURLConnection)url.openConnection();
2407 // Setup our method and headers
2408 connection.setRequestMethod("PUT");
2409 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2410 // Adding this in. It seems the HttpUrlConnection class does NOT
2411 // properly forward our headers for POST re-direction. It does so
2412 // for a GET re-direction.
2413 // So we need to handle this ourselves.
2414 //TODO - is this needed for a PUT? seems better to leave in for now?
2415 connection.setInstanceFollowRedirects(false);
2416 // Do not include any data in the PUT because this is just a
2417 // notification to the AC.
2418 // The AC will use GETs back to the PAP to get what it needs
2419 // to fill in the screens.
2421 connection.connect();
2422 if (connection.getResponseCode() == 204) {
2423 LOGGER.info("Success. We updated correctly.");
2425 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2428 } catch (Exception e) {
2429 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2430 disconnectedACs.add(acURL);
2432 // cleanup the connection
2433 connection.disconnect();
2436 // remove any ACs that are no longer connected
2437 if (disconnectedACs.size() > 0) {
2438 adminConsoleURLStringList.removeAll(disconnectedACs);
2443 private void testService(ECOMPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2444 LOGGER.info("Test request received");
2446 im.evaluateSanity();
2447 //If we make it this far, all is well
2448 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2449 LOGGER.info(message);
2450 loggingContext.transactionEnded();
2451 PolicyLogger.audit("Transaction Failed - See Error.log");
2452 response.setStatus(HttpServletResponse.SC_OK);
2454 }catch (ForwardProgressException fpe){
2455 //No forward progress is being made
2456 String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
2457 + " Exception Message: " + fpe.getMessage();
2458 LOGGER.info(message);
2459 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2460 loggingContext.transactionEnded();
2461 PolicyLogger.audit("Transaction Failed - See Error.log");
2462 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2464 }catch (AdministrativeStateException ase){
2465 //Administrative State is locked
2466 String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED "
2467 + " Exception Message: " + ase.getMessage();
2468 LOGGER.info(message);
2469 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2470 loggingContext.transactionEnded();
2471 PolicyLogger.audit("Transaction Failed - See Error.log");
2472 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2474 }catch (StandbyStatusException sse){
2475 //Administrative State is locked
2476 String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE "
2477 + " Exception Message: " + sse.getMessage();
2478 LOGGER.info(message);
2479 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2480 loggingContext.transactionEnded();
2481 PolicyLogger.audit("Transaction Failed - See Error.log");
2482 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2484 }catch (Exception e) {
2485 //A subsystem is not making progress, is locked, standby or is not responding
2486 String eMsg = e.getMessage();
2488 eMsg = "No Exception Message";
2490 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2491 + " Exception Message: " + eMsg;
2492 LOGGER.info(message);
2493 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2494 loggingContext.transactionEnded();
2495 PolicyLogger.audit("Transaction Failed - See Error.log");
2496 //Get the specific list of subsystems that failed
2497 String ssFailureList = null;
2498 for(String failedSS : papDependencyGroupsFlatArray){
2499 if(eMsg.contains(failedSS)){
2500 if(ssFailureList == null){
2501 ssFailureList = failedSS;
2503 ssFailureList = ssFailureList.concat(","+failedSS);
2507 if(ssFailureList == null){
2508 ssFailureList = "UnknownSubSystem";
2510 response.addHeader("X-ECOMP-SubsystemFailure", ssFailureList);
2511 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2517 * Authorizing the PEP Requests.
2519 private boolean authorizeRequest(HttpServletRequest request) {
2520 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2521 // Check if the Client is Authorized.
2522 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2529 private static void loadWebapps() throws PAPException{
2530 if(ACTION_HOME == null || CONFIG_HOME == null){
2531 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2533 if (webappsPath == null) {
2534 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2535 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2537 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2538 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2539 if (Files.notExists(webappsPathConfig)) {
2541 Files.createDirectories(webappsPathConfig);
2542 } catch (IOException e) {
2543 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: "
2544 + webappsPathConfig.toAbsolutePath().toString());
2547 if (Files.notExists(webappsPathAction)) {
2549 Files.createDirectories(webappsPathAction);
2550 } catch (IOException e) {
2551 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
2552 + webappsPathAction.toAbsolutePath().toString(), e);
2555 ACTION_HOME = webappsPathAction.toString();
2556 CONFIG_HOME = webappsPathConfig.toString();
2560 public static String getConfigHome(){
2563 } catch (PAPException e) {
2569 public static String getActionHome(){
2572 } catch (PAPException e) {
2578 public static EntityManagerFactory getEmf() {
2582 public static String getPDPFile(){
2583 return XACMLPapServlet.pdpFile;
2586 public static String getPersistenceUnit(){
2587 return PERSISTENCE_UNIT;
2590 public static PAPPolicyEngine getPAPEngine(){
2594 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2595 return policyDBDao.getNewTransaction();