From 68377161605e39c8c74ea77d0b504177480788f3 Mon Sep 17 00:00:00 2001 From: "Gao, Chenfei (cg287m)" Date: Thu, 22 Jun 2017 14:48:41 -0400 Subject: [POLICY-22] Reorganizing drools-apps Change-Id: I5f9bb3908f8d55c466dd847ae5e01a424e9ba364 Signed-off-by: Gao, Chenfei (cg287m) Signed-off-by: Pamela Dragosh --- .../java/org/onap/policy/guard/CallGuardTask.java | 99 ++++++ .../java/org/onap/policy/guard/GuardResult.java | 28 ++ .../java/org/onap/policy/guard/LockCallback.java | 28 ++ .../org/onap/policy/guard/PIPEngineGetHistory.java | 352 +++++++++++++++++++++ .../java/org/onap/policy/guard/PolicyGuard.java | 114 +++++++ .../org/onap/policy/guard/PolicyGuardRequest.java | 46 +++ .../org/onap/policy/guard/PolicyGuardResponse.java | 56 ++++ .../onap/policy/guard/PolicyGuardXacmlHelper.java | 204 ++++++++++++ .../guard/PolicyGuardXacmlRequestAttributes.java | 127 ++++++++ .../onap/policy/guard/PolicyGuardYamlToXacml.java | 198 ++++++++++++ .../java/org/onap/policy/guard/TargetLock.java | 37 +++ .../src/main/java/org/onap/policy/guard/Util.java | 91 ++++++ .../org/onap/policy/guard/impl/PNFTargetLock.java | 84 +++++ .../org/onap/policy/guard/impl/VMTargetLock.java | 80 +++++ 14 files changed, 1544 insertions(+) create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java create mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java (limited to 'controlloop/common/guard/src/main/java/org/onap') 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 new file mode 100644 index 000000000..af81a3610 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.policy.guard; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.annotations.RequestParser; +import java.util.UUID; + +import org.drools.core.WorkingMemory; + + +public class CallGuardTask implements Runnable { + + WorkingMemory workingMemory; + PDPEngine embeddedPdpEngine; + String restfulPdpUrl; + String actor; + String recipe; + String target; + String requestId; + + public CallGuardTask(PDPEngine engine, String url, WorkingMemory wm, String act, String rec, String tar, String reqId) { + + embeddedPdpEngine = engine; + restfulPdpUrl = url; + workingMemory = wm; + actor = act; + recipe = rec; + requestId = reqId; + target = tar; + } + public void run() { + long startTime = System.nanoTime(); + com.att.research.xacml.api.Request request = null; + + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(actor, recipe, target, requestId); + + try { + request = RequestParser.parseRequest(xacmlReq); + } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /* + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + */ + + System.out.println("\n********** XACML REQUEST START ********"); + System.out.println(request); + System.out.println("********** XACML REQUEST END ********\n"); + + com.att.research.xacml.api.Response xacmlResponse = PolicyGuardXacmlHelper.callPDP(embeddedPdpEngine, "", request, false); + + System.out.println("\n********** XACML RESPONSE START ********"); + System.out.println(xacmlResponse); + System.out.println("********** XACML RESPONSE END ********\n"); + + PolicyGuardResponse guardResponse = PolicyGuardXacmlHelper.ParseXacmlPdpResponse(xacmlResponse); + + // + //Create an artificial Guard response in case we didn't get a clear Permit or Deny + // + if(guardResponse.result.equals("Indeterminate")){ + guardResponse.operation = recipe; + guardResponse.requestID = UUID.fromString(requestId); + } + + long estimatedTime = System.nanoTime() - startTime; + System.out.println("\n\n============ Guard inserted with decision "+ guardResponse.result + " !!! =========== time took: " +(double)estimatedTime/1000/1000 +" mili sec \n\n"); + 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 new file mode 100644 index 000000000..4afd16dab --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +public enum GuardResult { + 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 new file mode 100644 index 000000000..0a1255d33 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +public interface LockCallback { + + 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 new file mode 100644 index 000000000..99775dc3d --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -0,0 +1,352 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.math.BigInteger; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.persistence.Query; + +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.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 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.std.datatypes.DataTypes; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + + +public class PIPEngineGetHistory extends StdConfigurableEngine{ + + private Log logger = LogFactory.getLog(this.getClass()); + + //private static EntityManager em; + + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + + // + // 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"; + + + private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:actor:actor-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:action"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:operation:operation-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:target:target-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + + 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) { + this.logger.error("Failed to convert " + value + " to an AttributeValue", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); + } + } + + + + public PIPEngineGetHistory() { + super(); + + System.out.println("HAHAHAHAHAHAHAHAHAHAHAHAHAHAHA"); + + // TODO Auto-generated constructor stub + } + + + + @Override + public Collection attributesRequired() { + // TODO Auto-generated method stub + System.out.println("DADADADADADADADADADADADADA"); + return null; + } + + @Override + public Collection attributesProvided() { + // TODO Auto-generated method stub + System.out.println("GAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAG"); + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + // TODO Auto-generated method stub + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Entering FeqLimiter PIP!!!"); + + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + this.logger.debug("No issuer in the request..."); + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - 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())) { + this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer "+ string +" does not match with: "+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 + + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer " + string + " is OK - proceeding with the request!!!"); + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - TimeWindow: " + timeWindowVal + " " + timeWindowScale); + + String actor = getActor(pipFinder).iterator().next(); + String operation = getRecipe(pipFinder).iterator().next(); + String target = getTarget(pipFinder).iterator().next(); + + String timeWindow = timeWindowVal + " " + timeWindowScale; + + System.out.println("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("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), + new IdentifierImpl("com:att:research: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); + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Configuring FeqLimiter PIP!!!"); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + /* + try{ + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + }catch(Exception e){ + System.err.println("Freq limiter PIP got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB."); + return; + } + */ + + } + + + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + System.out.println("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse.getAttributes().size() == 0) { + System.out.println("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + System.out.println("PIPException getting subject-id attribute: " + ex.getMessage()); + } + 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 null; + } + + /* + * 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 null; + } + + /* + * 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 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 null; + } + + /* + * 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){ + + long startTime = System.nanoTime(); + + + + EntityManager em; + try{ + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + }catch(Exception e){ + System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB."); + return -1; + } + + + //em.getTransaction().begin(); + String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor='" + + actor + + "' and operation='" + + operation + + "' and target='" + + target + + "' " + + "and endtime between date_sub(now(),interval " + + timeWindow + + ") and now()"; + + Query nq = em.createNativeQuery(sql); + + int ret = ((Number)nq.getSingleResult()).intValue(); + + System.out.println("###########************** History count: " + ret); + + //em.getTransaction().commit(); + long estimatedTime = System.nanoTime() - startTime; + System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec."); + + em.close(); + + return ret; + + + + } + + +} 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 new file mode 100644 index 000000000..b4aee2fda --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.impl.PNFTargetLock; +import org.onap.policy.guard.impl.VMTargetLock; + +public class PolicyGuard { + + private static Map activeLocks = new HashMap(); + + 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; + default: + return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); + } + // + // Keep track of it + // + activeLocks.put(targetInstance, lock); + // + // Return result + // + System.out.println("Locking " + lock); + return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); + } + } + + public static boolean unlockTarget(TargetLock lock) { + synchronized(activeLocks) { + if (activeLocks.containsKey(lock.getTargetInstance())) { + System.out.println("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; + } + } + +} 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 new file mode 100644 index 000000000..04732dc36 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardRequest{ + + public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { + super(); + this.actor = actor; + this.target = target; + this.requestID = requestID; + this.operation = operation; + } + public String actor; + public String target; + public UUID requestID; + public String operation; + + + @Override + public String toString() { + return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestID + ", operation=" + + operation + "]"; + } + +} \ No newline at end of file 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 new file mode 100644 index 000000000..20bbc2eb6 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardResponse{ + public PolicyGuardResponse(String string, UUID req, String op) { + this.result = string; + this.requestID = req; + this.operation = op; + } + public UUID requestID; + public String operation; + public String result; + + + + + + @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; + } + +} \ No newline at end of file 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 new file mode 100644 index 000000000..66d2f288e --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Iterator; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +//import org.openecomp.policy.appc.Response; + +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 com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; + + +public class PolicyGuardXacmlHelper { + + + + public static com.att.research.xacml.api.Response callPDP(PDPEngine xacmlEmbeddedPdpEngine, String restfulPdpUrl, com.att.research.xacml.api.Request request, boolean isREST) { + // + // Send it to the PDP + // + com.att.research.xacml.api.Response response = null; + if (isREST) { + try { + String jsonString = JSONRequest.toString((com.att.research.xacml.api.Request) request, false); + // + // Call RESTful PDP + // + response = (com.att.research.xacml.api.Response) callRESTfulPDP(new ByteArrayInputStream(jsonString.getBytes()), new URL(restfulPdpUrl/*"https://localhost:8443/pdp/"*/)); + } catch (Exception e) { + System.err.println("Error in sending RESTful request: " + e); + } + } else if(xacmlEmbeddedPdpEngine != null){ + // + // Embedded call to PDP + // + long lTimeStart = System.currentTimeMillis(); + try { + response = (com.att.research.xacml.api.Response) xacmlEmbeddedPdpEngine.decide((com.att.research.xacml.api.Request) request); + } catch (PDPException e) { + System.err.println(e); + } + long lTimeEnd = System.currentTimeMillis(); + System.out.println("Elapsed Time: " + (lTimeEnd - lTimeStart) + "ms"); + } + return response; + } + + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param file + * @return + */ + private static com.att.research.xacml.api.Response callRESTfulPDP(InputStream is, URL restURL) { + com.att.research.xacml.api.Response response = null; + HttpURLConnection connection = null; + try { + + // + // Open up the connection + // + connection = (HttpURLConnection) restURL.openConnection(); + connection.setRequestProperty("Content-Type", "application/json"); + // + // Setup our method and headers + // + 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) { + // + // Read the response + // + ContentType contentType = null; + try { + contentType = ContentType.parse(connection.getContentType()); + + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + response = (com.att.research.xacml.api.Response) JSONResponse.load(connection.getInputStream()); + } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { + response = (com.att.research.xacml.api.Response) DOMResponse.load(connection.getInputStream()); + } else { + System.err.println("unknown content-type: " + contentType); + } + + } catch (Exception e) { + String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); + System.err.println(message); + } + + } else { + System.err.println(connection.getResponseCode() + " " + connection.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e); + } + + return response; + } + + + 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 it_res = xacmlResponse.getResults().iterator(); + + Result res = it_res.next(); + String decision_from_xacml_response = res.getDecision().toString(); + Iterator it_attr_cat = res.getAttributes().iterator(); + UUID req_id_from_xacml_response = null; + String operation_from_xacml_response = ""; + + while(it_attr_cat.hasNext()){ + Iterator it_attr = it_attr_cat.next().getAttributes().iterator(); + while(it_attr.hasNext()){ + Attribute current_attr = it_attr.next(); + String s = current_attr.getAttributeId().stringValue(); + //System.out.println("ATTR ID = " + s); + if(s.equals("urn:oasis:names:tc:xacml:1.0:request:request-id")){ + Iterator> it_values = current_attr.getValues().iterator(); + req_id_from_xacml_response = UUID.fromString(it_values.next().getValue().toString()); + //System.out.println("UUID = " + req_id_from_xacml_response); + } + if(s.equals("urn:oasis:names:tc:xacml:1.0:operation:operation-id")){ + Iterator> it_values = current_attr.getValues().iterator(); + operation_from_xacml_response = it_values.next().getValue().toString(); + //System.out.println("OPERATION = " + operation_from_xacml_response); + } + + } + } + + + + + + return new PolicyGuardResponse(decision_from_xacml_response, req_id_from_xacml_response, operation_from_xacml_response); + + } + + + +} 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 new file mode 100644 index 000000000..4abb70f84 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +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) +public class PolicyGuardXacmlRequestAttributes { + + + + + public PolicyGuardXacmlRequestAttributes(String actor_id, String operation_id, String target_id, + String request_id) { + super(); + this.actor_id = actor_id; + this.operation_id = operation_id; + this.target_id = target_id; + this.request_id = request_id; + } + + + + @Override + public String toString() { + return "PolicyGuardXacmlRequestAttributes [actor_id=" + actor_id + ", operation_id=" + operation_id + + ", target_id=" + target_id + ", request_id=" + request_id + "]"; + } + + + + //@XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id") + //String userID; + + //@XACMLAction() + //String action; + + @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id") + String actor_id; + + @XACMLAction(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id") + String operation_id; + + //@XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id123") + //String resource; + + @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:target:target-id") + String target_id; + + @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:request:request-id") + String request_id; + + public String getActor_id() { + return actor_id; + } + + + + public void setActor_id(String actor_id) { + this.actor_id = actor_id; + } + + + + public String getOperation_id() { + return operation_id; + } + + + + public void setOperation_id(String operation_id) { + this.operation_id = operation_id; + } + + + + public String getTarget_id() { + return target_id; + } + + + + public void setTarget_id(String target_id) { + this.target_id = target_id; + } + + + + public String getRequest_id() { + return request_id; + } + + + + public void setRequest_id(String request_id) { + this.request_id = request_id; + } + + + + + }; + 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 new file mode 100644 index 000000000..b9a7881b6 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; + + +public class PolicyGuardYamlToXacml { + + + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ + + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().recipe); + System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num); + System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration); + System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent, + yamlGuardObject.guards.getFirst().actor, + yamlGuardObject.guards.getFirst().recipe, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg2"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg3") + ); + + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + + + public static String generateXacmlGuard(String xacmlFileContent, + String actor, + String recipe, + Integer limit, + Map timeWindow, + String guardActiveStart, + String guardActiveEnd) { + + Pattern p = Pattern.compile("\\$\\{actor\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(actor); + + p = Pattern.compile("\\$\\{recipe\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(recipe); + + p = Pattern.compile("\\$\\{limit\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(limit.toString()); + + + //p = Pattern.compile("\\$\\{timeWindow\\}"); + //m = p.matcher(xacmlFileContent); + //xacmlFileContent = m.replaceAll("tw"+timeWindow); + + p = Pattern.compile("\\$\\{twValue\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(timeWindow.get("value")); + + p = Pattern.compile("\\$\\{twUnits\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(timeWindow.get("units")); + + + p = Pattern.compile("\\$\\{guardActiveStart\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveStart); + + p = Pattern.compile("\\$\\{guardActiveEnd\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveEnd); + System.out.println(xacmlFileContent); + + return xacmlFileContent; + } + + + + public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ + + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().recipe); + System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num); + System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration); + System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, + yamlGuardObject.guards.getFirst().actor, + yamlGuardObject.guards.getFirst().recipe, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().blacklist, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg2"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg3") + ); + + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + public static String generateXacmlGuardBlacklist(String xacmlFileContent, + String actor, + String recipe, + List blacklist, + String guardActiveStart, + String guardActiveEnd) { + + Pattern p = Pattern.compile("\\$\\{actor\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(actor); + + p = Pattern.compile("\\$\\{recipe\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(recipe); + + p = Pattern.compile("\\$\\{guardActiveStart\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveStart); + + p = Pattern.compile("\\$\\{guardActiveEnd\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveEnd); + System.out.println(xacmlFileContent); + + for(String target : blacklist){ + p = Pattern.compile("\\$\\{blackListElement\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll("" + + target + + "" + + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}"); + } + + p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(""); + + + return xacmlFileContent; + } + + +} 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 new file mode 100644 index 000000000..f2e4f0ae2 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +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(); + +} 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 new file mode 100644 index 000000000..702f27ccb --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; + + +public final class Util { + + 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); + + //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas"); + System.out.println(contents); + //for(Policy policy : ((ControlLoopPolicy)obj).policies){ + + return new Pair((ControlLoopPolicy) obj, contents); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + 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 (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + +} 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 new file mode 100644 index 000000000..ea966ea55 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard.impl; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.LockCallback; +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 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 + "]"; + } + + + +} 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 new file mode 100644 index 000000000..1de105ce4 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard.impl; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +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 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; + } + + @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 "VMTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestID + "]"; + } + +} -- cgit 1.2.3-korg