aboutsummaryrefslogtreecommitdiffstats
path: root/controlloop/common/guard
diff options
context:
space:
mode:
authorGao, Chenfei (cg287m) <cgao@research.att.com>2017-06-22 14:48:41 -0400
committerPamela Dragosh <pdragosh@research.att.com>2017-06-29 12:50:23 -0400
commit68377161605e39c8c74ea77d0b504177480788f3 (patch)
treefb0fb8a27178da607866e1850f73ac056e046ee8 /controlloop/common/guard
parentf0c29b57e132e6335f0fa7bbad885d403e4c85df (diff)
[POLICY-22] Reorganizing drools-apps
Change-Id: I5f9bb3908f8d55c466dd847ae5e01a424e9ba364 Signed-off-by: Gao, Chenfei (cg287m) <chenfei.gao11@gmail.com> Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'controlloop/common/guard')
-rw-r--r--controlloop/common/guard/README.md2
-rw-r--r--controlloop/common/guard/pom.xml67
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java99
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java28
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java28
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java352
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java114
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java46
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java56
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java204
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java127
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java198
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java37
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java91
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java84
-rw-r--r--controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java80
-rw-r--r--controlloop/common/guard/src/main/resources/META-INF/persistence.xml22
-rw-r--r--controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java32
18 files changed, 1667 insertions, 0 deletions
diff --git a/controlloop/common/guard/README.md b/controlloop/common/guard/README.md
new file mode 100644
index 000000000..ba8593462
--- /dev/null
+++ b/controlloop/common/guard/README.md
@@ -0,0 +1,2 @@
+ECOMP Policy Guard Implementation
+
diff --git a/controlloop/common/guard/pom.xml b/controlloop/common/guard/pom.xml
new file mode 100644
index 000000000..388a233ea
--- /dev/null
+++ b/controlloop/common/guard/pom.xml
@@ -0,0 +1,67 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.onap.policy.drools-applications</groupId>
+ <artifactId>common</artifactId>
+ <version>1.1.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>guard</artifactId>
+ <dependencies>
+
+<!--
+ <dependency>
+ <groupId>org.onap.policy.drools-applications</groupId>
+ <artifactId>common</artifactId>
+ <version>1.1.0-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+-->
+
+ <dependency>
+ <groupId>org.onap.policy.drools-applications</groupId>
+ <artifactId>policy-yaml</artifactId>
+ <version>1.1.0-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.att.research.xacml</groupId>
+ <artifactId>xacml</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.att.research.xacml</groupId>
+ <artifactId>xacml-pdp</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ <version>4.5.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.drools</groupId>
+ <artifactId>drools-core</artifactId>
+ <version>6.3.0.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.persistence</groupId>
+ <artifactId>org.eclipse.persistence.jpa</artifactId>
+ <version>2.6.4</version>
+ </dependency>
+
+
+ </dependencies>
+</project>
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<BigInteger> attributeValue = null;
+ try {
+ attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value);
+ } catch (Exception ex) {
+ this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", 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<PIPRequest> attributesRequired() {
+ // TODO Auto-generated method stub
+ System.out.println("DADADADADADADADADADADADADA");
+ return null;
+ }
+
+ @Override
+ public Collection<PIPRequest> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
+ Set<String> setATTUIDs = new HashSet<String>();
+ for (Attribute attributeATTUID: listATTUIDs) {
+ Iterator<AttributeValue<String>> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
+ Set<String> setATTUIDs = new HashSet<String>();
+ for (Attribute attributeATTUID: listATTUIDs) {
+ Iterator<AttributeValue<String>> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
+ Set<String> setATTUIDs = new HashSet<String>();
+ for (Attribute attributeATTUID: listATTUIDs) {
+ Iterator<AttributeValue<String>> 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<String, TargetLock> activeLocks = new HashMap<String, TargetLock>();
+
+ public static class LockResult<A, B> {
+ private A a;
+ private B b;
+
+ public static <A, B> LockResult<A, B> createLockResult(A a, B b) {
+ return new LockResult<A, B>(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<GuardResult, TargetLock> 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<Result> it_res = xacmlResponse.getResults().iterator();
+
+ Result res = it_res.next();
+ String decision_from_xacml_response = res.getDecision().toString();
+ Iterator<AttributeCategory> it_attr_cat = res.getAttributes().iterator();
+ UUID req_id_from_xacml_response = null;
+ String operation_from_xacml_response = "";
+
+ while(it_attr_cat.hasNext()){
+ Iterator<Attribute> 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<AttributeValue<?>> 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<AttributeValue<?>> 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<String,String> 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<String> 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("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"
+ + target
+ + "</AttributeValue>"
+ + "\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<A, B> {
+ public final A a;
+ public final B b;
+
+ public Pair(A a, B b) {
+ this.a = a;
+ this.b = b;
+ }
+ }
+
+ public static Pair<ControlLoopPolicy, String> 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, String>((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 + "]";
+ }
+
+}
diff --git a/controlloop/common/guard/src/main/resources/META-INF/persistence.xml b/controlloop/common/guard/src/main/resources/META-INF/persistence.xml
new file mode 100644
index 000000000..babf94b01
--- /dev/null
+++ b/controlloop/common/guard/src/main/resources/META-INF/persistence.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<persistence xmlns="http://java.sun.com/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
+ http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
+
+ <persistence-unit name="OperationsHistoryPU11" transaction-type="RESOURCE_LOCAL">
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <!-- <jar-file>packedEntity.jar</jar-file>-->
+ <!-- <class>com.att.ecomp.policy.controlloop.eventmanager.OperationsHistoryDbEntry</class> -->
+ <properties>
+ <property name="eclipselink.ddl-generation" value="create-tables"/>
+ <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" />
+ <!-- <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:7779/policy"/>-->
+ <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://135.207.129.112:3306/policy"/>
+ <property name="javax.persistence.jdbc.user" value="root"/>
+ <property name="javax.persistence.jdbc.password" value="lmpg"/>
+ <property name="eclipselink.logging.level" value="INFO" />
+ </properties>
+ </persistence-unit>
+
+</persistence> \ No newline at end of file
diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java
new file mode 100644
index 000000000..7068fed3d
--- /dev/null
+++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java
@@ -0,0 +1,32 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * unit test
+ * ================================================================================
+ * 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 org.junit.Test;
+
+public class PolicyGuardTest {
+
+ @Test
+ public void test() {
+
+ }
+
+}