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 private static String papDbDriver = null;
156 private static String papDbUrl = null;
157 private static String papDbUser = null;
158 private 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 private static String msEcompName;
183 private 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 setPapDbDriver(papDbDriver);
228 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
229 if(papDbUrl == null){
230 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
231 throw new PAPException("papDbUrl is null");
233 setPapDbUrl(papDbUrl);
234 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
235 if(papDbUser == null){
236 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
237 throw new PAPException("papDbUser is null");
239 setPapDbUser(papDbUser);
240 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
241 if(papDbPassword == null){
242 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
243 throw new PAPException("papDbPassword is null");
245 setPapDbPassword(papDbPassword);
246 papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
247 if(papResourceName == null){
248 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
249 throw new PAPException("papResourceName is null");
251 papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
252 if(papSiteName == null){
253 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
254 throw new PAPException("papSiteName is null");
256 papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
257 if(papNodeType == null){
258 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
259 throw new PAPException("papNodeType is null");
261 environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
262 //Integer will throw an exception of anything is missing or unrecognized
263 papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
264 papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
265 papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
266 //Boolean will default to false if anything is missing or unrecognized
267 papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
268 papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
270 autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG));
271 // if Auto push then Load with properties.
275 file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE);
276 if(file.endsWith(".properties")){
277 autoPushPolicy = new AutoPushPolicy(file);
279 throw new PAPException();
282 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE );
283 LOGGER.info("Overriding the autoPushFlag to False...");
284 autoPushFlag = false;
287 papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
288 if(papDependencyGroups == null){
289 throw new PAPException("papDependencyGroups is null");
292 //Now we have flattened the array into a simple comma-separated list
293 papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");
294 //clean up the entries
295 for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
296 papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
299 if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
300 papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
303 String msg = "integrity_audit_period_seconds ";
304 LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
305 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
309 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
312 //Integer will throw an exception of anything is missing or unrecognized
313 fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
314 failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
315 testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
316 writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));
317 LOGGER.debug("\n\n\n**************************************"
318 + "\n**************************************"
320 + "\n papDbDriver = " + papDbDriver
321 + "\n papDbUrl = " + papDbUrl
322 + "\n papDbUser = " + papDbUser
323 + "\n papDbPassword = " + papDbPassword
324 + "\n papTransWait = " + papTransWait
325 + "\n papTransTimeout = " + papTransTimeout
326 + "\n papAuditTimeout = " + papAuditTimeout
327 + "\n papAuditFlag = " + papAuditFlag
328 + "\n papFileSystemAudit = " + papFileSystemAudit
329 + "\n autoPushFlag = " + autoPushFlag
330 + "\n papResourceName = " + papResourceName
331 + "\n fpMonitorInterval = " + fpMonitorInterval
332 + "\n failedCounterThreshold = " + failedCounterThreshold
333 + "\n testTransInterval = " + testTransInterval
334 + "\n writeFpcInterval = " + writeFpcInterval
335 + "\n papSiteName = " + papSiteName
336 + "\n papNodeType = " + papNodeType
337 + "\n papDependencyGroupsList = " + papDependencyGroups
338 + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
339 + "\n\n**************************************"
340 + "\n**************************************");
341 // Pull custom persistence settings
342 Properties properties;
344 properties = XACMLProperties.getProperties();
345 LOGGER.debug("\n\n\n**************************************"
346 + "\n**************************************"
348 + "properties = " + properties
349 + "\n\n**************************************");
350 } catch (IOException e) {
351 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
352 + "XACMLProperties.getProperties()");
353 throw new ServletException(e.getMessage(), e.getCause());
355 //Micro Service Properties
356 msEcompName=properties.getProperty("xacml.policy.msEcompName");
357 setMsEcompName(msEcompName);
358 msPolicyName=properties.getProperty("xacml.policy.msPolicyName");
359 setMsPolicyName(msPolicyName);
360 // PDPId File location
361 XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
362 if (XACMLPapServlet.pdpFile == null) {
363 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: "
364 + XACMLRestProperties.PROP_PDP_IDFILE);
365 throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
367 // Create an IntegrityMonitor
368 im = IntegrityMonitor.getInstance(papResourceName,properties);
369 // Create an IntegrityAudit
370 ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
371 ia.startAuditThread();
372 // Create the entity manager factory
373 emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
375 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
377 throw new ServletException("Unable to create Entity Manager Factory");
379 // we are about to call the PDPs and give them their configuration.
380 // To do that we need to have the URL of this PAP so we can construct the Policy file URLs
381 XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
382 //Create the policyDBDao
383 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
384 // Load our PAP engine, first create a factory
385 ECOMPPapEngineFactory factory = ECOMPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
386 // The factory knows how to go about creating a PAP Engine
387 XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine();
388 PolicyDBDaoTransaction addNewGroup = null;
390 if(((org.openecomp.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){
391 addNewGroup = policyDBDao.getNewTransaction();
392 EcompPDPGroup group = papEngine.getDefaultGroup();
393 addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
394 addNewGroup.commitTransaction();
395 addNewGroup = policyDBDao.getNewTransaction();
396 addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
397 addNewGroup.commitTransaction();
399 } catch(Exception e){
400 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database");
401 if(addNewGroup != null){
402 addNewGroup.rollbackTransaction();
405 policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine);
406 //boolean performFileToDatabaseAudit = false;
407 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
408 //get an AuditTransaction to lock out all other transactions
409 PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
410 policyDBDao.auditLocalDatabase(XACMLPapServlet.papEngine);
411 //release the transaction lock
415 // Sanity check for URL.
416 if (XACMLPapServlet.papURL == null) {
417 throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
419 // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
420 // to all its known PDP nodes.
421 if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
422 this.initiateThread = new Thread(this);
423 this.initiateThread.start();
425 // After startup, the PAP does Heartbeat's to each of the PDPs periodically
426 XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine);
427 XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
428 XACMLPapServlet.heartbeatThread.start();
430 } catch (FactoryException | PAPException e) {
431 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
432 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
433 } catch (Exception e) {
434 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
435 throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);
440 * Thread used only during PAP startup to initiate change messages to all known PDPs.
441 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
445 // send the current configuration to all the PDPs that we know about
450 * @see Servlet#destroy()
452 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
453 * For now we assume that we do care.
455 public void destroy() {
456 // Make sure our threads are destroyed
457 if (XACMLPapServlet.heartbeatThread != null) {
458 // stop the heartbeat
460 if (XACMLPapServlet.heartbeat != null) {
461 XACMLPapServlet.heartbeat.terminate();
463 XACMLPapServlet.heartbeatThread.interrupt();
464 XACMLPapServlet.heartbeatThread.join();
465 } catch (InterruptedException e) {
466 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
469 if (this.initiateThread != null) {
471 this.initiateThread.interrupt();
472 this.initiateThread.join();
473 } catch (InterruptedException e) {
474 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
481 * - PDP nodes to register themselves with the PAP, and
482 * - Admin Console to make changes in the PDP Groups.
484 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
486 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
487 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
488 loggingContext.transactionStarted();
489 loggingContext.setServiceName("PAP.post");
490 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
491 UUID requestID = UUID.randomUUID();
492 loggingContext.setRequestID(requestID.toString());
493 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
495 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
497 PolicyDBDaoTransaction pdpTransaction = null;
499 im.startTransaction();
500 } catch (AdministrativeStateException ae){
501 String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
502 + " state of " + im.getStateManager().getAdminState()
503 + "\n Exception Message: " + ae.getMessage();
504 LOGGER.info(message);
505 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
506 loggingContext.transactionEnded();
507 PolicyLogger.audit("Transaction Failed - See Error.log");
508 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
510 }catch (StandbyStatusException se) {
511 String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
512 + " of " + im.getStateManager().getStandbyStatus()
513 + "\n Exception Message: " + se.getMessage();
514 LOGGER.info(message);
515 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
516 loggingContext.transactionEnded();
517 PolicyLogger.audit("Transaction Failed - See Error.log");
518 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
522 XACMLRest.dumpRequest(request);
523 // since getParameter reads the content string, explicitly get the content before doing that.
524 // Simply getting the inputStream seems to protect it against being consumed by getParameter.
525 request.getInputStream();
526 String groupId = request.getParameter("groupId");
527 String apiflag = request.getParameter("apiflag");
528 if(groupId != null) {
529 // Is this from the Admin Console or API?
530 if(apiflag!=null && apiflag.equalsIgnoreCase("api")) {
531 // this is from the API so we need to check the client credentials before processing the request
532 if(!authorizeRequest(request)){
533 String message = "PEP not Authorized for making this Request!!";
534 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
535 loggingContext.transactionEnded();
536 PolicyLogger.audit("Transaction Failed - See Error.log");
537 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
542 doACPost(request, response, groupId, loggingContext);
543 loggingContext.transactionEnded();
544 PolicyLogger.audit("Transaction Ended Successfully");
548 // Request is from a PDP asking for its config.
549 loggingContext.setServiceName("PDP:PAP.register");
551 String id = this.getPDPID(request);
552 String jmxport = this.getPDPJMX(request);
553 LOGGER.info("Request(doPost) from PDP coming up: " + id);
554 // Get the PDP Object
555 EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
558 LOGGER.info("Unknown PDP: " + id);
560 if(CheckPDP.validateID(id)){
561 pdpTransaction = policyDBDao.getNewTransaction();
563 pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
564 XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
565 } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) {
566 pdpTransaction.rollbackTransaction();
567 String message = "Failed to create new PDP for id: " + id;
568 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
569 loggingContext.transactionEnded();
570 PolicyLogger.audit("Transaction Failed - See Error.log");
571 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
575 // get the PDP we just created
576 pdp = XACMLPapServlet.papEngine.getPDP(id);
578 if(pdpTransaction != null){
579 pdpTransaction.rollbackTransaction();
581 String message = "Failed to create new PDP for id: " + id;
582 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
583 loggingContext.transactionEnded();
584 PolicyLogger.audit("Transaction Failed - See Error.log");
585 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
590 String message = "PDP is Unauthorized to Connect to PAP: "+ id;
591 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
592 loggingContext.transactionEnded();
593 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
594 PolicyLogger.audit("Transaction Failed - See Error.log");
599 pdpTransaction.commitTransaction();
600 } catch(Exception e){
601 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
604 if (jmxport != null && jmxport != ""){
605 ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
607 // Get the PDP's Group
608 EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp);
610 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
611 loggingContext.transactionEnded();
612 PolicyLogger.audit("Transaction Failed - See Error.log");
613 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
617 // Determine what group the PDP node is in and get
618 // its policy/pip properties.
619 Properties policies = group.getPolicyProperties();
620 Properties pipconfig = group.getPipConfigProperties();
621 // Get the current policy/pip configuration that the PDP has
622 Properties pdpProperties = new Properties();
623 pdpProperties.load(request.getInputStream());
624 LOGGER.info("PDP Current Properties: " + pdpProperties.toString());
625 LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null"));
626 LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
627 // Validate the node's properties
628 boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
629 // Send back current configuration
630 if (isCurrent == false) {
631 // Tell the PDP we are sending back the current policies/pip config
632 LOGGER.info("PDP configuration NOT current.");
633 if (policies != null) {
634 // Put URL's into the properties in case the PDP needs to
636 this.populatePolicyURL(request.getRequestURL(), policies);
637 // Copy the properties to the output stream
638 policies.store(response.getOutputStream(), "");
640 if (pipconfig != null) {
641 // Copy the properties to the output stream
642 pipconfig.store(response.getOutputStream(), "");
644 // We are good - and we are sending them information
645 response.setStatus(HttpServletResponse.SC_OK);
646 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
648 // Tell them they are good
649 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
650 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
652 // tell the AC that something changed
654 loggingContext.transactionEnded();
655 auditLogger.info("Success");
656 PolicyLogger.audit("Transaction Ended Successfully");
657 } catch (PAPException e) {
658 if(pdpTransaction != null){
659 pdpTransaction.rollbackTransaction();
661 LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
662 loggingContext.transactionEnded();
663 PolicyLogger.audit("Transaction Failed - See Error.log");
664 response.sendError(500, e.getMessage());
668 //Catch anything that fell through
669 loggingContext.transactionEnded();
670 PolicyLogger.audit("Transaction Ended");
675 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
677 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
678 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
679 loggingContext.transactionStarted();
680 loggingContext.setServiceName("PAP.get");
681 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
682 UUID requestID = UUID.randomUUID();
683 loggingContext.setRequestID(requestID.toString());
684 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
686 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
689 XACMLRest.dumpRequest(request);
690 String pathInfo = request.getRequestURI();
691 LOGGER.info("path info: " + pathInfo);
692 if (pathInfo != null){
693 //DO NOT do a im.startTransaction for the test request
694 if (pathInfo.equals("/pap/test")) {
695 testService(loggingContext, response);
699 //This im.startTransaction() covers all other Get transactions
701 im.startTransaction();
702 } catch (AdministrativeStateException ae){
703 String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
704 + " state of " + im.getStateManager().getAdminState()
705 + "\n Exception Message: " + ae.getMessage();
706 LOGGER.info(message);
707 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
708 loggingContext.transactionEnded();
709 PolicyLogger.audit("Transaction Failed - See Error.log");
710 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
712 }catch (StandbyStatusException se) {
713 String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
714 + " of " + im.getStateManager().getStandbyStatus()
715 + "\n Exception Message: " + se.getMessage();
716 LOGGER.info(message);
717 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
718 loggingContext.transactionEnded();
719 PolicyLogger.audit("Transaction Failed - See Error.log");
720 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
723 // Request from the API to get the gitPath
724 String apiflag = request.getParameter("apiflag");
726 if(authorizeRequest(request)){
727 APIRequestHandler apiRequestHandler = new APIRequestHandler();
728 apiRequestHandler.doGet(request,response, apiflag);
729 loggingContext.transactionEnded();
730 PolicyLogger.audit("Transaction Ended Successfully");
734 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
735 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
736 loggingContext.transactionEnded();
737 PolicyLogger.audit("Transaction Failed - See Error.log");
738 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
743 // Is this from the Admin Console?
744 String groupId = request.getParameter("groupId");
745 if (groupId != null) {
746 // this is from the Admin Console, so handle separately
747 doACGet(request, response, groupId, loggingContext);
748 loggingContext.transactionEnded();
749 PolicyLogger.audit("Transaction Ended Successfully");
754 String id = this.getPDPID(request);
755 LOGGER.info("doGet from: " + id);
756 // Get the PDP Object
757 EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
760 // Check if request came from localhost
761 if (request.getRemoteHost().equals("localhost") ||
762 request.getRemoteHost().equals("127.0.0.1") ||
763 request.getRemoteHost().equals(request.getLocalAddr())) {
764 // Return status information - basically all the groups
765 loggingContext.setServiceName("PAP.getGroups");
766 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
767 // convert response object to JSON and include in the response
768 ObjectMapper mapper = new ObjectMapper();
769 mapper.writeValue(response.getOutputStream(), groups);
770 response.setHeader("content-type", "application/json");
771 response.setStatus(HttpServletResponse.SC_OK);
772 loggingContext.transactionEnded();
773 PolicyLogger.audit("Transaction Ended Successfully");
777 String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
778 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
779 loggingContext.transactionEnded();
780 PolicyLogger.audit("Transaction Failed - See Error.log");
781 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
785 loggingContext.setServiceName("PAP.getPolicy");
786 // Get the PDP's Group
787 EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp);
789 String message = "No group associated with pdp " + pdp.getId();
790 LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
791 loggingContext.transactionEnded();
792 PolicyLogger.audit("Transaction Failed - See Error.log");
793 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
797 // Which policy do they want?
798 String policyId = request.getParameter("id");
799 if (policyId == null) {
800 String message = "Did not specify an id for the policy";
801 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
802 loggingContext.transactionEnded();
803 PolicyLogger.audit("Transaction Failed - See Error.log");
804 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
808 PDPPolicy policy = group.getPolicy(policyId);
809 if (policy == null) {
810 String message = "Unknown policy: " + policyId;
811 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
812 loggingContext.transactionEnded();
813 PolicyLogger.audit("Transaction Failed - See Error.log");
814 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
818 LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
819 + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
820 try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) {
821 // Send the policy back
822 IOUtils.copy(is, os);
823 response.setStatus(HttpServletResponse.SC_OK);
824 loggingContext.transactionEnded();
825 auditLogger.info("Success");
826 PolicyLogger.audit("Transaction Ended Successfully");
827 } catch (IOException e) {
828 String message = "Failed to open policy id " + policyId;
829 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
830 loggingContext.transactionEnded();
831 PolicyLogger.audit("Transaction Failed - See Error.log");
832 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
834 } catch (PAPException e) {
835 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
836 loggingContext.transactionEnded();
837 PolicyLogger.audit("Transaction Failed - See Error.log");
838 response.sendError(500, e.getMessage());
842 loggingContext.transactionEnded();
843 PolicyLogger.audit("Transaction Ended");
848 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
850 protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
851 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
852 storedRequestId = loggingContext.getRequestID();
853 loggingContext.transactionStarted();
854 loggingContext.setServiceName("PAP.put");
855 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
856 UUID requestID = UUID.randomUUID();
857 loggingContext.setRequestID(requestID.toString());
858 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
860 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
863 im.startTransaction();
864 } catch (AdministrativeStateException ae){
865 String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative"
866 + " state of " + im.getStateManager().getAdminState()
867 + "\n Exception Message: " + ae.getMessage();
868 LOGGER.info(message +ae);
869 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
870 loggingContext.transactionEnded();
871 PolicyLogger.audit("Transaction Failed - See Error.log");
872 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
874 }catch (StandbyStatusException se) {
875 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
876 + " of " + im.getStateManager().getStandbyStatus()
877 + "\n Exception Message: " + se.getMessage();
878 LOGGER.info(message +se);
879 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
880 loggingContext.transactionEnded();
881 PolicyLogger.audit("Transaction Failed - See Error.log");
882 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
885 XACMLRest.dumpRequest(request);
886 //need to check if request is from the API or Admin console
887 String apiflag = request.getParameter("apiflag");
888 //This would occur if a PolicyDBDao notification was received
889 String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
890 if(policyDBDaoRequestUrl != null){
891 String policyDBDaoRequestEntityId = request.getParameter("entityid");
892 //String policyDBDaoRequestEntityType = request.getParameter("entitytype");
893 String policyDBDaoRequestEntityType = request.getParameter("entitytype");
894 String policyDBDaoRequestExtraData = request.getParameter("extradata");
895 if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
896 response.sendError(400, "entityid or entitytype not supplied");
897 loggingContext.transactionEnded();
898 PolicyLogger.audit("Transaction Ended Successfully");
902 policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
903 response.setStatus(200);
904 loggingContext.transactionEnded();
905 PolicyLogger.audit("Transaction Ended Successfully");
910 * Request for ImportService
912 String importService = request.getParameter("importService");
913 if (importService != null) {
914 if(authorizeRequest(request)){
915 APIRequestHandler apiRequestHandler = new APIRequestHandler();
916 apiRequestHandler.doPut(request, response, importService);
920 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
921 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
922 loggingContext.transactionEnded();
923 PolicyLogger.audit("Transaction Failed - See Error.log");
924 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
928 //This would occur if we received a notification of a policy rename from AC
929 String oldPolicyName = request.getParameter("oldPolicyName");
930 String newPolicyName = request.getParameter("newPolicyName");
931 if(oldPolicyName != null && newPolicyName != null){
932 if(LOGGER.isDebugEnabled()){
933 LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding"
934 + "\npolicyToCreateUpdate = " + " ");
938 oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
939 newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
940 if(LOGGER.isDebugEnabled()){
941 LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding"
942 + "\npolicyToCreateUpdate = " + " ");
944 } catch(UnsupportedEncodingException e){
945 PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
946 + "\npolicyToCreateUpdate = " + " ");
947 response.sendError(500,"policyToCreateUpdate encoding not supported"
948 + "\nfailure with the following exception: " + e);
949 loggingContext.transactionEnded();
950 PolicyLogger.audit("Transaction Failed - See error.log");
954 //send it to PolicyDBDao
955 PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
957 renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
959 renameTransaction.rollbackTransaction();
960 response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
961 + "\nfailure with the following exception: " + e);
962 loggingContext.transactionEnded();
963 PolicyLogger.audit("Transaction Failed - See error.log");
967 renameTransaction.commitTransaction();
968 response.setStatus(HttpServletResponse.SC_OK);
969 loggingContext.transactionEnded();
970 PolicyLogger.audit("Transaction Ended Successfully");
975 // See if this is Admin Console registering itself with us
977 String acURLString = request.getParameter("adminConsoleURL");
978 if (acURLString != null) {
979 loggingContext.setServiceName("AC:PAP.register");
980 // remember this Admin Console for future updates
981 if ( ! adminConsoleURLStringList.contains(acURLString)) {
982 adminConsoleURLStringList.add(acURLString);
984 if (LOGGER.isDebugEnabled()) {
985 LOGGER.debug("Admin Console registering with URL: " + acURLString);
987 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
988 loggingContext.transactionEnded();
989 auditLogger.info("Success");
990 PolicyLogger.audit("Transaction Ended Successfully");
995 * This is to update the PDP Group with the policy/policies being pushed
996 * Part of a 2 step process to push policies to the PDP that can now be done
997 * From both the Admin Console and the PolicyEngine API
999 String groupId = request.getParameter("groupId");
1000 if (groupId != null) {
1002 if(!authorizeRequest(request)){
1003 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1004 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1005 loggingContext.transactionEnded();
1006 PolicyLogger.audit("Transaction Failed - See Error.log");
1007 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1010 if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
1011 updateGroupsFromAPI(request, response, groupId, loggingContext);
1012 loggingContext.transactionEnded();
1013 PolicyLogger.audit("Transaction Ended Successfully");
1014 im.endTransaction();
1018 // this is from the Admin Console, so handle separately
1019 doACPut(request, response, groupId, loggingContext);
1020 loggingContext.transactionEnded();
1021 PolicyLogger.audit("Transaction Ended Successfully");
1022 im.endTransaction();
1026 // Request is for policy validation and creation
1028 if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
1029 // this request is from the Admin Console
1030 SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
1031 savePolicyHandler.doPolicyAPIPut(request, response);
1032 loggingContext.transactionEnded();
1033 PolicyLogger.audit("Transaction Ended Successfully");
1034 im.endTransaction();
1036 } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
1037 // this request is from the Policy Creation API
1038 if(authorizeRequest(request)){
1039 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1040 apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
1041 loggingContext.transactionEnded();
1042 PolicyLogger.audit("Transaction Ended Successfully");
1043 im.endTransaction();
1046 String message = "PEP not Authorized for making this Request!!";
1047 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1048 loggingContext.transactionEnded();
1049 PolicyLogger.audit("Transaction Failed - See Error.log");
1050 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1051 im.endTransaction();
1055 // We do not expect anything from anywhere else.
1056 // This method is here in case we ever need to support other operations.
1057 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
1058 loggingContext.transactionEnded();
1059 PolicyLogger.audit("Transaction Failed - See Error.log");
1060 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
1061 loggingContext.transactionEnded();
1062 PolicyLogger.audit("Transaction Failed - See error.log");
1063 im.endTransaction();
1067 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
1069 protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
1070 ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
1071 loggingContext.transactionStarted();
1072 loggingContext.setServiceName("PAP.delete");
1073 if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
1074 UUID requestID = UUID.randomUUID();
1075 loggingContext.setRequestID(requestID.toString());
1076 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
1078 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
1081 im.startTransaction();
1082 } catch (AdministrativeStateException ae){
1083 String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
1084 + " state of " + im.getStateManager().getAdminState()
1085 + "\n Exception Message: " + ae.getMessage();
1086 LOGGER.info(message);
1087 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1088 loggingContext.transactionEnded();
1089 PolicyLogger.audit("Transaction Failed - See Error.log");
1090 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1092 }catch (StandbyStatusException se) {
1093 String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
1094 + " of " + im.getStateManager().getStandbyStatus()
1095 + "\n Exception Message: " + se.getMessage();
1096 LOGGER.info(message);
1097 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
1098 loggingContext.transactionEnded();
1099 PolicyLogger.audit("Transaction Failed - See Error.log");
1100 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
1103 XACMLRest.dumpRequest(request);
1104 String groupId = request.getParameter("groupId");
1105 String apiflag = request.getParameter("apiflag");
1106 if (groupId != null) {
1107 // Is this from the Admin Console or API?
1109 if(!authorizeRequest(request)){
1110 String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
1111 PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
1112 loggingContext.transactionEnded();
1113 PolicyLogger.audit("Transaction Failed - See Error.log");
1114 response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
1117 APIRequestHandler apiRequestHandler = new APIRequestHandler();
1119 apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
1120 } catch (Exception e) {
1121 LOGGER.error("Exception Occured"+e);
1123 if(apiRequestHandler.getNewGroup()!=null){
1124 groupChanged(apiRequestHandler.getNewGroup());
1128 // this is from the Admin Console, so handle separately
1129 doACDelete(request, response, groupId, loggingContext);
1130 loggingContext.transactionEnded();
1131 PolicyLogger.audit("Transaction Ended Successfully");
1132 im.endTransaction();
1135 //Catch anything that fell through
1136 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
1137 loggingContext.transactionEnded();
1138 PolicyLogger.audit("Transaction Failed - See Error.log");
1139 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
1140 im.endTransaction();
1143 private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
1144 String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1145 String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1146 if (localRootPolicies == null || localReferencedPolicies == null) {
1147 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies);
1150 // Compare the policies and pipconfig properties to the pdpProperties
1152 // the policy properties includes only xacml.rootPolicies and
1153 // xacml.referencedPolicies without any .url entries
1154 Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
1155 Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
1156 if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
1157 localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
1158 pdpPipConfig.equals(pipconfig)) {
1159 // The PDP is current
1162 } catch (Exception e) {
1163 // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
1164 // or if there are policies that do not have a corresponding ".url" property.
1165 // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
1166 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
1171 private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
1172 String lists[] = new String[2];
1173 lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
1174 lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
1175 for (String list : lists) {
1176 if (list != null && list.isEmpty() == false) {
1177 for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
1178 String url = urlPath + "?id=" + id;
1179 LOGGER.info("Policy URL for " + id + ": " + url);
1180 policies.setProperty(id + ".url", url);
1186 protected String getPDPID(HttpServletRequest request) {
1187 String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
1188 if (pdpURL == null || pdpURL.isEmpty()) {
1189 // Should send back its port for identification
1190 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
1196 protected String getPDPJMX(HttpServletRequest request) {
1197 String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
1198 if (pdpJMMX == null || pdpJMMX.isEmpty()) {
1199 // Should send back its port for identification
1200 LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
1207 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
1212 * @param loggingContext
1213 * @throws ServletException
1214 * @throws IOException
1216 public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws IOException {
1217 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1219 // for PUT operations the group may or may not need to exist before the operation can be done
1220 StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);
1221 // get the request input stream content into a String
1223 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1224 scanner.useDelimiter("\\A");
1225 json = scanner.hasNext() ? scanner.next() : "";
1227 PolicyLogger.info("JSON request from PolicyEngine API: " + json);
1228 // convert Object sent as JSON into local object
1229 StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
1230 Set<PDPPolicy> policies = new HashSet<>();
1232 policies.add(policy);
1234 //Get the current policies from the Group and Add the new one
1235 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
1236 currentPoliciesInGroup = group.getPolicies();
1237 //If the selected policy is in the group we must remove it because the name is default
1238 Iterator<PDPPolicy> policyIterator = policies.iterator();
1239 LOGGER.debug("policyIterator....." + policies);
1240 while (policyIterator.hasNext()) {
1241 PDPPolicy selPolicy = policyIterator.next();
1242 for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
1243 if (existingPolicy.getId().equals(selPolicy.getId())) {
1244 group.removePolicyFromGroup(existingPolicy);
1245 LOGGER.debug("Removing policy: " + existingPolicy);
1250 //Update the PDP Group after removing old version of policy
1251 Set<PDPPolicy> updatedPoliciesInGroup = new HashSet<>();
1252 updatedPoliciesInGroup = group.getPolicies();
1253 //need to remove the policy with default name from group
1254 for (PDPPolicy updatedPolicy : currentPoliciesInGroup) {
1255 if (updatedPolicy.getName().equalsIgnoreCase("default")) {
1256 group.removePolicyFromGroup(updatedPolicy);
1260 if(updatedPoliciesInGroup!=null){
1261 policies.addAll(updatedPoliciesInGroup);
1263 group.setPolicies(policies);
1264 // Assume that this is an update of an existing PDP Group
1265 loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
1267 acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
1268 } catch(Exception e){
1269 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
1270 +"group="+group.getId());
1271 throw new PAPException(e.getMessage());
1273 papEngine.updateGroup(group);
1274 String policyId = "empty";
1276 policyId = policy.getId();
1278 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1279 response.addHeader("operation", "push");
1280 response.addHeader("policyId", policyId);
1281 response.addHeader("groupId", groupId);
1282 if (LOGGER.isDebugEnabled()) {
1283 LOGGER.debug("Group '" + group.getId() + "' updated");
1285 acPutTransaction.commitTransaction();
1287 // Group changed, which might include changing the policies
1288 groupChanged(group);
1289 loggingContext.transactionEnded();
1290 auditLogger.info("Success");
1292 if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
1293 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1294 if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) {
1295 LOGGER.debug("Precheck Successful.");
1299 PolicyLogger.audit("Transaction Ended Successfully");
1301 } catch (PAPException e) {
1302 acPutTransaction.rollbackTransaction();
1303 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
1304 loggingContext.transactionEnded();
1305 PolicyLogger.audit("Transaction Failed - See Error.log");
1306 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
1307 response.sendError(500, e.getMessage());
1308 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1309 response.addHeader("error","addGroupError");
1310 response.addHeader("message", message);
1316 * Requests from the Admin Console for operations not on single specific objects
1321 * @param loggingContext
1322 * @throws ServletException
1323 * @throws IOException
1325 private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1326 PolicyDBDaoTransaction doACPostTransaction = null;
1328 String groupName = request.getParameter("groupName");
1329 String groupDescription = request.getParameter("groupDescription");
1330 String apiflag = request.getParameter("apiflag");
1331 if (groupName != null && groupDescription != null) {
1332 // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group
1333 loggingContext.setServiceName("AC:PAP.createGroup");
1334 String unescapedName = URLDecoder.decode(groupName, "UTF-8");
1335 String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
1336 PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
1338 newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
1339 papEngine.newGroup(unescapedName, unescapedDescription);
1340 newGroupTransaction.commitTransaction();
1341 } catch (Exception e) {
1342 newGroupTransaction.rollbackTransaction();
1343 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
1344 loggingContext.transactionEnded();
1346 PolicyLogger.audit("Transaction Failed - See Error.log");
1347 response.sendError(500, "Unable to create new group '" + groupId + "'");
1350 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1351 if (LOGGER.isDebugEnabled()) {
1352 LOGGER.debug("New Group '" + groupId + "' created");
1354 // tell the Admin Consoles there is a change
1356 // new group by definition has no PDPs, so no need to notify them of changes
1357 loggingContext.transactionEnded();
1358 PolicyLogger.audit("Transaction Failed - See Error.log");
1359 auditLogger.info("Success");
1360 PolicyLogger.audit("Transaction Ended Successfully");
1363 // for all remaining POST operations the group must exist before the operation can be done
1364 EcompPDPGroup group = papEngine.getGroup(groupId);
1365 if (group == null) {
1366 String message = "Unknown groupId '" + groupId + "'";
1367 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1368 loggingContext.transactionEnded();
1369 PolicyLogger.audit("Transaction Failed - See Error.log");
1371 response.addHeader("error", "unknownGroupId");
1372 response.addHeader("operation", "push");
1373 response.addHeader("message", message);
1374 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
1376 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1380 // determine the operation needed based on the parameters in the request
1381 if (request.getParameter("policyId") != null) {
1382 // Args: group=<groupId> policy=<policyId> <= copy file
1383 // copy a policy from the request contents into a file in the group's directory on this machine
1385 loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
1387 loggingContext.setServiceName("AC:PAP.postPolicy");
1389 String policyId = request.getParameter("policyId");
1390 PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
1392 InputStream is = null;
1394 if (apiflag != null){
1395 // get the request content into a String if the request is from API
1397 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1398 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1399 scanner.useDelimiter("\\A");
1400 json = scanner.hasNext() ? scanner.next() : "";
1402 LOGGER.info("JSON request from API: " + json);
1403 // convert Object sent as JSON into local object
1404 ObjectMapper mapper = new ObjectMapper();
1405 Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);
1406 StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;
1407 temp = new File(policy.getLocation());
1408 is = new FileInputStream(temp);
1410 is = request.getInputStream();
1412 addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
1413 if (apiflag != null){
1414 ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is);
1417 if (policyId.endsWith(".xml")) {
1418 name = policyId.replace(".xml", "");
1419 name = name.substring(0, name.lastIndexOf("."));
1421 ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is);
1423 if(is!=null && temp!=null){
1427 addPolicyToGroupTransaction.commitTransaction();
1428 } catch (Exception e) {
1429 addPolicyToGroupTransaction.rollbackTransaction();
1430 String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
1431 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
1432 loggingContext.transactionEnded();
1433 PolicyLogger.audit("Transaction Failed - See Error.log");
1435 response.addHeader("error", "policyCopyError");
1436 response.addHeader("message", message);
1437 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1439 response.sendError(500, message);
1443 // policy file copied ok and the Group was updated on the PDP
1444 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1445 response.addHeader("operation", "push");
1446 response.addHeader("policyId", policyId);
1447 response.addHeader("groupId", groupId);
1448 if (LOGGER.isDebugEnabled()) {
1449 LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
1451 loggingContext.transactionEnded();
1452 auditLogger.info("Success");
1453 PolicyLogger.audit("Transaction Ended Successfully");
1455 } else if (request.getParameter("default") != null) {
1456 // Args: group=<groupId> default=true <= make default
1457 // change the current default group to be the one identified in the request.
1458 loggingContext.setServiceName("AC:PAP.setDefaultGroup");
1459 // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
1460 // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
1461 PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
1463 setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
1464 papEngine.SetDefaultGroup(group);
1465 setDefaultGroupTransaction.commitTransaction();
1466 } catch (Exception e) {
1467 setDefaultGroupTransaction.rollbackTransaction();
1468 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
1469 loggingContext.transactionEnded();
1471 PolicyLogger.audit("Transaction Failed - See Error.log");
1472 response.sendError(500, "Unable to set group '" + groupId + "' to default");
1475 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1476 if (LOGGER.isDebugEnabled()) {
1477 LOGGER.debug("Group '" + groupId + "' set to be default");
1479 // Notify the Admin Consoles that something changed
1480 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1481 //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
1483 // This does not affect any PDPs in the existing groups, so no need to notify them of this change
1484 loggingContext.transactionEnded();
1485 auditLogger.info("Success");
1486 PolicyLogger.audit("Transaction Ended Successfully");
1488 } else if (request.getParameter("pdpId") != null) {
1489 doACPostTransaction = policyDBDao.getNewTransaction();
1490 // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
1491 loggingContext.setServiceName("AC:PAP.movePDP");
1492 String pdpId = request.getParameter("pdpId");
1493 EcompPDP pdp = papEngine.getPDP(pdpId);
1494 EcompPDPGroup originalGroup = papEngine.getPDPGroup((EcompPDP) pdp);
1496 doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
1497 }catch(Exception e){
1498 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
1499 " Error while moving pdp in the database: "
1500 +"pdp="+pdp.getId()+",to group="+group.getId());
1501 throw new PAPException(e.getMessage());
1503 papEngine.movePDP((EcompPDP) pdp, group);
1504 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1505 if (LOGGER.isDebugEnabled()) {
1506 LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
1508 // update the status of both the original group and the new one
1509 ((StdPDPGroup)originalGroup).resetStatus();
1510 ((StdPDPGroup)group).resetStatus();
1511 // Notify the Admin Consoles that something changed
1512 // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
1514 // Need to notify the PDP that it's config may have changed
1516 doACPostTransaction.commitTransaction();
1517 loggingContext.transactionEnded();
1518 auditLogger.info("Success");
1519 PolicyLogger.audit("Transaction Ended Successfully");
1522 } catch (PAPException e) {
1523 if(doACPostTransaction != null){
1524 doACPostTransaction.rollbackTransaction();
1526 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
1527 loggingContext.transactionEnded();
1528 PolicyLogger.audit("Transaction Failed - See Error.log");
1529 response.sendError(500, e.getMessage());
1535 * Requests from the Admin Console to GET info about the Groups and PDPs
1540 * @param loggingContext
1541 * @throws ServletException
1542 * @throws IOException
1544 private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1546 String parameterDefault = request.getParameter("default");
1547 String pdpId = request.getParameter("pdpId");
1548 String pdpGroup = request.getParameter("getPDPGroup");
1549 if ("".equals(groupId)) {
1550 // request IS from AC but does not identify a group by name
1551 if (parameterDefault != null) {
1552 // Request is for the Default group (whatever its id)
1553 loggingContext.setServiceName("AC:PAP.getDefaultGroup");
1554 EcompPDPGroup group = papEngine.getDefaultGroup();
1555 // convert response object to JSON and include in the response
1556 ObjectMapper mapper = new ObjectMapper();
1557 mapper.writeValue(response.getOutputStream(), group);
1558 if (LOGGER.isDebugEnabled()) {
1559 LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
1561 response.setStatus(HttpServletResponse.SC_OK);
1562 response.setHeader("content-type", "application/json");
1563 response.getOutputStream().close();
1564 loggingContext.transactionEnded();
1565 auditLogger.info("Success");
1566 PolicyLogger.audit("Transaction Ended Successfully");
1568 } else if (pdpId != null) {
1569 // Request is related to a PDP
1570 if (pdpGroup == null) {
1571 // Request is for the (unspecified) group containing a given PDP
1572 loggingContext.setServiceName("AC:PAP.getPDP");
1573 EcompPDP pdp = papEngine.getPDP(pdpId);
1574 // convert response object to JSON and include in the response
1575 ObjectMapper mapper = new ObjectMapper();
1576 mapper.writeValue(response.getOutputStream(), pdp);
1577 if (LOGGER.isDebugEnabled()) {
1578 LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
1580 response.setStatus(HttpServletResponse.SC_OK);
1581 response.setHeader("content-type", "application/json");
1582 response.getOutputStream().close();
1583 loggingContext.transactionEnded();
1584 auditLogger.info("Success");
1585 PolicyLogger.audit("Transaction Ended Successfully");
1588 // Request is for the group containing a given PDP
1589 loggingContext.setServiceName("AC:PAP.getGroupForPDP");
1590 EcompPDP pdp = papEngine.getPDP(pdpId);
1591 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
1592 // convert response object to JSON and include in the response
1593 ObjectMapper mapper = new ObjectMapper();
1594 mapper.writeValue(response.getOutputStream(), group);
1595 if (LOGGER.isDebugEnabled()) {
1596 LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
1598 response.setStatus(HttpServletResponse.SC_OK);
1599 response.setHeader("content-type", "application/json");
1600 response.getOutputStream().close();
1601 loggingContext.transactionEnded();
1602 auditLogger.info("Success");
1603 PolicyLogger.audit("Transaction Ended Successfully");
1607 // request is for top-level properties about all groups
1608 loggingContext.setServiceName("AC:PAP.getAllGroups");
1609 Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();
1610 // convert response object to JSON and include in the response
1611 ObjectMapper mapper = new ObjectMapper();
1612 mapper.writeValue(response.getOutputStream(), groups);
1613 if (LOGGER.isDebugEnabled()) {
1614 LOGGER.debug("GET All groups req");
1616 response.setStatus(HttpServletResponse.SC_OK);
1617 response.setHeader("content-type", "application/json");
1618 response.getOutputStream().close();
1619 loggingContext.transactionEnded();
1620 auditLogger.info("Success");
1621 PolicyLogger.audit("Transaction Ended Successfully");
1625 // for all other GET operations the group must exist before the operation can be done
1626 EcompPDPGroup group = papEngine.getGroup(groupId);
1627 if (group == null) {
1628 String message = "Unknown groupId '" + groupId + "'";
1629 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1630 loggingContext.transactionEnded();
1632 PolicyLogger.audit("Transaction Failed - See Error.log");
1633 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1636 // Figure out which request this is based on the parameters
1637 String policyId = request.getParameter("policyId");
1638 if (policyId != null) {
1639 // retrieve a policy
1640 loggingContext.setServiceName("AC:PAP.getPolicy");
1641 // convert response object to JSON and include in the response
1642 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
1643 loggingContext.transactionEnded();
1644 PolicyLogger.audit("Transaction Failed - See Error.log");
1645 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");
1647 // No other parameters, so return the identified Group
1648 loggingContext.setServiceName("AC:PAP.getGroup");
1649 // convert response object to JSON and include in the response
1650 ObjectMapper mapper = new ObjectMapper();
1651 mapper.writeValue(response.getOutputStream(), group);
1652 if (LOGGER.isDebugEnabled()) {
1653 LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
1655 response.setStatus(HttpServletResponse.SC_OK);
1656 response.setHeader("content-type", "application/json");
1657 response.getOutputStream().close();
1658 loggingContext.transactionEnded();
1659 auditLogger.info("Success");
1660 PolicyLogger.audit("Transaction Ended Successfully");
1663 // Currently there are no other GET calls from the AC.
1664 // 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.
1665 // Other GETs that could be called:
1666 // Specific Group (groupId=<groupId>)
1667 // A Policy (groupId=<groupId> policyId=<policyId>)
1668 // A PDP (groupId=<groupId> pdpId=<pdpId>)
1669 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
1670 loggingContext.transactionEnded();
1671 PolicyLogger.audit("Transaction Failed - See Error.log");
1672 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1673 } catch (PAPException e) {
1674 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
1675 loggingContext.transactionEnded();
1676 PolicyLogger.audit("Transaction Failed - See Error.log");
1677 response.sendError(500, e.getMessage());
1683 * Requests from the Admin Console to create new items or update existing ones
1688 * @param loggingContext
1689 * @throws ServletException
1690 * @throws IOException
1692 private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1693 PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
1695 // for PUT operations the group may or may not need to exist before the operation can be done
1696 EcompPDPGroup group = papEngine.getGroup(groupId);
1697 // determine the operation needed based on the parameters in the request
1698 // for remaining operations the group must exist before the operation can be done
1699 if (group == null) {
1700 String message = "Unknown groupId '" + groupId + "'";
1701 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1702 loggingContext.transactionEnded();
1703 PolicyLogger.audit("Transaction Failed - See Error.log");
1704 response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
1707 if (request.getParameter("policy") != null) {
1708 // 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)
1709 loggingContext.setServiceName("AC:PAP.putPolicy");
1710 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
1711 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1712 loggingContext.transactionEnded();
1713 PolicyLogger.audit("Transaction Failed - See Error.log");
1714 auditLogger.info("Success");
1715 PolicyLogger.audit("Transaction Ended Successfully");
1717 } else if (request.getParameter("pdpId") != null) {
1718 // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one
1719 String pdpId = request.getParameter("pdpId");
1720 if (papEngine.getPDP(pdpId) == null) {
1721 loggingContext.setServiceName("AC:PAP.createPDP");
1723 loggingContext.setServiceName("AC:PAP.updatePDP");
1725 // get the request content into a String
1727 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1728 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1729 scanner.useDelimiter("\\A");
1730 json = scanner.hasNext() ? scanner.next() : "";
1732 LOGGER.info("JSON request from AC: " + json);
1733 // convert Object sent as JSON into local object
1734 ObjectMapper mapper = new ObjectMapper();
1735 Object objectFromJSON = mapper.readValue(json, StdPDP.class);
1736 if (pdpId == null ||
1737 objectFromJSON == null ||
1738 ! (objectFromJSON instanceof StdPDP) ||
1739 ((StdPDP)objectFromJSON).getId() == null ||
1740 ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
1741 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
1742 loggingContext.transactionEnded();
1743 PolicyLogger.audit("Transaction Failed - See Error.log");
1744 response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
1746 StdPDP pdp = (StdPDP) objectFromJSON;
1748 if (papEngine.getPDP(pdpId) == null) {
1749 // this is a request to create a new PDP object
1751 acPutTransaction.addPdpToGroup(pdp == null ? "PDP is null" : pdp.getId(), group.getId(), pdp.getName(),
1752 pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
1753 } catch(Exception e){
1754 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1755 +"pdp="+ (pdp == null ? "PDP is null" : pdp.getId()) +",to group="+group.getId());
1756 throw new PAPException(e.getMessage());
1758 papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
1761 acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
1762 } catch(Exception e){
1763 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
1764 +"pdp="+ pdp.getId());
1765 throw new PAPException(e.getMessage());
1767 // this is a request to update the pdp
1768 papEngine.updatePDP(pdp);
1770 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1771 if (LOGGER.isDebugEnabled()) {
1772 LOGGER.debug("PDP '" + pdpId + "' created/updated");
1774 // adjust the group's state including the new PDP
1775 ((StdPDPGroup)group).resetStatus();
1776 // tell the Admin Consoles there is a change
1778 // this might affect the PDP, so notify it of the change
1780 acPutTransaction.commitTransaction();
1781 loggingContext.transactionEnded();
1782 auditLogger.info("Success");
1783 PolicyLogger.audit("Transaction Ended Successfully");
1787 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
1788 +"pdp=null" + ",to group="+group.getId());
1789 throw new PAPException("PDP is null");
1790 } catch(Exception e){
1791 throw new PAPException("PDP is null" + e.getMessage() +e);
1794 } else if (request.getParameter("pipId") != null) {
1795 // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation)
1796 loggingContext.setServiceName("AC:PAP.putPIP");
1797 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1798 loggingContext.transactionEnded();
1799 PolicyLogger.audit("Transaction Failed - See Error.log");
1800 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1803 // Assume that this is an update of an existing PDP Group
1804 // ARGS: group=<groupId> <= Update an Existing Group
1805 loggingContext.setServiceName("AC:PAP.updateGroup");
1806 // get the request content into a String
1808 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
1809 java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
1810 scanner.useDelimiter("\\A");
1811 json = scanner.hasNext() ? scanner.next() : "";
1813 LOGGER.info("JSON request from AC: " + json);
1814 // convert Object sent as JSON into local object
1815 ObjectMapper mapper = new ObjectMapper();
1816 Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class);
1817 if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) ||
1818 ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
1819 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
1820 loggingContext.transactionEnded();
1821 PolicyLogger.audit("Transaction Failed - See Error.log");
1822 response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON);
1824 // The Path on the PAP side is not carried on the RESTful interface with the AC
1825 // (because it is local to the PAP)
1826 // so we need to fill that in before submitting the group for update
1827 if(objectFromJSON != null){
1828 ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
1831 acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
1832 } catch(Exception e){
1833 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
1834 +"group="+group.getId());
1835 throw new PAPException(e.getMessage());
1838 PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
1839 EcompPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;
1840 if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) {
1841 LOGGER.debug("Precheck Successful.");
1844 papEngine.updateGroup((StdPDPGroup)objectFromJSON);
1846 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1847 if (LOGGER.isDebugEnabled()) {
1848 LOGGER.debug("Group '" + group.getId() + "' updated");
1850 acPutTransaction.commitTransaction();
1851 // tell the Admin Consoles there is a change
1853 // Group changed, which might include changing the policies
1854 groupChanged(group);
1855 loggingContext.transactionEnded();
1856 auditLogger.info("Success");
1857 PolicyLogger.audit("Transaction Ended Successfully");
1860 } catch (PAPException e) {
1861 acPutTransaction.rollbackTransaction();
1862 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
1863 loggingContext.transactionEnded();
1864 PolicyLogger.audit("Transaction Failed - See Error.log");
1865 response.sendError(500, e.getMessage());
1871 * Requests from the Admin Console to delete/remove items
1876 * @param loggingContext
1877 * @throws ServletException
1878 * @throws IOException
1880 private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
1881 //This code is to allow deletes to propagate to the database since delete is not implemented
1882 String isDeleteNotify = request.getParameter("isDeleteNotify");
1883 if(isDeleteNotify != null){
1884 String policyToDelete = request.getParameter("policyToDelete");
1886 policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
1887 } catch(UnsupportedEncodingException e){
1888 PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8");
1889 response.sendError(500,"policyToDelete encoding not supported");
1892 PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
1894 deleteTransaction.deletePolicy(policyToDelete);
1895 } catch(Exception e){
1896 deleteTransaction.rollbackTransaction();
1897 response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) "
1898 + "\nfailure with the following exception: " + e);
1901 deleteTransaction.commitTransaction();
1902 response.setStatus(HttpServletResponse.SC_OK);
1905 PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
1907 // for all DELETE operations the group must exist before the operation can be done
1908 loggingContext.setServiceName("AC:PAP.delete");
1909 EcompPDPGroup group = papEngine.getGroup(groupId);
1910 if (group == null) {
1911 String message = "Unknown groupId '" + groupId + "'";
1912 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
1913 loggingContext.transactionEnded();
1914 PolicyLogger.audit("Transaction Failed - See Error.log");
1915 response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
1918 // determine the operation needed based on the parameters in the request
1919 if (request.getParameter("policy") != null) {
1920 // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group
1921 loggingContext.setServiceName("AC:PAP.deletePolicy");
1922 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1923 loggingContext.transactionEnded();
1924 PolicyLogger.audit("Transaction Failed - See Error.log");
1925 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1927 } else if (request.getParameter("pdpId") != null) {
1928 // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
1929 String pdpId = request.getParameter("pdpId");
1930 EcompPDP pdp = papEngine.getPDP(pdpId);
1932 removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
1933 } catch(Exception e){
1934 throw new PAPException();
1936 papEngine.removePDP((EcompPDP) pdp);
1937 // adjust the status of the group, which may have changed when we removed this PDP
1938 ((StdPDPGroup)group).resetStatus();
1939 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1941 // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
1943 removePdpOrGroupTransaction.commitTransaction();
1944 loggingContext.transactionEnded();
1945 auditLogger.info("Success");
1946 PolicyLogger.audit("Transaction Ended Successfully");
1948 } else if (request.getParameter("pipId") != null) {
1949 // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine
1950 loggingContext.setServiceName("AC:PAP.deletePIPConfig");
1951 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
1952 loggingContext.transactionEnded();
1953 PolicyLogger.audit("Transaction Failed - See Error.log");
1954 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
1957 // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all its PDPs to the given group
1958 String moveToGroupId = request.getParameter("movePDPsToGroupId");
1959 EcompPDPGroup moveToGroup = null;
1960 if (moveToGroupId != null) {
1961 moveToGroup = papEngine.getGroup(moveToGroupId);
1963 // get list of PDPs in the group being deleted so we can notify them that they got changed
1964 Set<EcompPDP> movedPDPs = new HashSet<>();
1965 movedPDPs.addAll(group.getEcompPdps());
1966 // do the move/remove
1968 removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
1969 } catch(Exception e){
1970 PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
1971 throw new PAPException(e.getMessage());
1973 papEngine.removeGroup(group, moveToGroup);
1974 response.setStatus(HttpServletResponse.SC_NO_CONTENT);
1976 // notify any PDPs in the removed set that their config may have changed
1977 for (EcompPDP pdp : movedPDPs) {
1980 removePdpOrGroupTransaction.commitTransaction();
1981 loggingContext.transactionEnded();
1982 auditLogger.info("Success");
1983 PolicyLogger.audit("Transaction Ended Successfully");
1986 } catch (PAPException e) {
1987 removePdpOrGroupTransaction.rollbackTransaction();
1988 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
1989 loggingContext.transactionEnded();
1990 PolicyLogger.audit("Transaction Failed - See Error.log");
1991 response.sendError(500, e.getMessage());
1997 * Heartbeat thread - periodically check on PDPs' status
1999 * Heartbeat with all known PDPs.
2001 * Implementation note:
2003 * The PDPs are contacted Sequentially, not in Parallel.
2005 * If we did this in parallel using multiple threads we would simultaneously use
2009 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
2010 * when user changes occur.
2011 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
2013 * The Sequential operation does a heartbeat request to each PDP one at a time.
2014 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
2015 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
2016 * it could take a long time to cycle through all of the PDPs.
2017 * That means that this may not notice a PDP being down in a predictable time.
2019 private class Heartbeat implements Runnable {
2020 private PAPPolicyEngine papEngine;
2021 private Set<EcompPDP> pdps = new HashSet<>();
2022 private int heartbeatInterval;
2023 private int heartbeatTimeout;
2025 public volatile boolean isRunning = false;
2027 public synchronized boolean isRunning() {
2028 return this.isRunning;
2031 public synchronized void terminate() {
2032 this.isRunning = false;
2035 public Heartbeat(PAPPolicyEngine papEngine2) {
2036 papEngine = papEngine2;
2037 this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
2038 this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
2043 // Set ourselves as running
2044 synchronized(this) {
2045 this.isRunning = true;
2047 HashMap<String, URL> idToURLMap = new HashMap<>();
2049 while (this.isRunning()) {
2050 // Wait the given time
2051 Thread.sleep(heartbeatInterval);
2052 // get the list of PDPs (may have changed since last time)
2054 synchronized(papEngine) {
2056 for (EcompPDPGroup g : papEngine.getEcompPDPGroups()) {
2057 for (EcompPDP p : g.getEcompPdps()) {
2061 } catch (PAPException e) {
2062 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
2065 // Check for shutdown
2066 if (this.isRunning() == false) {
2067 LOGGER.info("isRunning is false, getting out of loop.");
2070 // try to get the summary status from each PDP
2071 boolean changeSeen = false;
2072 for (EcompPDP pdp : pdps) {
2073 // Check for shutdown
2074 if (this.isRunning() == false) {
2075 LOGGER.info("isRunning is false, getting out of loop.");
2078 // the id of the PDP is its url (though we add a query parameter)
2079 URL pdpURL = idToURLMap.get(pdp.getId());
2080 if (pdpURL == null) {
2081 // haven't seen this PDP before
2082 String fullURLString = null;
2085 if(CheckPDP.validateID(pdp.getId())){
2086 fullURLString = pdp.getId() + "?type=hb";
2087 pdpURL = new URL(fullURLString);
2088 idToURLMap.put(pdp.getId(), pdpURL);
2090 } catch (MalformedURLException e) {
2091 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
2095 // Do a GET with type HeartBeat
2096 String newStatus = "";
2097 HttpURLConnection connection = null;
2099 // Open up the connection
2101 connection = (HttpURLConnection)pdpURL.openConnection();
2102 // Setup our method and headers
2103 connection.setRequestMethod("GET");
2104 connection.setConnectTimeout(heartbeatTimeout);
2106 String encoding = CheckPDP.getEncoding(pdp.getId());
2107 if(encoding !=null){
2108 connection.setRequestProperty("Authorization", "Basic " + encoding);
2111 connection.connect();
2112 if (connection.getResponseCode() == 204) {
2113 newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
2114 if (LOGGER.isDebugEnabled()) {
2115 LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
2118 // anything else is an unexpected result
2119 newStatus = PDPStatus.Status.UNKNOWN.toString();
2120 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
2123 } catch (UnknownHostException e) {
2124 newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
2125 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
2126 } catch (SocketTimeoutException e) {
2127 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2128 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
2129 } catch (ConnectException e) {
2130 newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
2131 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
2132 } catch (Exception e) {
2133 newStatus = PDPStatus.Status.UNKNOWN.toString();
2134 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
2136 // cleanup the connection
2137 if(connection != null)
2138 connection.disconnect();
2140 if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
2141 if (LOGGER.isDebugEnabled()) {
2142 LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'");
2145 setPDPSummaryStatus(pdp, newStatus);
2146 } catch (PAPException e) {
2147 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
2152 // Check for shutdown
2153 if (this.isRunning() == false) {
2154 LOGGER.info("isRunning is false, getting out of loop.");
2157 // if any of the PDPs changed state, tell the ACs to update
2162 } catch (InterruptedException e) {
2163 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down");
2170 * HELPER to change Group status when PDP status is changed
2171 * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
2173 private void setPDPSummaryStatus(EcompPDP pdp, PDPStatus.Status newStatus) throws PAPException {
2174 setPDPSummaryStatus(pdp, newStatus.toString());
2177 private void setPDPSummaryStatus(EcompPDP pdp, String newStatus) throws PAPException {
2178 synchronized(papEngine) {
2179 StdPDPStatus status = new StdPDPStatus();
2180 status.setStatus(PDPStatus.Status.valueOf(newStatus));
2181 ((StdPDP)pdp).setStatus(status);
2182 // now adjust the group
2183 StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((EcompPDP) pdp);
2184 // if the PDP was just deleted it may transiently exist but not be in a group
2185 if (group != null) {
2186 group.resetStatus();
2192 * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
2193 * in the PDP group directories
2196 public void changed() {
2197 // all PDPs in all groups need to be updated/sync'd
2198 Set<EcompPDPGroup> groups;
2200 groups = papEngine.getEcompPDPGroups();
2201 } catch (PAPException e) {
2202 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
2203 throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
2205 for (EcompPDPGroup group : groups) {
2206 groupChanged(group);
2211 public void groupChanged(EcompPDPGroup group) {
2212 // all PDPs within one group need to be updated/sync'd
2213 for (EcompPDP pdp : group.getEcompPdps()) {
2219 public void pdpChanged(EcompPDP pdp) {
2220 // kick off a thread to do an event notification for each PDP.
2221 // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
2222 // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
2223 Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId));
2224 if(CheckPDP.validateID(pdp.getId())){
2229 private class UpdatePDPThread implements Runnable {
2230 private EcompPDP pdp;
2231 private String requestId;
2233 public UpdatePDPThread(EcompPDP pdp, String storedRequestId) {
2235 requestId = storedRequestId;
2239 // send the current configuration to one PDP
2240 HttpURLConnection connection = null;
2241 // get a new logging context for the thread
2242 ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext);
2244 loggingContext.setServiceName("PAP:PDP.putConfig");
2245 // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
2246 if ((requestId == null) || (requestId == "")) {
2247 UUID requestID = UUID.randomUUID();
2248 loggingContext.setRequestID(requestID.toString());
2249 PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID());
2251 loggingContext.setRequestID(requestId);
2252 PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID());
2254 loggingContext.transactionStarted();
2255 // the Id of the PDP is its URL
2256 if (LOGGER.isDebugEnabled()) {
2257 LOGGER.debug("creating url for id '" + pdp.getId() + "'");
2259 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2260 //TODO (need to change "cache=", implying getting some input saying which to change)
2261 URL url = new URL(pdp.getId() + "?cache=all");
2262 // Open up the connection
2263 connection = (HttpURLConnection)url.openConnection();
2264 // Setup our method and headers
2265 connection.setRequestMethod("PUT");
2267 String encoding = CheckPDP.getEncoding(pdp.getId());
2268 if(encoding !=null){
2269 connection.setRequestProperty("Authorization", "Basic " + encoding);
2271 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2272 connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
2273 storedRequestId = null;
2274 connection.setInstanceFollowRedirects(true);
2275 connection.setDoOutput(true);
2276 try (OutputStream os = connection.getOutputStream()) {
2277 EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
2278 // if the PDP was just deleted, there is no group, but we want to send an update anyway
2279 if (group == null) {
2280 // create blank properties files
2281 Properties policyProperties = new Properties();
2282 policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
2283 policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
2284 policyProperties.store(os, "");
2285 Properties pipProps = new Properties();
2286 pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
2287 pipProps.store(os, "");
2289 // send properties from the current group
2290 group.getPolicyProperties().store(os, "");
2291 Properties policyLocations = new Properties();
2292 for (PDPPolicy policy : group.getPolicies()) {
2293 policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
2295 policyLocations.store(os, "");
2296 group.getPipConfigProperties().store(os, "");
2298 } catch (Exception e) {
2299 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
2300 // Since this is a server-side error, it probably does not reflect a problem on the client,
2301 // so do not change the PDP status.
2305 connection.connect();
2306 if (connection.getResponseCode() == 204) {
2307 LOGGER.info("Success. We are configured correctly.");
2308 loggingContext.transactionEnded();
2309 auditLogger.info("Success. PDP is configured correctly.");
2310 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2311 setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
2312 } else if (connection.getResponseCode() == 200) {
2313 LOGGER.info("Success. PDP needs to update its configuration.");
2314 loggingContext.transactionEnded();
2315 auditLogger.info("Success. PDP needs to update its configuration.");
2316 PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
2317 setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
2319 LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2320 loggingContext.transactionEnded();
2321 auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2322 PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2323 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2325 } catch (Exception e) {
2326 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
2327 loggingContext.transactionEnded();
2328 PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
2330 setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
2331 } catch (PAPException e1) {
2332 PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);
2333 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
2336 // cleanup the connection
2337 if(connection != null){
2338 connection.disconnect();
2340 // tell the AC to update it's status info
2347 * RESTful Interface from PAP to ACs notifying them of changes
2349 private void notifyAC() {
2350 // kick off a thread to do one event notification for all registered ACs
2351 // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
2352 // as part of processing this message on their end.
2353 Thread t = new Thread(new NotifyACThread());
2357 private class NotifyACThread implements Runnable {
2359 List<String> disconnectedACs = new ArrayList<>();
2360 // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
2361 // The "for each" loop uses the collection's iterator under the covers, so it should be correct.
2362 for (String acURL : adminConsoleURLStringList) {
2363 HttpURLConnection connection = null;
2365 acURL += "?PAPNotification=true";
2366 //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed?
2367 //TODO - If so, put correct parameters into the Query string here
2368 acURL += "&objectType=all" + "&action=update";
2369 if (LOGGER.isDebugEnabled()) {
2370 LOGGER.debug("creating url for id '" + acURL + "'");
2372 //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other?
2373 //TODO (need to change "cache=", implying getting some input saying which to change)
2374 URL url = new URL(acURL );
2375 // Open up the connection
2376 connection = (HttpURLConnection)url.openConnection();
2377 // Setup our method and headers
2378 connection.setRequestMethod("PUT");
2379 connection.setRequestProperty("Content-Type", "text/x-java-properties");
2380 // Adding this in. It seems the HttpUrlConnection class does NOT
2381 // properly forward our headers for POST re-direction. It does so
2382 // for a GET re-direction.
2383 // So we need to handle this ourselves.
2384 //TODO - is this needed for a PUT? seems better to leave in for now?
2385 connection.setInstanceFollowRedirects(false);
2386 // Do not include any data in the PUT because this is just a
2387 // notification to the AC.
2388 // The AC will use GETs back to the PAP to get what it needs
2389 // to fill in the screens.
2391 connection.connect();
2392 if (connection.getResponseCode() == 204) {
2393 LOGGER.info("Success. We updated correctly.");
2395 LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
2398 } catch (Exception e) {
2399 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
2400 disconnectedACs.add(acURL);
2402 // cleanup the connection
2403 if(connection != null)
2404 connection.disconnect();
2407 // remove any ACs that are no longer connected
2408 if (disconnectedACs.size() > 0) {
2409 adminConsoleURLStringList.removeAll(disconnectedACs);
2414 private void testService(ECOMPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
2415 LOGGER.info("Test request received");
2417 im.evaluateSanity();
2418 //If we make it this far, all is well
2419 String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
2420 LOGGER.info(message);
2421 loggingContext.transactionEnded();
2422 PolicyLogger.audit("Transaction Failed - See Error.log");
2423 response.setStatus(HttpServletResponse.SC_OK);
2425 }catch (ForwardProgressException fpe){
2426 //No forward progress is being made
2427 String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
2428 + " Exception Message: " + fpe.getMessage();
2429 LOGGER.info(message);
2430 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2431 loggingContext.transactionEnded();
2432 PolicyLogger.audit("Transaction Failed - See Error.log");
2433 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2435 }catch (AdministrativeStateException ase){
2436 //Administrative State is locked
2437 String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED "
2438 + " Exception Message: " + ase.getMessage();
2439 LOGGER.info(message);
2440 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2441 loggingContext.transactionEnded();
2442 PolicyLogger.audit("Transaction Failed - See Error.log");
2443 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2445 }catch (StandbyStatusException sse){
2446 //Administrative State is locked
2447 String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE "
2448 + " Exception Message: " + sse.getMessage();
2449 LOGGER.info(message);
2450 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2451 loggingContext.transactionEnded();
2452 PolicyLogger.audit("Transaction Failed - See Error.log");
2453 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2455 }catch (Exception e) {
2456 //A subsystem is not making progress, is locked, standby or is not responding
2457 String eMsg = e.getMessage();
2459 eMsg = "No Exception Message";
2461 String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
2462 + " Exception Message: " + eMsg;
2463 LOGGER.info(message);
2464 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
2465 loggingContext.transactionEnded();
2466 PolicyLogger.audit("Transaction Failed - See Error.log");
2467 //Get the specific list of subsystems that failed
2468 String ssFailureList = null;
2469 for(String failedSS : papDependencyGroupsFlatArray){
2470 if(eMsg.contains(failedSS)){
2471 if(ssFailureList == null){
2472 ssFailureList = failedSS;
2474 ssFailureList = ssFailureList.concat(","+failedSS);
2478 if(ssFailureList == null){
2479 ssFailureList = "UnknownSubSystem";
2481 response.addHeader("X-ECOMP-SubsystemFailure", ssFailureList);
2482 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
2488 * Authorizing the PEP Requests.
2490 private boolean authorizeRequest(HttpServletRequest request) {
2491 String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
2492 // Check if the Client is Authorized.
2493 if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
2500 private static void loadWebapps() throws PAPException{
2501 if(ACTION_HOME == null || CONFIG_HOME == null){
2502 Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
2504 if (webappsPath == null) {
2505 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2506 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
2508 Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
2509 Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action");
2510 if (Files.notExists(webappsPathConfig)) {
2512 Files.createDirectories(webappsPathConfig);
2513 } catch (IOException e) {
2514 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: "
2515 + webappsPathConfig.toAbsolutePath().toString());
2518 if (Files.notExists(webappsPathAction)) {
2520 Files.createDirectories(webappsPathAction);
2521 } catch (IOException e) {
2522 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
2523 + webappsPathAction.toAbsolutePath().toString(), e);
2526 ACTION_HOME = webappsPathAction.toString();
2527 CONFIG_HOME = webappsPathConfig.toString();
2531 public static String getConfigHome(){
2534 } catch (PAPException e) {
2540 public static String getActionHome(){
2543 } catch (PAPException e) {
2549 public static EntityManagerFactory getEmf() {
2553 public IntegrityAudit getIa() {
2557 public static String getPDPFile(){
2558 return XACMLPapServlet.pdpFile;
2561 public static String getPersistenceUnit(){
2562 return PERSISTENCE_UNIT;
2565 public static PAPPolicyEngine getPAPEngine(){
2569 public static PolicyDBDaoTransaction getDbDaoTransaction(){
2570 return policyDBDao.getNewTransaction();
2572 public static String getPapDbDriver() {
2576 public static void setPapDbDriver(String papDbDriver) {
2577 XACMLPapServlet.papDbDriver = papDbDriver;
2580 public static String getPapDbUrl() {
2584 public static void setPapDbUrl(String papDbUrl) {
2585 XACMLPapServlet.papDbUrl = papDbUrl;
2588 public static String getPapDbUser() {
2592 public static void setPapDbUser(String papDbUser) {
2593 XACMLPapServlet.papDbUser = papDbUser;
2596 public static String getPapDbPassword() {
2597 return papDbPassword;
2600 public static void setPapDbPassword(String papDbPassword) {
2601 XACMLPapServlet.papDbPassword = papDbPassword;
2604 public static String getMsEcompName() {
2608 public static void setMsEcompName(String msEcompName) {
2609 XACMLPapServlet.msEcompName = msEcompName;
2612 public static String getMsPolicyName() {
2613 return msPolicyName;
2616 public static void setMsPolicyName(String msPolicyName) {
2617 XACMLPapServlet.msPolicyName = msPolicyName;