From 5c4675e5f6f7fe9b8d9e87976ac5f603ff61c268 Mon Sep 17 00:00:00 2001 From: mmis Date: Thu, 22 Mar 2018 14:20:46 +0000 Subject: Removed checkstyle warnings Removed checkstyle warnings in: policy/controlloop/common/guard policy/controlloop/common/msb policy/controlloop/simulators including renaming of the following classes: MSBServiceFactory -> MsbServiceFactory MSBServiceManager -> MsbServiceManager MSBServiceException -> MsbServiceException Issue-ID: POLICY-705 Change-Id: I11d62a74fcb77e764121df119cb0bd9b844b485b Signed-off-by: mmis --- .../java/org/onap/policy/guard/CallGuardTask.java | 160 ++--- .../java/org/onap/policy/guard/GuardResult.java | 8 +- .../java/org/onap/policy/guard/LockCallback.java | 11 +- .../org/onap/policy/guard/PIPEngineGetHistory.java | 734 ++++++++++--------- .../java/org/onap/policy/guard/PolicyGuard.java | 208 +++--- .../org/onap/policy/guard/PolicyGuardRequest.java | 94 +-- .../org/onap/policy/guard/PolicyGuardResponse.java | 82 ++- .../onap/policy/guard/PolicyGuardXacmlHelper.java | 779 +++++++++++---------- .../guard/PolicyGuardXacmlRequestAttributes.java | 151 ++-- .../onap/policy/guard/PolicyGuardYamlToXacml.java | 377 +++++----- .../java/org/onap/policy/guard/TargetLock.java | 16 +- .../src/main/java/org/onap/policy/guard/Util.java | 224 +++--- .../org/onap/policy/guard/impl/PNFTargetLock.java | 109 +-- .../org/onap/policy/guard/impl/VMTargetLock.java | 93 +-- .../org/onap/policy/guard/impl/VNFTargetLock.java | 109 +-- 15 files changed, 1638 insertions(+), 1517 deletions(-) (limited to 'controlloop/common/guard/src/main/java') diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java index 9e3116dd8..4ac22600b 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,91 +20,93 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.std.annotations.RequestParser; + import java.util.UUID; import org.drools.core.WorkingMemory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.std.annotations.RequestParser; - public class CallGuardTask implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); - WorkingMemory workingMemory; - String restfulPdpUrl; - String clname; - String actor; - String recipe; - String target; - String requestId; - - /* - * Guard url is grabbed from PolicyEngine.manager properties - */ - public CallGuardTask(WorkingMemory wm, String cl, String act, String rec, String tar, String reqId) { - workingMemory = wm; - clname = cl; - actor = act; - recipe = rec; - requestId = reqId; - target = tar; - } - - @Override - public void run() { - long startTime = System.nanoTime(); - com.att.research.xacml.api.Request request = null; - - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId); - - try { - request = RequestParser.parseRequest(xacmlReq); - } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { - logger.error("CallGuardTask.run threw: {}", e); - } - - - logger.debug("\n********** XACML REQUEST START ********"); - logger.debug("{}", request); - logger.debug("********** XACML REQUEST END ********\n"); - - String guardDecision = null; - - // - // Make guard request - // - guardDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); - - logger.debug("\n********** XACML RESPONSE START ********"); - logger.debug("{}", guardDecision); - logger.debug("********** XACML RESPONSE END ********\n"); - - // - // Check if the restful call was unsuccessful or property doesn't exist - // - if(guardDecision == null){ - logger.error("********** XACML FAILED TO CONNECT ********"); - guardDecision = Util.INDETERMINATE; - } - - PolicyGuardResponse guardResponse = new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); - - - // - //Create an artificial Guard response in case we didn't get a clear Permit or Deny - // - if(guardResponse.getResult().equals("Indeterminate")){ - guardResponse.setOperation(recipe); - guardResponse.setRequestID(UUID.fromString(requestId)); - } - - long estimatedTime = System.nanoTime() - startTime; - logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", - guardResponse.getResult(), (double)estimatedTime/1000/1000); - workingMemory.insert(guardResponse); - - } + private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); + WorkingMemory workingMemory; + String restfulPdpUrl; + String clname; + String actor; + String recipe; + String target; + String requestId; + + /** + * Guard url is grabbed from PolicyEngine.manager properties + */ + public CallGuardTask(WorkingMemory wm, String cl, String act, String rec, String tar, String reqId) { + workingMemory = wm; + clname = cl; + actor = act; + recipe = rec; + requestId = reqId; + target = tar; + } + + @Override + public void run() { + final long startTime = System.nanoTime(); + com.att.research.xacml.api.Request request = null; + + PolicyGuardXacmlRequestAttributes xacmlReq = + new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId); + + try { + request = RequestParser.parseRequest(xacmlReq); + } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { + logger.error("CallGuardTask.run threw: {}", e); + } + + + logger.debug("\n********** XACML REQUEST START ********"); + logger.debug("{}", request); + logger.debug("********** XACML REQUEST END ********\n"); + + String guardDecision = null; + + // + // Make guard request + // + guardDecision = new PolicyGuardXacmlHelper().callPDP(xacmlReq); + + logger.debug("\n********** XACML RESPONSE START ********"); + logger.debug("{}", guardDecision); + logger.debug("********** XACML RESPONSE END ********\n"); + + // + // Check if the restful call was unsuccessful or property doesn't exist + // + if (guardDecision == null) { + logger.error("********** XACML FAILED TO CONNECT ********"); + guardDecision = Util.INDETERMINATE; + } + + PolicyGuardResponse guardResponse = + new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); + + + // + // Create an artificial Guard response in case we didn't get a clear Permit or Deny + // + if (guardResponse.getResult().equals("Indeterminate")) { + guardResponse.setOperation(recipe); + guardResponse.setRequestID(UUID.fromString(requestId)); + } + + long estimatedTime = System.nanoTime() - startTime; + logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", + guardResponse.getResult(), (double) estimatedTime / 1000 / 1000); + workingMemory.insert(guardResponse); + + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java index b2792858a..6b11c1afa 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; public enum GuardResult { - LOCK_ACQUIRED, - LOCK_DENIED, - LOCK_EXCEPTION - ; + LOCK_ACQUIRED, LOCK_DENIED, LOCK_EXCEPTION; } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java index 0a1255d33..2b33e0e57 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; public interface LockCallback { - - public boolean isActive(); - - public boolean releaseLock(); + + public boolean isActive(); + + public boolean releaseLock(); } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java index 21bdcd853..a9a984ade 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,21 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; + import java.math.BigInteger; import java.sql.Timestamp; import java.util.Collection; @@ -40,374 +55,351 @@ import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.pip.StdMutablePIPResponse; -import com.att.research.xacml.std.pip.StdPIPRequest; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; - -public class PIPEngineGetHistory extends StdConfigurableEngine{ - private static final Logger logger = LoggerFactory.getLogger(PIPEngineGetHistory.class); - - // - // Base issuer string. The issuer in the policy will also contain time window information - // E.g., "com:att:research:xacml:guard:historydb:tw:10:min" - // - public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb"; - public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; - - private static final String XML_SCHEMA_STRING = "http://www.w3.org/2001/XMLSchema#string"; - - private static final String XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; - private static final String XACML_ACTOR_ACTOR_ID = "urn:oasis:names:tc:xacml:1.0:actor:actor-id"; - private static final String XACML_ATTRIBUTE_CATEGORY_ACTION ="urn:oasis:names:tc:xacml:3.0:attribute-category:action"; - private static final String XACML_OPERATION_OPERATION_ID ="urn:oasis:names:tc:xacml:1.0:operation:operation-id"; - private static final String XACML_ATTRIBUTE_CATEGORY_RESOURCE ="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; - private static final String XACML_TARGET_TARGET_ID ="urn:oasis:names:tc:xacml:1.0:target:target-id"; - private static final String XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT = "com:att:research:xacml:test:sql:resource:operations:count"; - - private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( - new IdentifierImpl(XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT), - new IdentifierImpl(XACML_ACTOR_ACTOR_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_ACTION), - new IdentifierImpl(XACML_OPERATION_OPERATION_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), - new IdentifierImpl(XACML_TARGET_TARGET_ID), - new IdentifierImpl(XML_SCHEMA_STRING)); - - public PIPEngineGetHistory() { - super(); - } - - @Override - public Collection attributesRequired() { - return Collections.emptySet(); - } - - @Override - public Collection attributesProvided() { - return Collections.emptySet(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - logger.debug("Entering FeqLimiter PIP"); - - /* - * First check to see if the issuer is set and then match it - */ - String string; - if ((string = pipRequest.getIssuer()) == null) { - - logger.debug("No issuer in the request..."); - logger.debug("FeqLimiter PIP - No issuer in the request!"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - else{ - //Notice, we are checking here for the base issuer prefix. - if (!string.contains(this.getIssuer())) { - logger.debug("Requested issuer '{}' does not match {}", string, getIssuer()); - logger.debug("FeqLimiter PIP - Issuer {} does not match with: ", string, this.getIssuer()); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - } - - String[] s1 = string.split("tw:"); - String[] s2 = s1[1].split(":"); - String timeWindowVal = s2[0];// number [of minutes, hours, days...] - String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year - - String actor = null; - String operation = null; - String target = null; - try { - actor = getActor(pipFinder).iterator().next(); - operation = getRecipe(pipFinder).iterator().next(); - target = getTarget(pipFinder).iterator().next(); - } catch (Exception e) { - logger.debug("could not retrieve actor, operation, or target from PIP finder", e); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - - String timeWindow = timeWindowVal + " " + timeWindowScale; - - logger.debug("Going to query DB about: {} {} {} {}", actor, operation, target, timeWindow); - int countFromDB = getCountFromDB(actor, operation, target, timeWindow); - - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - - this.addIntegerAttribute(stdPIPResponse, - new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), - new IdentifierImpl(XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT), - countFromDB, - pipRequest); - - return new StdPIPResponse(stdPIPResponse); - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - } catch (PIPException ex) { - logger.error("getAttribute threw:", ex); - return null; - } - if (pipResponse == null) { - return null; - } - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - if (logger.isWarnEnabled()) { - logger.warn("PIP response error {}: {}", pipRequest.getAttributeId().stringValue(), pipResponse.getStatus().toString()); - } - return null; - } - if (pipResponse.getAttributes() != null && pipResponse.getAttributes().isEmpty()) { - if (logger.isWarnEnabled()) { - logger.warn("No attributes in POP response {}: {}", pipRequest.getAttributeId().stringValue(), pipResponse.getStatus().toString()); - } - return null; - } - return pipResponse; - } - - private Set getActor(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private Set getRecipe(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { - AttributeValue attributeValue = null; - try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); - } catch (Exception ex) { - logger.error("Failed to convert {} to an AttributeValue",value, ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); - } - } - - private Set getTarget(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - - return setATTUIDs; - } - - private static int getCountFromDB(String actor, String operation, String target, String timeWindow){ - // DB Properties - Properties props = new Properties(); - props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); - props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); - props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); - - - EntityManager em = null; - String opsHistPU = System.getProperty("OperationsHistoryPU"); - if (opsHistPU == null || !opsHistPU.equals("TestOperationsHistoryPU")){ - opsHistPU = "OperationsHistoryPU"; - } - else { - props.clear(); - } - - try { - em = Persistence.createEntityManagerFactory(opsHistPU, props).createEntityManager(); - } catch(Exception ex){ - logger.error("PIP thread got Exception. Can't connect to Operations History DB -- {}", opsHistPU); - logger.error("getCountFromDB threw: ", ex); - return -1; - } - - long now = new Date().getTime(); - long diff; - try { - diff = now - getMSFromTimeWindow(timeWindow); - } catch (Exception ex) { - logger.error("PIP thread got Exception " + ex); - return -1; - } - - StringBuilder sqlBuilder = new StringBuilder(); - sqlBuilder.append("select count(*) as count from operationshistory10 where outcome<>'Failure_Guard'"); - sqlBuilder.append(" and actor= ?"); - sqlBuilder.append(" and operation= ?"); - sqlBuilder.append(" and target= ?"); - sqlBuilder.append(" and endtime between '"); - sqlBuilder.append(new Timestamp(diff)); - sqlBuilder.append("' and '"); - sqlBuilder.append(new Timestamp(now)); - sqlBuilder.append('\''); - - Query nq = em.createNativeQuery(sqlBuilder.toString()); - nq.setParameter(1, actor); - nq.setParameter(2, operation); - nq.setParameter(3, target); - - int ret = -1; - try { - ret = ((Number)nq.getSingleResult()).intValue(); - } - catch(NoResultException | NonUniqueResultException ex){ - logger.error("getCountFromDB threw: ", ex); - return -1; - } - - em.close(); - - return ret; - } - - /** - * Get the Millisecond time from a time window string - * @param timeWindow the time window string to parse - * @return the millisecond time from the time window string - * @throws PIPException On invalid time window strings - */ - private static long getMSFromTimeWindow(String timeWindowString) throws PIPException { - long ms = 0; - double multiplier = 0; - - String[] split = timeWindowString.split(" "); - if (split.length != 2) { - throw new PIPException("Invalid Value Unit pair for SQL"); - } - - ms = Long.parseLong(split[0]); - - if("SECOND".compareToIgnoreCase(split[1]) == 0){ - multiplier = 1000; - } - else if("MINUTE".compareToIgnoreCase(split[1]) == 0){ - multiplier = 60000; - } - else if("HOUR".compareToIgnoreCase(split[1]) == 0){ - multiplier = 3.6e+6; - } - else if("DAY".compareToIgnoreCase(split[1]) == 0){ - multiplier = 8.64e+7; - } - else if("WEEK".compareToIgnoreCase(split[1]) == 0){ - multiplier = 6.048e+8; - } - else if("MONTH".compareToIgnoreCase(split[1]) == 0){ - multiplier = 2.628e+9; - } - else if("QUARTER".compareToIgnoreCase(split[1]) == 0){ - multiplier = 2.628e+9 * 3; - } - else if("YEAR".compareToIgnoreCase(split[1]) == 0){ - multiplier = 3.154e+10; - } - else{ - logger.error("{} not supported", split[1]); - } - - ms *= multiplier; - return ms; - } +public class PIPEngineGetHistory extends StdConfigurableEngine { + private static final Logger logger = LoggerFactory.getLogger(PIPEngineGetHistory.class); + + // + // Base issuer string. The issuer in the policy will also contain time window information + // E.g., "com:att:research:xacml:guard:historydb:tw:10:min" + // + public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb"; + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + + private static final String XML_SCHEMA_STRING = "http://www.w3.org/2001/XMLSchema#string"; + + private static final String XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT = + "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + private static final String XACML_ACTOR_ACTOR_ID = "urn:oasis:names:tc:xacml:1.0:actor:actor-id"; + private static final String XACML_ATTRIBUTE_CATEGORY_ACTION = + "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + private static final String XACML_OPERATION_OPERATION_ID = "urn:oasis:names:tc:xacml:1.0:operation:operation-id"; + private static final String XACML_ATTRIBUTE_CATEGORY_RESOURCE = + "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + private static final String XACML_TARGET_TARGET_ID = "urn:oasis:names:tc:xacml:1.0:target:target-id"; + private static final String XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT = + "com:att:research:xacml:test:sql:resource:operations:count"; + + private static final PIPRequest PIP_REQUEST_ACTOR = + new StdPIPRequest(new IdentifierImpl(XACML_SUBJECT_CATEGORY_ACCESS_SUBJECT), + new IdentifierImpl(XACML_ACTOR_ACTOR_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + private static final PIPRequest PIP_REQUEST_RECIPE = + new StdPIPRequest(new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_ACTION), + new IdentifierImpl(XACML_OPERATION_OPERATION_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + private static final PIPRequest PIP_REQUEST_TARGET = + new StdPIPRequest(new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), + new IdentifierImpl(XACML_TARGET_TARGET_ID), new IdentifierImpl(XML_SCHEMA_STRING)); + + public PIPEngineGetHistory() { + super(); + } + + @Override + public Collection attributesRequired() { + return Collections.emptySet(); + } + + @Override + public Collection attributesProvided() { + return Collections.emptySet(); + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + logger.debug("Entering FeqLimiter PIP"); + + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + + logger.debug("No issuer in the request..."); + logger.debug("FeqLimiter PIP - No issuer in the request!"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } else { + // Notice, we are checking here for the base issuer prefix. + if (!string.contains(this.getIssuer())) { + logger.debug("Requested issuer '{}' does not match {}", string, getIssuer()); + logger.debug("FeqLimiter PIP - Issuer {} does not match with: ", string, this.getIssuer()); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + } + + String[] s1 = string.split("tw:"); + String[] s2 = s1[1].split(":"); + String timeWindowVal = s2[0];// number [of minutes, hours, days...] + String timeWindowScale = s2[1];// e.g., minute, hour, day, week, month, year + + String actor = null; + String operation = null; + String target = null; + try { + actor = getActor(pipFinder).iterator().next(); + operation = getRecipe(pipFinder).iterator().next(); + target = getTarget(pipFinder).iterator().next(); + } catch (Exception e) { + logger.debug("could not retrieve actor, operation, or target from PIP finder", e); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + + String timeWindow = timeWindowVal + " " + timeWindowScale; + + logger.debug("Going to query DB about: {} {} {} {}", actor, operation, target, timeWindow); + int countFromDb = getCountFromDb(actor, operation, target, timeWindow); + + StdMutablePIPResponse stdPipResponse = new StdMutablePIPResponse(); + + this.addIntegerAttribute(stdPipResponse, new IdentifierImpl(XACML_ATTRIBUTE_CATEGORY_RESOURCE), + new IdentifierImpl(XACML_TEST_SQL_RESOURCE_OPERATIONS_COUNT), countFromDb, pipRequest); + + return new StdPIPResponse(stdPipResponse); + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + } catch (PIPException ex) { + logger.error("getAttribute threw:", ex); + return null; + } + if (pipResponse == null) { + return null; + } + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + if (logger.isWarnEnabled()) { + logger.warn("PIP response error {}: {}", pipRequest.getAttributeId().stringValue(), + pipResponse.getStatus().toString()); + } + return null; + } + if (pipResponse.getAttributes() != null && pipResponse.getAttributes().isEmpty()) { + if (logger.isWarnEnabled()) { + logger.warn("No attributes in POP response {}: {}", pipRequest.getAttributeId().stringValue(), + pipResponse.getStatus().toString()); + } + return null; + } + return pipResponse; + } + + private Set getActor(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private Set getRecipe(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private void addIntegerAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, Identifier attributeId, + int value, PIPRequest pipRequest) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + logger.error("Failed to convert {} to an AttributeValue", value, ex); + } + if (attributeValue != null) { + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer()/* this.getIssuer() */, false)); + } + } + + private Set getTarget(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseAttUid = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); + if (pipResponseAttUid == null) { + return new HashSet<>(); + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listAttUids = pipResponseAttUid.getAttributes(); + Set setAttUids = new HashSet<>(); + for (Attribute attributeAttUid : listAttUids) { + Iterator> iterAttributeValues = attributeAttUid.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setAttUids.add(attuid); + } + } + } + } + + return setAttUids; + } + + private static int getCountFromDb(String actor, String operation, String target, String timeWindow) { + // DB Properties + Properties props = new Properties(); + props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL)); + props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER)); + props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS)); + + + EntityManager em = null; + String opsHistPu = System.getProperty("OperationsHistoryPU"); + if (opsHistPu == null || !opsHistPu.equals("TestOperationsHistoryPU")) { + opsHistPu = "OperationsHistoryPU"; + } else { + props.clear(); + } + + try { + em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager(); + } catch (Exception ex) { + logger.error("PIP thread got Exception. Can't connect to Operations History DB -- {}", opsHistPu); + logger.error("getCountFromDb threw: ", ex); + return -1; + } + + long now = new Date().getTime(); + long diff; + try { + diff = now - getMsFromTimeWindow(timeWindow); + } catch (Exception ex) { + logger.error("PIP thread got Exception " + ex); + return -1; + } + + StringBuilder sqlBuilder = new StringBuilder(); + sqlBuilder.append("select count(*) as count from operationshistory10 where outcome<>'Failure_Guard'"); + sqlBuilder.append(" and actor= ?"); + sqlBuilder.append(" and operation= ?"); + sqlBuilder.append(" and target= ?"); + sqlBuilder.append(" and endtime between '"); + sqlBuilder.append(new Timestamp(diff)); + sqlBuilder.append("' and '"); + sqlBuilder.append(new Timestamp(now)); + sqlBuilder.append('\''); + + Query nq = em.createNativeQuery(sqlBuilder.toString()); + nq.setParameter(1, actor); + nq.setParameter(2, operation); + nq.setParameter(3, target); + + int ret = -1; + try { + ret = ((Number) nq.getSingleResult()).intValue(); + } catch (NoResultException | NonUniqueResultException ex) { + logger.error("getCountFromDb threw: ", ex); + return -1; + } + + em.close(); + + return ret; + } + + /** + * Get the Millisecond time from a time window string. + * + * @param timeWindow the time window string to parse + * @return the millisecond time from the time window string + * @throws PIPException On invalid time window strings + */ + private static long getMsFromTimeWindow(String timeWindowString) throws PIPException { + long ms = 0; + double multiplier = 0; + + String[] split = timeWindowString.split(" "); + if (split.length != 2) { + throw new PIPException("Invalid Value Unit pair for SQL"); + } + + ms = Long.parseLong(split[0]); + + if ("SECOND".compareToIgnoreCase(split[1]) == 0) { + multiplier = 1000; + } else if ("MINUTE".compareToIgnoreCase(split[1]) == 0) { + multiplier = 60000; + } else if ("HOUR".compareToIgnoreCase(split[1]) == 0) { + multiplier = 3.6e+6; + } else if ("DAY".compareToIgnoreCase(split[1]) == 0) { + multiplier = 8.64e+7; + } else if ("WEEK".compareToIgnoreCase(split[1]) == 0) { + multiplier = 6.048e+8; + } else if ("MONTH".compareToIgnoreCase(split[1]) == 0) { + multiplier = 2.628e+9; + } else if ("QUARTER".compareToIgnoreCase(split[1]) == 0) { + multiplier = 2.628e+9 * 3; + } else if ("YEAR".compareToIgnoreCase(split[1]) == 0) { + multiplier = 3.154e+10; + } else { + logger.error("{} not supported", split[1]); + } + + ms *= multiplier; + return ms; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java index c23dc35cd..47faa88c2 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.guard; import java.util.HashMap; @@ -31,97 +32,122 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PolicyGuard { - private PolicyGuard() { - // Cannot instantiate this static class - } - - private static Map activeLocks = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + private PolicyGuard() { + // Cannot instantiate this static class + } + + private static Map activeLocks = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(PolicyGuard.class); + + public static class LockResult { + private A parameterA; + private B parameterB; + + public static LockResult createLockResult(A parameterA, B parameterB) { + return new LockResult<>(parameterA, parameterB); + } + + public LockResult(A parameterA, B parameterB) { + this.parameterA = parameterA; + this.parameterB = parameterB; + } + + public A getA() { + return parameterA; + } + + public B getB() { + return parameterB; + } + } + + /** + * Lock a target. + * + * @param targetType the target type + * @param targetInstance the target instance + * @param requestID the request Id + * @param callback the LockCallback + * @return the LockResult + */ + public static LockResult lockTarget(TargetType targetType, String targetInstance, + UUID requestID, LockCallback callback) { + + synchronized (activeLocks) { + // + // Is there a lock on this instance already? + // + if (activeLocks.containsKey(targetInstance)) { + return LockResult.createLockResult(GuardResult.LOCK_DENIED, null); + } + TargetLock lock = null; + switch (targetType) { + case PNF: + // + // Create the Lock object + // + lock = new PNFTargetLock(targetType, targetInstance, requestID, callback); + break; + case VM: + // + // Create the Lock object + // + lock = new VMTargetLock(targetType, targetInstance, requestID, callback); + break; + case VNF: + // + // Create the Lock object + // + lock = new VNFTargetLock(targetType, targetInstance, requestID, callback); + break; + + default: + return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); + } + // + // Keep track of it + // + activeLocks.put(targetInstance, lock); + // + // Return result + // + logger.debug("Locking {}", lock); + return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); + } + } - public static class LockResult { - private A a; - private B b; - - public static LockResult createLockResult(A a, B b) { - return new LockResult<>(a, b); - } - - public LockResult(A a, B b) { - this.a = a; - this.b = b; - } - - public A getA() { - return a; - } - - public B getB() { - return b; - } - } - - public static LockResult lockTarget(TargetType targetType, String targetInstance, UUID requestID, LockCallback callback) { - - synchronized(activeLocks) { - // - // Is there a lock on this instance already? - // - if (activeLocks.containsKey(targetInstance)) { - return LockResult.createLockResult(GuardResult.LOCK_DENIED, null); - } - TargetLock lock = null; - switch (targetType) { - case PNF: - // - // Create the Lock object - // - lock = new PNFTargetLock(targetType, targetInstance, requestID, callback); - break; - case VM: - // - // Create the Lock object - // - lock = new VMTargetLock(targetType, targetInstance, requestID, callback); - break; - case VNF: - // - // Create the Lock object - // - lock = new VNFTargetLock(targetType, targetInstance, requestID, callback); - break; + /** + * Unlock a target. + * + * @param lock the target lock to unlock + * @return true if the target is successfully unlocked, false + * otherwise + */ + public static boolean unlockTarget(TargetLock lock) { + synchronized (activeLocks) { + if (activeLocks.containsKey(lock.getTargetInstance())) { + logger.debug("Unlocking {}", lock); + return (activeLocks.remove(lock.getTargetInstance()) != null); + } + return false; + } + } - default: - return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); - } - // - // Keep track of it - // - activeLocks.put(targetInstance, lock); - // - // Return result - // - logger.debug("Locking {}", lock); - return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); - } - } - - public static boolean unlockTarget(TargetLock lock) { - synchronized(activeLocks) { - if (activeLocks.containsKey(lock.getTargetInstance())) { - logger.debug("Unlocking {}", lock); - return (activeLocks.remove(lock.getTargetInstance()) != null); - } - return false; - } - } - - public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) { - synchronized(activeLocks) { - if (activeLocks.containsKey(targetInstance)) { - TargetLock lock = activeLocks.get(targetInstance); - return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID)); - } - return false; - } - } + /** + * Check if a target is locked. + * + * @param targetType the target type + * @param targetInstance the target instance + * @param requestID the request Id + * @return true if the target is locked, false otherwise + */ + public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) { + synchronized (activeLocks) { + if (activeLocks.containsKey(targetInstance)) { + TargetLock lock = activeLocks.get(targetInstance); + return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID)); + } + return false; + } + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java index 20c9665ce..bca31d904 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java @@ -23,54 +23,62 @@ package org.onap.policy.guard; import java.util.UUID; public class PolicyGuardRequest { - private String actor; - private String target; - private UUID requestID; - private String operation; - - public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { - super(); - this.actor = actor; - this.target = target; - this.requestID = requestID; - this.operation = operation; - } - - @Override - public String toString() { - return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestID + ", operation=" - + operation + "]"; - } + private String actor; + private String target; + private UUID requestId; + private String operation; - public String getActor() { - return actor; - } + /** + * Construct an instance. + * + * @param actor the actor + * @param target the target + * @param requestID the request Id + * @param operation the operation + */ + public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { + super(); + this.actor = actor; + this.target = target; + this.requestId = requestID; + this.operation = operation; + } - public void setActor(String actor) { - this.actor = actor; - } + @Override + public String toString() { + return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestId + ", operation=" + + operation + "]"; + } - public String getTarget() { - return target; - } + public String getActor() { + return actor; + } - public void setTarget(String target) { - this.target = target; - } + public void setActor(String actor) { + this.actor = actor; + } - public UUID getRequestID() { - return requestID; - } + public String getTarget() { + return target; + } - public void setRequestID(UUID requestID) { - this.requestID = requestID; - } + public void setTarget(String target) { + this.target = target; + } - public String getOperation() { - return operation; - } + public UUID getRequestID() { + return requestId; + } - public void setOperation(String operation) { - this.operation = operation; - } -} \ No newline at end of file + public void setRequestID(UUID requestID) { + this.requestId = requestID; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java index 110fbe0ab..e9ff435f8 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java @@ -22,38 +22,50 @@ package org.onap.policy.guard; import java.util.UUID; -public class PolicyGuardResponse{ - private UUID requestID; - private String operation; - private String result; - - public PolicyGuardResponse(String result, UUID req, String op) { - this.result = result; - this.requestID = req; - this.operation = op; - } - - @Override - public String toString() { - return "PolicyGuardResponse [requestID=" + requestID + ", operation=" + operation + ", result=" + result + "]"; - } - - public UUID getRequestID() { - return requestID; - } - public void setRequestID(UUID requestID) { - this.requestID = requestID; - } - public String getResult() { - return result; - } - public void setResult(String result) { - this.result = result; - } - public String getOperation() { - return operation; - } - public void setOperation(String operation) { - this.operation = operation; - } -} \ No newline at end of file +public class PolicyGuardResponse { + private UUID requestId; + private String operation; + private String result; + + /** + * Create an instance. + * + * @param result the result + * @param req the request Id + * @param op the operation + */ + public PolicyGuardResponse(String result, UUID req, String op) { + this.result = result; + this.requestId = req; + this.operation = op; + } + + @Override + public String toString() { + return "PolicyGuardResponse [requestID=" + requestId + ", operation=" + operation + ", result=" + result + "]"; + } + + public UUID getRequestID() { + return requestId; + } + + public void setRequestID(UUID requestID) { + this.requestId = requestID; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java index a81da89d7..777240fea 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -20,6 +20,11 @@ package org.onap.policy.guard; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeCategory; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Result; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -40,391 +45,395 @@ import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeCategory; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Result; - public class PolicyGuardXacmlHelper { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); - private static final Logger netLogger = LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER); - - // Constant for the systme line separator - private static final String SYSTEM_LS = System.lineSeparator(); - - public PolicyGuardXacmlHelper() { - init(PolicyEngine.manager.getEnvironment()); - } - - // initialized from 'pdpx.url' property -- - // Each entry in 'restUrls' contains a destination URL, and an optional - // 'Authorization' header entry. 'restUrlIndex' indicates the next - // entry to try -- after each failure, the index is advanced to the - // next entry (wrapping to the beginning, if needed). - private static class URLEntry implements Serializable { - private static final long serialVersionUID = -8859237552195400518L; - - URL restURL; - String authorization = null; - String clientAuth = null; - String environment = null; - } - - private URLEntry[] restUrls = null; - private int restUrlIndex = 0; - - // REST timeout, initialized from 'pdpx.timeout' property - private int timeout = 20000; - - public String callPDP(PolicyGuardXacmlRequestAttributes xacmlReq) { - // - // Send it to the PDP - // - String response = null; - - // - // Build the json request - // - JSONObject attributes = new JSONObject(); - attributes.put("actor", xacmlReq.getActorID()); - attributes.put("recipe", xacmlReq.getOperationID()); - attributes.put("target", xacmlReq.getTargetID()); - if (xacmlReq.getClnameID() != null) { - attributes.put("clname", xacmlReq.getClnameID()); - } - JSONObject jsonReq = new JSONObject(); - jsonReq.put("decisionAttributes", attributes); - jsonReq.put("onapName", "PDPD"); - - - try { - // - // Call RESTful PDP - // - URLEntry urlEntry = restUrls[restUrlIndex]; - String jsonRequestString = jsonReq.toString(); - netLogger.info("[OUT|{}|{}|]{}{}", "GUARD", urlEntry.restURL, SYSTEM_LS, jsonRequestString); - response = callRESTfulPDP(new ByteArrayInputStream(jsonReq - .toString().getBytes()), urlEntry.restURL, - urlEntry.authorization, urlEntry.clientAuth, - urlEntry.environment); - netLogger.info("[IN|{}|{}|]{}{}", "GUARD", urlEntry.restURL, SYSTEM_LS, response); - } catch (Exception e) { - logger.error("Error in sending RESTful request: ", e); - } - - return response; - } - - /** - * This makes an HTTP POST call to a running PDP RESTful servlet to get a - * decision. - * - * @param file - * @return response from guard which contains "Permit" or "Deny" - */ - private String callRESTfulPDP(InputStream is, URL restURL, String authorization, String clientauth, String environment) { - HttpURLConnection connection = null; - - try { - // - // Open up the connection - // - connection = (HttpURLConnection) restURL.openConnection(); - connection.setRequestProperty("Content-Type", "application/json"); - // - // Setup our method and headers - // - connection.setRequestProperty("Accept", "application/json"); - if (authorization != null) { - connection.setRequestProperty("Authorization", authorization); - } - if (clientauth != null) { - connection.setRequestProperty("ClientAuth", clientauth); - } - if (environment != null) { - connection.setRequestProperty("Environment", environment); - } - connection.setConnectTimeout(timeout); - connection.setReadTimeout(timeout); - connection.setRequestMethod("POST"); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - // - // Send the request - // - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy(is, os); - } - - // - // Do the connect - // - connection.connect(); - - if (connection.getResponseCode() != 200) { - logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); - return Util.INDETERMINATE; - } - } catch (Exception e) { - logger.error("Exception in 'PolicyGuardXacmlHelper.callRESTfulPDP'", e); - return Util.INDETERMINATE; - } - - // - // Read the response - // - try { - ContentType contentType = ContentType.parse(connection.getContentType()); - - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - InputStream iStream = connection.getInputStream(); - int contentLength = connection.getContentLength(); - - return readResponseFromStream(iStream, contentLength); - } else { - logger.error("unknown content-type: {}", contentType); - return Util.INDETERMINATE; - } - - } catch (Exception e) { - String message = "Parsing Content-Type: " + connection.getContentType(); - logger.error(message, e); - return Util.INDETERMINATE; - } - } - - public static PolicyGuardResponse parseXACMLPDPResponse(com.att.research.xacml.api.Response xacmlResponse) { - if (xacmlResponse == null) { - // - // In case the actual XACML response was null, create an empty - // response object with decision "Indeterminate" - // - return new PolicyGuardResponse("Indeterminate", null, ""); - } - - Iterator itRes = xacmlResponse.getResults().iterator(); - - Result res = itRes.next(); - String decisionFromXACMLResponse = res.getDecision().toString(); - Iterator itAttrCat = res.getAttributes().iterator(); - UUID reqIDFromXACMLResponse = null; - String operationFromXACMLResponse = ""; - - while (itAttrCat.hasNext()) { - Iterator itAttr = itAttrCat.next().getAttributes() - .iterator(); - while (itAttr.hasNext()) { - Attribute currentAttr = itAttr.next(); - String s = currentAttr.getAttributeId().stringValue(); - if ("urn:oasis:names:tc:xacml:1.0:request:request-id".equals(s)) { - Iterator> itValues = currentAttr.getValues().iterator(); - reqIDFromXACMLResponse = UUID.fromString(itValues .next().getValue().toString()); - } - if ("urn:oasis:names:tc:xacml:1.0:operation:operation-id" .equals(s)) { - Iterator> itValues = currentAttr.getValues().iterator(); - operationFromXACMLResponse = itValues.next().getValue().toString(); - } - } - } - - return new PolicyGuardResponse(decisionFromXACMLResponse, - reqIDFromXACMLResponse, operationFromXACMLResponse); - - } - - private void init(Properties properties) { - // used to store error messages - StringBuilder sb = new StringBuilder(); - - // fetch these parameters, if they exist - String timeoutString = properties.getProperty("pdpx.timeout"); - String disabledString = properties.getProperty("guard.disabled"); - - if (disabledString != null && Boolean.parseBoolean(disabledString)) { - return; - } - - ArrayList entries = initEntries(properties, sb); - - if (entries.isEmpty()) { - sb.append("'pdpx.*' -- no URLs specified, "); - } else { - restUrls = entries.toArray(new URLEntry[0]); - } - - if (timeoutString != null) { - try { - // decode optional 'pdpx.timeout' parameter - timeout = Integer.valueOf(timeoutString); - } catch (NumberFormatException e) { - sb.append("'pdpx.timeout': " + e + ", "); - logger.trace(e.getLocalizedMessage()); - } - } - - - // if there are any errors, update 'errorMessage' & disable guard - // queries - if (sb.length() != 0) { - // remove the terminating ", ", and extract resulting error message - sb.setLength(sb.length() - 2); - String errorMessage = sb.toString(); - logger.error("Initialization failure: {}", errorMessage); - } - } - - private ArrayList initEntries(Properties properties, StringBuilder sb) { - // now, see which numeric entries (1-9) exist - ArrayList entries = new ArrayList<>(); - - for (int index = 0; index < 10; index += 1) { - String urlPrefix = "guard."; - if (index != 0) { - urlPrefix = urlPrefix + index + "."; - } - - // see if the associated URL exists - String restURLlist = properties.getProperty(urlPrefix + "url"); - if (nullOrEmpty(restURLlist)) { - // no entry for this index - continue; - } - - // support a list of entries separated by semicolons. Each entry - // can be: - // URL - // URL,user - // URL,user,password - for (String restURL : restURLlist.split("\\s*;\\s*")) { - URLEntry entry = initRestURL(properties, sb, restURL); - // include this URLEntry in the list - if (entry != null) { - entries.add(entry); - } - } - } - - return entries; - } - - private URLEntry initRestURL(Properties properties, StringBuilder sb, String restURL) { - String urlPrefix = "guard."; - String pdpxPrefix = "pdpx."; - - String[] segments = restURL.split("\\s*,\\s*"); - String user = null; - String password = null; - - if (segments.length >= 2) { - // user id is provided - restURL = segments[0]; - user = segments[1]; - if (segments.length >= 3) { - // password is also provided - password = segments[2]; - } - } - - // URL does exist -- create the entry - URLEntry urlEntry = new URLEntry(); - try { - urlEntry.restURL = new URL(restURL); - } catch (java.net.MalformedURLException e) { - // if we don't have a URL, - // don't bother with the rest on this one - sb.append("'").append(urlPrefix).append("url' '") - .append(restURL).append("': ").append(e) - .append(","); - return null; - } - - if (nullOrEmpty(user)) { - // user id was not provided on '*.url' line -- - // extract it from a separate property - user = properties.getProperty(pdpxPrefix + "username", properties.getProperty("pdpx.username")); - } - if (nullOrEmpty(password)) { - // password was not provided on '*.url' line -- - // extract it from a separate property - password = properties.getProperty(pdpxPrefix + "password", properties.getProperty("pdpx.password")); - } - - // see if 'user' and 'password' entries both exist - if (!nullOrEmpty(user) && !nullOrEmpty(password)) { - urlEntry.authorization = "Basic " - + Base64.getEncoder().encodeToString( - (user + ":" + password).getBytes()); - } - - // see if 'client.user' and 'client.password' entries both exist - String clientUser = properties.getProperty(pdpxPrefix + "client.username", properties.getProperty("pdpx.client.username")); - String clientPassword = properties.getProperty(pdpxPrefix + "client.password", properties.getProperty("pdpx.client.password")); - if (!nullOrEmpty(clientUser) && !nullOrEmpty(clientPassword)) { - urlEntry.clientAuth = "Basic " - + Base64.getEncoder().encodeToString( - (clientUser + ":" + clientPassword) - .getBytes()); - } - - // see if there is an 'environment' entry - String environment = properties.getProperty(pdpxPrefix + "environment", properties.getProperty("pdpx.environment")); - if (!nullOrEmpty(environment)) { - urlEntry.environment = environment; - } - - return urlEntry; - } - - /** - * Check if a string is null or an empty string - * - * @param value - * the string to be tested - * @return 'true' if the string is 'null' or has a length of 0, 'false' - * otherwise - */ - private static boolean nullOrEmpty(String value) { - return (value == null || value.isEmpty()); - } - - private static String readResponseFromStream(InputStream iStream, int contentLength) throws IOException { - // if content length is -1, response is chunked, and - // TCP connection will be dropped at the end - byte[] buf = new byte[contentLength < 0 ? 1024: contentLength]; - int offset = 0; - do { - int size = iStream.read(buf, offset, buf.length - offset); - if (size < 0) { - // In a chunked response a dropped connection is expected, but not if the response is not chunked - if (contentLength > 0) { - logger.error("partial input stream"); - } - break; - } - offset += size; - } while (offset != contentLength); - - String response = new String(buf, 0, offset); - - // - // Connection may have failed or not been 200 OK, return Indeterminate - // - if (response.isEmpty()) { - return Util.INDETERMINATE; - } - - return new JSONObject(response).getString("decision"); - - } + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); + private static final Logger netLogger = + LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER); + + // Constant for the systme line separator + private static final String SYSTEM_LS = System.lineSeparator(); + + public PolicyGuardXacmlHelper() { + init(PolicyEngine.manager.getEnvironment()); + } + + // initialized from 'pdpx.url' property -- + // Each entry in 'restUrls' contains a destination URL, and an optional + // 'Authorization' header entry. 'restUrlIndex' indicates the next + // entry to try -- after each failure, the index is advanced to the + // next entry (wrapping to the beginning, if needed). + private static class UrlEntry implements Serializable { + private static final long serialVersionUID = -8859237552195400518L; + + URL restUrl; + String authorization = null; + String clientAuth = null; + String environment = null; + } + + private UrlEntry[] restUrls = null; + private int restUrlIndex = 0; + + // REST timeout, initialized from 'pdpx.timeout' property + private int timeout = 20000; + + /** + * Call PDP. + * + * @param xacmlReq the XACML request + * @return the response + */ + public String callPDP(PolicyGuardXacmlRequestAttributes xacmlReq) { + // + // Send it to the PDP + // + String response = null; + + // + // Build the json request + // + JSONObject attributes = new JSONObject(); + attributes.put("actor", xacmlReq.getActorID()); + attributes.put("recipe", xacmlReq.getOperationID()); + attributes.put("target", xacmlReq.getTargetID()); + if (xacmlReq.getClnameID() != null) { + attributes.put("clname", xacmlReq.getClnameID()); + } + JSONObject jsonReq = new JSONObject(); + jsonReq.put("decisionAttributes", attributes); + jsonReq.put("onapName", "PDPD"); + + + try { + // + // Call RESTful PDP + // + UrlEntry urlEntry = restUrls[restUrlIndex]; + String jsonRequestString = jsonReq.toString(); + netLogger.info("[OUT|{}|{}|]{}{}", "GUARD", urlEntry.restUrl, SYSTEM_LS, jsonRequestString); + response = callRESTfulPDP(new ByteArrayInputStream(jsonReq.toString().getBytes()), urlEntry.restUrl, + urlEntry.authorization, urlEntry.clientAuth, urlEntry.environment); + netLogger.info("[IN|{}|{}|]{}{}", "GUARD", urlEntry.restUrl, SYSTEM_LS, response); + } catch (Exception e) { + logger.error("Error in sending RESTful request: ", e); + } + + return response; + } + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param is the InputStream + * @param authorization the Authorization + * @param clientauth the ClientAuth + * @param environment the Environment + * @return response from guard which contains "Permit" or "Deny" + */ + private String callRESTfulPDP(InputStream is, URL restURL, String authorization, String clientauth, + String environment) { + HttpURLConnection connection = null; + + try { + // + // Open up the connection + // + connection = (HttpURLConnection) restURL.openConnection(); + connection.setRequestProperty("Content-Type", "application/json"); + // + // Setup our method and headers + // + connection.setRequestProperty("Accept", "application/json"); + if (authorization != null) { + connection.setRequestProperty("Authorization", authorization); + } + if (clientauth != null) { + connection.setRequestProperty("ClientAuth", clientauth); + } + if (environment != null) { + connection.setRequestProperty("Environment", environment); + } + connection.setConnectTimeout(timeout); + connection.setReadTimeout(timeout); + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // + // Send the request + // + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(is, os); + } + + // + // Do the connect + // + connection.connect(); + + if (connection.getResponseCode() != 200) { + logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); + return Util.INDETERMINATE; + } + } catch (Exception e) { + logger.error("Exception in 'PolicyGuardXacmlHelper.callRESTfulPDP'", e); + return Util.INDETERMINATE; + } + + // + // Read the response + // + try { + ContentType contentType = ContentType.parse(connection.getContentType()); + + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + InputStream inputStream = connection.getInputStream(); + int contentLength = connection.getContentLength(); + + return readResponseFromStream(inputStream, contentLength); + } else { + logger.error("unknown content-type: {}", contentType); + return Util.INDETERMINATE; + } + + } catch (Exception e) { + String message = "Parsing Content-Type: " + connection.getContentType(); + logger.error(message, e); + return Util.INDETERMINATE; + } + } + + /** + * Parse XACML PDP response. + * + * @param xacmlResponse the XACML response + * @return the PolicyGuardResponse + */ + public static PolicyGuardResponse parseXACMLPDPResponse(com.att.research.xacml.api.Response xacmlResponse) { + if (xacmlResponse == null) { + // + // In case the actual XACML response was null, create an empty + // response object with decision "Indeterminate" + // + return new PolicyGuardResponse("Indeterminate", null, ""); + } + + Iterator itRes = xacmlResponse.getResults().iterator(); + + Result res = itRes.next(); + String decisionFromXacmlResponse = res.getDecision().toString(); + Iterator itAttrCat = res.getAttributes().iterator(); + UUID reqIdFromXacmlResponse = null; + String operationFromXacmlResponse = ""; + + while (itAttrCat.hasNext()) { + Iterator itAttr = itAttrCat.next().getAttributes().iterator(); + while (itAttr.hasNext()) { + Attribute currentAttr = itAttr.next(); + String attributeId = currentAttr.getAttributeId().stringValue(); + if ("urn:oasis:names:tc:xacml:1.0:request:request-id".equals(attributeId)) { + Iterator> itValues = currentAttr.getValues().iterator(); + reqIdFromXacmlResponse = UUID.fromString(itValues.next().getValue().toString()); + } + if ("urn:oasis:names:tc:xacml:1.0:operation:operation-id".equals(attributeId)) { + Iterator> itValues = currentAttr.getValues().iterator(); + operationFromXacmlResponse = itValues.next().getValue().toString(); + } + } + } + + return new PolicyGuardResponse(decisionFromXacmlResponse, reqIdFromXacmlResponse, operationFromXacmlResponse); + + } + + private void init(Properties properties) { + // used to store error messages + StringBuilder sb = new StringBuilder(); + + // fetch these parameters, if they exist + String timeoutString = properties.getProperty("pdpx.timeout"); + String disabledString = properties.getProperty("guard.disabled"); + + if (disabledString != null && Boolean.parseBoolean(disabledString)) { + return; + } + + ArrayList entries = initEntries(properties, sb); + + if (entries.isEmpty()) { + sb.append("'pdpx.*' -- no URLs specified, "); + } else { + restUrls = entries.toArray(new UrlEntry[0]); + } + + if (timeoutString != null) { + try { + // decode optional 'pdpx.timeout' parameter + timeout = Integer.valueOf(timeoutString); + } catch (NumberFormatException e) { + sb.append("'pdpx.timeout': " + e + ", "); + logger.trace(e.getLocalizedMessage()); + } + } + + + // if there are any errors, update 'errorMessage' & disable guard + // queries + if (sb.length() != 0) { + // remove the terminating ", ", and extract resulting error message + sb.setLength(sb.length() - 2); + String errorMessage = sb.toString(); + logger.error("Initialization failure: {}", errorMessage); + } + } + + private ArrayList initEntries(Properties properties, StringBuilder sb) { + // now, see which numeric entries (1-9) exist + ArrayList entries = new ArrayList<>(); + + for (int index = 0; index < 10; index += 1) { + String urlPrefix = "guard."; + if (index != 0) { + urlPrefix = urlPrefix + index + "."; + } + + // see if the associated URL exists + String restUrllist = properties.getProperty(urlPrefix + "url"); + if (nullOrEmpty(restUrllist)) { + // no entry for this index + continue; + } + + // support a list of entries separated by semicolons. Each entry + // can be: + // URL + // URL,user + // URL,user,password + for (String restUrl : restUrllist.split("\\s*;\\s*")) { + UrlEntry entry = initRestUrl(properties, sb, restUrl); + // include this URLEntry in the list + if (entry != null) { + entries.add(entry); + } + } + } + + return entries; + } + + private UrlEntry initRestUrl(Properties properties, StringBuilder sb, String restUrl) { + String urlPrefix = "guard."; + String pdpxPrefix = "pdpx."; + + String[] segments = restUrl.split("\\s*,\\s*"); + String user = null; + String password = null; + + if (segments.length >= 2) { + // user id is provided + restUrl = segments[0]; + user = segments[1]; + if (segments.length >= 3) { + // password is also provided + password = segments[2]; + } + } + + // URL does exist -- create the entry + UrlEntry urlEntry = new UrlEntry(); + try { + urlEntry.restUrl = new URL(restUrl); + } catch (java.net.MalformedURLException e) { + // if we don't have a URL, + // don't bother with the rest on this one + sb.append("'").append(urlPrefix).append("url' '").append(restUrl).append("': ").append(e).append(","); + return null; + } + + if (nullOrEmpty(user)) { + // user id was not provided on '*.url' line -- + // extract it from a separate property + user = properties.getProperty(pdpxPrefix + "username", properties.getProperty("pdpx.username")); + } + if (nullOrEmpty(password)) { + // password was not provided on '*.url' line -- + // extract it from a separate property + password = properties.getProperty(pdpxPrefix + "password", properties.getProperty("pdpx.password")); + } + + // see if 'user' and 'password' entries both exist + if (!nullOrEmpty(user) && !nullOrEmpty(password)) { + urlEntry.authorization = "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes()); + } + + // see if 'client.user' and 'client.password' entries both exist + String clientUser = + properties.getProperty(pdpxPrefix + "client.username", properties.getProperty("pdpx.client.username")); + String clientPassword = + properties.getProperty(pdpxPrefix + "client.password", properties.getProperty("pdpx.client.password")); + if (!nullOrEmpty(clientUser) && !nullOrEmpty(clientPassword)) { + urlEntry.clientAuth = + "Basic " + Base64.getEncoder().encodeToString((clientUser + ":" + clientPassword).getBytes()); + } + + // see if there is an 'environment' entry + String environment = + properties.getProperty(pdpxPrefix + "environment", properties.getProperty("pdpx.environment")); + if (!nullOrEmpty(environment)) { + urlEntry.environment = environment; + } + + return urlEntry; + } + + /** + * Check if a string is null or an empty string. + * + * @param value the string to be tested + * @return 'true' if the string is 'null' or has a length of 0, 'false' otherwise + */ + private static boolean nullOrEmpty(String value) { + return (value == null || value.isEmpty()); + } + + private static String readResponseFromStream(InputStream inputStream, int contentLength) throws IOException { + // if content length is -1, response is chunked, and + // TCP connection will be dropped at the end + byte[] buf = new byte[contentLength < 0 ? 1024 : contentLength]; + int offset = 0; + do { + int size = inputStream.read(buf, offset, buf.length - offset); + if (size < 0) { + // In a chunked response a dropped connection is expected, but not if the response + // is not chunked + if (contentLength > 0) { + logger.error("partial input stream"); + } + break; + } + offset += size; + } + while (offset != contentLength); + + String response = new String(buf, 0, offset); + + // + // Connection may have failed or not been 200 OK, return Indeterminate + // + if (response.isEmpty()) { + return Util.INDETERMINATE; + } + + return new JSONObject(response).getString("decision"); + + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java index 70291001a..5e69d6435 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -20,82 +20,91 @@ package org.onap.policy.guard; - import com.att.research.xacml.std.annotations.XACMLAction; import com.att.research.xacml.std.annotations.XACMLRequest; import com.att.research.xacml.std.annotations.XACMLResource; import com.att.research.xacml.std.annotations.XACMLSubject; -@XACMLRequest(ReturnPolicyIdList=true,CombinedDecision=true) +@XACMLRequest(ReturnPolicyIdList = true, CombinedDecision = true) public class PolicyGuardXacmlRequestAttributes { - public PolicyGuardXacmlRequestAttributes(String clnameID, String actorID, String operationID, String targetID, String requestID) { - super(); - this.clnameID = clnameID; - this.actorID = actorID; - this.operationID = operationID; - this.targetID = targetID; - this.requestID = requestID; - } - - @Override - public String toString() { - return "PolicyGuardXacmlRequestAttributes [actorID=" + actorID + ", operationID=" + operationID - + ", targetID=" + targetID + ", requestID=" + requestID + "]"; - } - - @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:clname:clname-id") - String clnameID; - - @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id") - String actorID; - - @XACMLAction(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id") - String operationID; - - @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:target:target-id") - String targetID; - - @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:request:request-id") - String requestID; - - public String getActorID() { - return actorID; - } - - public void setActorID(String actorID) { - this.actorID = actorID; - } - - public String getOperationID() { - return operationID; - } - - public void setOperationID(String operationID) { - this.operationID = operationID; - } - - public String getTargetID() { - return targetID; - } - - public void setTargetID(String targetID) { - this.targetID = targetID; - } - - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - public String getClnameID() { - return clnameID; - } - - public void setClnameID(String clnameID) { - this.clnameID = clnameID; - } + /** + * Construct an instance. + * + * @param clnameID the control loop Id + * @param actorID the actor Id + * @param operationID the operation Id + * @param targetID the target Id + * @param requestID the request Id + */ + public PolicyGuardXacmlRequestAttributes(String clnameID, String actorID, String operationID, String targetID, + String requestID) { + super(); + this.clnameID = clnameID; + this.actorID = actorID; + this.operationID = operationID; + this.targetID = targetID; + this.requestID = requestID; + } + + @Override + public String toString() { + return "PolicyGuardXacmlRequestAttributes [actorID=" + actorID + ", operationID=" + operationID + ", targetID=" + + targetID + ", requestID=" + requestID + "]"; + } + + @XACMLSubject(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:clname:clname-id") + String clnameID; + + @XACMLSubject(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:actor:actor-id") + String actorID; + + @XACMLAction(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:operation:operation-id") + String operationID; + + @XACMLResource(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:target:target-id") + String targetID; + + @XACMLResource(includeInResults = true, attributeId = "urn:oasis:names:tc:xacml:1.0:request:request-id") + String requestID; + + public String getActorID() { + return actorID; + } + + public void setActorID(String actorID) { + this.actorID = actorID; + } + + public String getOperationID() { + return operationID; + } + + public void setOperationID(String operationID) { + this.operationID = operationID; + } + + public String getTargetID() { + return targetID; + } + + public void setTargetID(String targetID) { + this.targetID = targetID; + } + + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + public String getClnameID() { + return clnameID; + } + + public void setClnameID(String clnameID) { + this.clnameID = clnameID; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java index bb6ae49c8..b493fff38 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -35,174 +35,211 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PolicyGuardYamlToXacml { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); - - private PolicyGuardYamlToXacml() { - // Construction of this static class is not allowed - } - - public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { - ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); - logger.debug("clname: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); - logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); - logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - logger.debug("num: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); - logger.debug("duration: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); - logger.debug("time_in_range: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); - - Path xacmlTemplatePath = Paths.get(xacmlTemplate); - String xacmlTemplateContent; - - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - - String xacmlPolicyContent = generateXACMLGuard(xacmlTemplateContent, - yamlGuardObject.getGuards().getFirst().getMatch_parameters(), - yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() - ); - - Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); - - } catch (IOException e) { - logger.error("fromYamlToXacml threw: ", e); - } - } - - private static String generateXACMLGuard(String xacmlTemplateContent, MatchParameters matchParameters, Constraint constraint) { - Pattern p = Pattern.compile("\\$\\{clname\\}"); - Matcher m = p.matcher(xacmlTemplateContent); - if (isNullOrEmpty(matchParameters.getControlLoopName())) matchParameters.setControlLoopName(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getControlLoopName()); - - p = Pattern.compile("\\$\\{actor\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getActor())) matchParameters.setActor(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getActor()); - - p = Pattern.compile("\\$\\{recipe\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getRecipe())) matchParameters.setRecipe(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getRecipe()); - - p = Pattern.compile("\\$\\{targets\\}"); - m = p.matcher(xacmlTemplateContent); - String targetsRegex = ""; - if(isNullOrEmptyList(matchParameters.getTargets())) { - targetsRegex = ".*"; - } - else { - StringBuilder targetsRegexSB = new StringBuilder(); - boolean addBarChar = false; - for (String t : matchParameters.getTargets()){ - targetsRegexSB.append(t); - if (addBarChar) { - targetsRegexSB.append("|"); - } - else { - addBarChar = true; - } - } - targetsRegex = targetsRegexSB.toString(); - } - xacmlTemplateContent = m.replaceAll(targetsRegex); - - p = Pattern.compile("\\$\\{limit\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getFreq_limit_per_target().toString()); - - p = Pattern.compile("\\$\\{twValue\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getTime_window().get("value")); - - p = Pattern.compile("\\$\\{twUnits\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getTime_window().get("units")); - - - p = Pattern.compile("\\$\\{guardActiveStart\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("start")); - - p = Pattern.compile("\\$\\{guardActiveEnd\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("end")); - logger.debug(xacmlTemplateContent); - - return xacmlTemplateContent; - } - - public static boolean isNullOrEmpty(String s) { - return s == null || s.trim().isEmpty(); - } - - public static boolean isNullOrEmptyList(List list){ - return list == null || list.isEmpty(); - } - - public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ - ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); - logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); - logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - logger.debug("freq_limit_per_target: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); - logger.debug("time_window: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); - logger.debug("active_time_range: {}", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); - - Path xacmlTemplatePath = Paths.get(xacmlTemplate); - String xacmlTemplateContent; - - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, - yamlGuardObject.getGuards().getFirst().getMatch_parameters(), - yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst() - ); - - Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); - - } catch (IOException e) { - logger.error("fromYamlToXacmlBlacklist threw: ", e); - } - } - - private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, Constraint constraint) { - Pattern p = Pattern.compile("\\$\\{clname\\}"); - Matcher m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getControlLoopName())) matchParameters.setControlLoopName(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getControlLoopName()); - - p = Pattern.compile("\\$\\{actor\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getActor())) matchParameters.setActor(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getActor()); - - p = Pattern.compile("\\$\\{recipe\\}"); - m = p.matcher(xacmlTemplateContent); - if(isNullOrEmpty(matchParameters.getRecipe())) matchParameters.setRecipe(".*"); - xacmlTemplateContent = m.replaceAll(matchParameters.getRecipe()); - - p = Pattern.compile("\\$\\{guardActiveStart\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("start")); - - p = Pattern.compile("\\$\\{guardActiveEnd\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(constraint.getActive_time_range().get("end")); - logger.debug(xacmlTemplateContent); - - for(String target : constraint.getBlacklist()){ - p = Pattern.compile("\\$\\{blackListElement\\}"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll("" - + target - + "" - + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); - } - - p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); - m = p.matcher(xacmlTemplateContent); - xacmlTemplateContent = m.replaceAll(""); - - - return xacmlTemplateContent; - } + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); + + private PolicyGuardYamlToXacml() { + // Construction of this static class is not allowed + } + + /** + * Convert from Yaml to Xacml. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + logger.debug("clname: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); + logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); + logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); + logger.debug("num: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); + logger.debug("duration: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); + logger.debug("time_in_range: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent, + yamlGuardObject.getGuards().getFirst().getMatch_parameters(), + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()); + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + logger.error("fromYamlToXacml threw: ", e); + } + } + + /** + * Generate a Xacml guard. + * + * @param xacmlTemplateContent the Xacml template content + * @param matchParameters the paremeters to use + * @param constraint the constraint to use + * @return the guard + */ + private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + Pattern pattern = Pattern.compile("\\$\\{clname\\}"); + Matcher matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getControlLoopName())) { + matchParameters.setControlLoopName(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName()); + + pattern = Pattern.compile("\\$\\{actor\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getActor())) { + matchParameters.setActor(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor()); + + pattern = Pattern.compile("\\$\\{recipe\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getRecipe())) { + matchParameters.setRecipe(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe()); + + pattern = Pattern.compile("\\$\\{targets\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + String targetsRegex = ""; + if (isNullOrEmptyList(matchParameters.getTargets())) { + targetsRegex = ".*"; + } else { + StringBuilder targetsRegexSb = new StringBuilder(); + boolean addBarChar = false; + for (String t : matchParameters.getTargets()) { + targetsRegexSb.append(t); + if (addBarChar) { + targetsRegexSb.append("|"); + } else { + addBarChar = true; + } + } + targetsRegex = targetsRegexSb.toString(); + } + xacmlTemplateContent = matcher.replaceAll(targetsRegex); + + pattern = Pattern.compile("\\$\\{limit\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getFreq_limit_per_target().toString()); + + pattern = Pattern.compile("\\$\\{twValue\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("value")); + + pattern = Pattern.compile("\\$\\{twUnits\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getTime_window().get("units")); + + + pattern = Pattern.compile("\\$\\{guardActiveStart\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start")); + + pattern = Pattern.compile("\\$\\{guardActiveEnd\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end")); + logger.debug(xacmlTemplateContent); + + return xacmlTemplateContent; + } + + public static boolean isNullOrEmpty(String string) { + return string == null || string.trim().isEmpty(); + } + + public static boolean isNullOrEmptyList(List list) { + return list == null || list.isEmpty(); + } + + /** + * Convert from Yaml to Xacml blacklist. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + logger.debug("actor: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); + logger.debug("recipe: {}", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); + logger.debug("freq_limit_per_target: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()); + logger.debug("time_window: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()); + logger.debug("active_time_range: {}", + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range()); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, + yamlGuardObject.getGuards().getFirst().getMatch_parameters(), + yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()); + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + logger.error("fromYamlToXacmlBlacklist threw: ", e); + } + } + + private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + Pattern pattern = Pattern.compile("\\$\\{clname\\}"); + Matcher matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getControlLoopName())) { + matchParameters.setControlLoopName(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getControlLoopName()); + + pattern = Pattern.compile("\\$\\{actor\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getActor())) { + matchParameters.setActor(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getActor()); + + pattern = Pattern.compile("\\$\\{recipe\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + if (isNullOrEmpty(matchParameters.getRecipe())) { + matchParameters.setRecipe(".*"); + } + xacmlTemplateContent = matcher.replaceAll(matchParameters.getRecipe()); + + pattern = Pattern.compile("\\$\\{guardActiveStart\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("start")); + + pattern = Pattern.compile("\\$\\{guardActiveEnd\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(constraint.getActive_time_range().get("end")); + logger.debug(xacmlTemplateContent); + + for (String target : constraint.getBlacklist()) { + pattern = Pattern.compile("\\$\\{blackListElement\\}"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = + matcher.replaceAll("" + target + + "" + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + } + + pattern = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + matcher = pattern.matcher(xacmlTemplateContent); + xacmlTemplateContent = matcher.replaceAll(""); + + + return xacmlTemplateContent; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java index f2e4f0ae2..1e3064abd 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java @@ -25,13 +25,13 @@ import java.util.UUID; import org.onap.policy.controlloop.policy.TargetType; public interface TargetLock { - - public UUID getLockID(); - - public TargetType getTargetType(); - - public String getTargetInstance(); - - public UUID getRequestID(); + + public UUID getLockID(); + + public TargetType getTargetType(); + + public String getTargetInstance(); + + public UUID getRequestID(); } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java index 53e7a5e50..233fc0b49 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java @@ -36,110 +36,122 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public final class Util { - private Util() { - // This static class cannot be instantiated - } - - /* - * Keys for guard properties - */ - public static final String PROP_GUARD_URL = "guard.url"; - public static final String PROP_GUARD_USER = "pdpx.username"; - public static final String PROP_GUARD_PASS = "pdpx.password"; - public static final String PROP_GUARD_CLIENT_USER = "pdpx.client.username"; - public static final String PROP_GUARD_CLIENT_PASS = "pdpx.client.password"; - public static final String PROP_GUARD_ENV = "pdpx.environment"; - public static final String PROP_GUARD_DISABLED = "guard.disabled"; - - /* - * Keys for eclipse link and ONAP properties - */ - public static final String ECLIPSE_LINK_KEY_URL = "javax.persistence.jdbc.url"; - public static final String ECLIPSE_LINK_KEY_USER = "javax.persistence.jdbc.user"; - public static final String ECLIPSE_LINK_KEY_PASS = "javax.persistence.jdbc.password"; - - public static final String ONAP_KEY_URL = "guard.jdbc.url"; - public static final String ONAP_KEY_USER = "sql.db.username"; - public static final String ONAP_KEY_PASS = "sql.db.password"; - - /* - * Guard responses - */ - public static final String INDETERMINATE = "Indeterminate"; - public static final String PERMIT = "Permit"; - public static final String DENY = "Deny"; - - /* - * Junit props - */ - protected static final String PU_KEY = "OperationsHistoryPU"; - protected static final String JUNITPU = "TestOperationsHistoryPU"; - - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - public static Pair loadYaml(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(contents); - - logger.debug(contents); - - return new Pair<>((ControlLoopPolicy) obj, contents); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - public static ControlLoopGuard loadYamlGuard(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(contents); - return (ControlLoopGuard) obj; - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - /** - * Sets Guard Properties. - * - * @see /guard/src/test/java/org/onap/policy/guard/UtilTest.java - * for setting test properties - */ - public static void setGuardEnvProps(String url, String username, String password, String clientName, String clientPassword, String environment) { - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, clientName); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, clientPassword); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, environment); - } - - public static void setGuardEnvProp(String key, String value){ - PolicyEngine.manager.setEnvironmentProperty(key, value); - } - - public static String getGuardProp(String propName){ - return PolicyEngine.manager.getEnvironmentProperty(propName); - } + private Util() { + // This static class cannot be instantiated + } + + /* + * Keys for guard properties + */ + public static final String PROP_GUARD_URL = "guard.url"; + public static final String PROP_GUARD_USER = "pdpx.username"; + public static final String PROP_GUARD_PASS = "pdpx.password"; + public static final String PROP_GUARD_CLIENT_USER = "pdpx.client.username"; + public static final String PROP_GUARD_CLIENT_PASS = "pdpx.client.password"; + public static final String PROP_GUARD_ENV = "pdpx.environment"; + public static final String PROP_GUARD_DISABLED = "guard.disabled"; + + /* + * Keys for eclipse link and ONAP properties + */ + public static final String ECLIPSE_LINK_KEY_URL = "javax.persistence.jdbc.url"; + public static final String ECLIPSE_LINK_KEY_USER = "javax.persistence.jdbc.user"; + public static final String ECLIPSE_LINK_KEY_PASS = "javax.persistence.jdbc.password"; + + public static final String ONAP_KEY_URL = "guard.jdbc.url"; + public static final String ONAP_KEY_USER = "sql.db.username"; + public static final String ONAP_KEY_PASS = "sql.db.password"; + + /* + * Guard responses + */ + public static final String INDETERMINATE = "Indeterminate"; + public static final String PERMIT = "Permit"; + public static final String DENY = "Deny"; + + /* + * Junit props + */ + protected static final String PU_KEY = "OperationsHistoryPU"; + protected static final String JUNITPU = "TestOperationsHistoryPU"; + + private static final Logger logger = LoggerFactory.getLogger(Util.class); + + public static class Pair { + public final A parameterA; + public final B parameterB; + + public Pair(A parameterA, B parameterB) { + this.parameterA = parameterA; + this.parameterB = parameterB; + } + } + + /** + * Load a Yaml file. + * + * @param testFile the Yaml file + * @return the policies + */ + public static Pair loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + logger.debug(contents); + + return new Pair<>((ControlLoopPolicy) obj, contents); + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Load a Yaml guard. + * + * @param testFile the Yaml file + * @return the guard + */ + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Sets Guard Properties. + * + * @see /guard/src/test/java/org/onap/policy/guard/UtilTest.java for setting test properties + */ + public static void setGuardEnvProps(String url, String username, String password, String clientName, + String clientPassword, String environment) { + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, clientName); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, clientPassword); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, environment); + } + + public static void setGuardEnvProp(String key, String value) { + PolicyEngine.manager.setEnvironmentProperty(key, value); + } + + public static String getGuardProp(String propName) { + return PolicyEngine.manager.getEnvironmentProperty(propName); + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java index d9335ea3d..06bd9fb89 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,56 +29,61 @@ import org.onap.policy.guard.TargetLock; public class PNFTargetLock implements TargetLock, Serializable { - /** - * - */ - private static final long serialVersionUID = 2335897394577202732L; - - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - - public PNFTargetLock (TargetType type, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } - - @Override - public UUID getLockID() { - return this.lockID; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } - - public LockCallback getCallback() { - return this.callback; - } - - @Override - public String toString() { - return "PNFTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } - - + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; + + /** + * Construct an instance. + * + * @param type the target type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public PNFTargetLock(TargetType type, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockId; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "PNFTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } + + } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java index 0a7556bc9..dc81712cd 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,53 +28,58 @@ import org.onap.policy.guard.LockCallback; import org.onap.policy.guard.TargetLock; public class VMTargetLock implements TargetLock, Serializable { - - /** - * - */ - private static final long serialVersionUID = -8795145054334409724L; - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - public VMTargetLock(TargetType targetType, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = targetType; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } + private static final long serialVersionUID = -8795145054334409724L; + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; - @Override - public UUID getLockID() { - return this.lockID; - } - - @Override - public TargetType getTargetType() { - return targetType; - } + /** + * Create an instance. + * + * @param targetType the target type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public VMTargetLock(TargetType targetType, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = targetType; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } + @Override + public UUID getLockID() { + return this.lockId; + } - public LockCallback getCallback() { - return this.callback; - } + @Override + public TargetType getTargetType() { + return targetType; + } - @Override - public String toString() { - return "VMTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "VMTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java index b6e49b578..307c11acf 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VNFTargetLock.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,56 +29,61 @@ import org.onap.policy.guard.TargetLock; public class VNFTargetLock implements TargetLock, Serializable { - /** - * - */ - private static final long serialVersionUID = 2335897394577202732L; - - private final UUID lockID; - private final TargetType targetType; - private final String target; - private final UUID requestID; - private final transient LockCallback callback; - - public VNFTargetLock (TargetType type, String target, UUID requestID, LockCallback callback) { - this.lockID = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestID = requestID; - this.callback = callback; - } - - @Override - public UUID getLockID() { - return this.lockID; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestID() { - return this.requestID; - } - - public LockCallback getCallback() { - return this.callback; - } - - @Override - public String toString() { - return "VNFTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" - + requestID + "]"; - } - - + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; + + /** + * Create an instance. + * + * @param type the type + * @param target the target + * @param requestID the request Id + * @param callback the callback + */ + public VNFTargetLock(TargetType type, String target, UUID requestID, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestId = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockId; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "VNFTargetLock [lockID=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestId + "]"; + } + + } -- cgit 1.2.3-korg