From fa09813ca39cbdb7a0ac6a38507d4ea96e28879f Mon Sep 17 00:00:00 2001 From: Michael Borokhovich Date: Thu, 20 Jul 2017 09:53:57 -0400 Subject: [POLICY-80] Adding the Policy Guard features Two Policy Guard features added: Frequency-limiter and Blacklist. Change-Id: I48184ab0ae9760c9ea7594cd7346b456aa964d48 Signed-off-by: Michael Borokhovich --- .../java/org/onap/policy/guard/CallGuardTask.java | 16 +- .../org/onap/policy/guard/PIPEngineGetHistory.java | 75 ++- .../guard/PolicyGuardXacmlRequestAttributes.java | 18 +- .../onap/policy/guard/PolicyGuardYamlToXacml.java | 110 +++- .../controlloop/policy/guard/Constraint.java | 78 +-- .../controlloop/policy/guard/GuardPolicy.java | 73 +-- .../controlloop/policy/guard/MatchParameters.java | 138 +++++ .../compiler/ControlLoopGuardCompilerTest.java | 13 +- .../policy/guard/ControlLoopGuardBuilderTest.java | 31 +- .../policy/guard/ControlLoopGuardTest.java | 4 +- .../v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml | 19 + .../policy_guard_OpenECOMP_demo_vDNS.yaml | 14 - .../policy_guard_OpenECOMP_demo_vDNS.yaml~ | 12 - .../v2.0.0-guard/policy_guard_appc_restart.yaml | 24 + .../v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml | 26 - .../resources/ControlLoop_Template_xacml_guard.drl | 9 +- .../src/main/resources/blacklist_template.xml | 11 +- .../main/resources/frequency_limiter_template.xml | 18 +- .../processor/ControlLoopXacmlGuardTest.java | 674 --------------------- .../onap/policy/controlloop/processor/Util.java | 90 --- .../template/demo/ControlLoopXacmlGuardTest.java | 623 +++++++++++++++++++ .../java/org/onap/policy/template/demo/Util.java | 90 +++ .../resources/xacml/xacml_guard_old.properties | 277 --------- .../yaml/policy_ControlLoop_Service123.yaml | 62 ++ .../yaml/policy_ControlLoop_vUSP_1707.yaml | 68 --- .../resources/yaml/policy_guard_appc_migrate.yaml | 26 + .../resources/yaml/policy_guard_appc_rebuild.yaml | 26 + .../yaml/policy_guard_appc_rebuild_1.yaml | 26 + .../resources/yaml/policy_guard_appc_restart.yaml | 27 + .../yaml/policy_guard_appc_restart_blacklist.yaml | 27 + .../yaml/policy_guard_vUSP_1707_appc_migrate.yaml | 24 - .../yaml/policy_guard_vUSP_1707_appc_rebuild.yaml | 24 - .../policy_guard_vUSP_1707_appc_rebuild_1.yaml | 24 - .../yaml/policy_guard_vUSP_1707_appc_restart.yaml | 24 - ...icy_guard_vUSP_1707_appc_restart_blacklist.yaml | 26 - 35 files changed, 1370 insertions(+), 1457 deletions(-) create mode 100644 controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java create mode 100644 controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml delete mode 100644 controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml delete mode 100644 controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml~ create mode 100644 controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml delete mode 100644 controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/ControlLoopXacmlGuardTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/Util.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopXacmlGuardTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java delete mode 100644 controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard_old.properties create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_Service123.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_migrate.yaml create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild.yaml create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart.yaml create mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml delete mode 100644 controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java index af81a3610..dbef0c433 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -18,7 +18,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.guard; import com.att.research.xacml.api.DataTypeException; @@ -34,16 +33,18 @@ public class CallGuardTask implements Runnable { WorkingMemory workingMemory; PDPEngine embeddedPdpEngine; String restfulPdpUrl; + String clname; String actor; String recipe; String target; String requestId; - public CallGuardTask(PDPEngine engine, String url, WorkingMemory wm, String act, String rec, String tar, String reqId) { + public CallGuardTask(PDPEngine engine, String url, WorkingMemory wm, String cl, String act, String rec, String tar, String reqId) { embeddedPdpEngine = engine; restfulPdpUrl = url; workingMemory = wm; + clname = cl; actor = act; recipe = rec; requestId = reqId; @@ -53,7 +54,7 @@ public class CallGuardTask implements Runnable { long startTime = System.nanoTime(); com.att.research.xacml.api.Request request = null; - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(actor, recipe, target, requestId); + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId); try { request = RequestParser.parseRequest(xacmlReq); @@ -61,14 +62,7 @@ public class CallGuardTask implements Runnable { // 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); diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java index 99775dc3d..87eb5170f 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -28,6 +28,8 @@ import java.util.Properties; import java.util.Set; import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import javax.persistence.Query; @@ -97,9 +99,6 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ public PIPEngineGetHistory() { super(); - - System.out.println("HAHAHAHAHAHAHAHAHAHAHAHAHAHAHA"); - // TODO Auto-generated constructor stub } @@ -108,21 +107,19 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ @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!!!"); + System.out.println("Entering FeqLimiter PIP"); /* * First check to see if the issuer is set and then match it @@ -130,14 +127,14 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ 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!!!"); + System.out.println("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()); + System.out.println("FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer()); return StdPIPResponse.PIP_RESPONSE_EMPTY; } } @@ -146,9 +143,6 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ 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(); @@ -159,7 +153,6 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ 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, @@ -175,26 +168,32 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ @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 void addStringAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, String value) { + if (value != null) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_STRING.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, this.getIssuer(), false)); + } + } + } + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { PIPResponse pipResponse = null; @@ -305,20 +304,16 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ private static int getCountFromDB(String actor, String operation, String target, String timeWindow){ - long startTime = System.nanoTime(); + //long startTime = System.nanoTime(); - - EntityManager em; try{ - em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager(); }catch(Exception e){ - System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB."); + System.err.println("PIP thread got Exception " + e.getLocalizedMessage() + " Can't connect 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='" @@ -332,19 +327,23 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{ Query nq = em.createNativeQuery(sql); - int ret = ((Number)nq.getSingleResult()).intValue(); - - System.out.println("###########************** History count: " + ret); + int ret = -1; + try{ + ret = ((Number)nq.getSingleResult()).intValue(); + } + catch(NoResultException | NonUniqueResultException ex){ + System.err.println("PIP thread got Exception " + ex.getLocalizedMessage()); + return -1; + } - //em.getTransaction().commit(); - long estimatedTime = System.nanoTime() - startTime; - System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec."); + //System.out.println("###########************** History count: " + ret); + + //long estimatedTime = System.nanoTime() - startTime; + //System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec."); em.close(); - return ret; - - + return ret; } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java index 4abb70f84..115108219 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -34,9 +34,10 @@ public class PolicyGuardXacmlRequestAttributes { - public PolicyGuardXacmlRequestAttributes(String actor_id, String operation_id, String target_id, + public PolicyGuardXacmlRequestAttributes(String clname_id, String actor_id, String operation_id, String target_id, String request_id) { super(); + this.clname_id = clname_id; this.actor_id = actor_id; this.operation_id = operation_id; this.target_id = target_id; @@ -59,6 +60,9 @@ public class PolicyGuardXacmlRequestAttributes { //@XACMLAction() //String action; + @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:clname:clname-id") + String clname_id; + @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id") String actor_id; @@ -119,6 +123,18 @@ public class PolicyGuardXacmlRequestAttributes { public void setRequest_id(String request_id) { this.request_id = request_id; } + + + + public String getClname_id() { + return clname_id; + } + + + + public void setClname_id(String clname_id) { + this.clname_id = clname_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 index b9a7881b6..baf43b3b0 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -20,30 +20,33 @@ 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.LinkedList; 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); + System.out.println("clname: " + yamlGuardObject.guards.getFirst().match_parameters.controlLoopName); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().match_parameters.actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().match_parameters.recipe); + System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target); + System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window); + System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range); Path xacmlTemplatePath = Paths.get(xacmlTemplate); String xacmlTemplateContent; @@ -52,12 +55,14 @@ public class PolicyGuardYamlToXacml { 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") + yamlGuardObject.guards.getFirst().match_parameters.controlLoopName, + yamlGuardObject.guards.getFirst().match_parameters.actor, + yamlGuardObject.guards.getFirst().match_parameters.recipe, + yamlGuardObject.guards.getFirst().match_parameters.targets, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("start"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("end") ); @@ -73,20 +78,44 @@ public class PolicyGuardYamlToXacml { public static String generateXacmlGuard(String xacmlFileContent, + String clname, String actor, - String recipe, + String recipe, + LinkedList targets, Integer limit, Map timeWindow, String guardActiveStart, String guardActiveEnd) { - Pattern p = Pattern.compile("\\$\\{actor\\}"); + Pattern p = Pattern.compile("\\$\\{clname\\}"); Matcher m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(clname)) clname = ".*"; + xacmlFileContent = m.replaceAll(clname); + + p = Pattern.compile("\\$\\{actor\\}"); + m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(actor)) actor = ".*"; xacmlFileContent = m.replaceAll(actor); p = Pattern.compile("\\$\\{recipe\\}"); m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(recipe)) recipe = ".*"; xacmlFileContent = m.replaceAll(recipe); + + p = Pattern.compile("\\$\\{targets\\}"); + m = p.matcher(xacmlFileContent); + String targetsRegex = ""; + if(isNullOrEmptyList(targets)){ + targetsRegex = ".*"; + } + else{ + for(String t : targets){ + targetsRegex += (t + "|"); + + } + targetsRegex = targetsRegex.substring(0, targetsRegex.length()-1); + } + xacmlFileContent = m.replaceAll(targetsRegex); p = Pattern.compile("\\$\\{limit\\}"); m = p.matcher(xacmlFileContent); @@ -118,16 +147,39 @@ public class PolicyGuardYamlToXacml { return xacmlFileContent; } + public static boolean isNullOrEmpty(String s){ + + if(s == null){ + return true; + } + else if(s.equals("")){ + return true; + } + return false; + + } + + public static boolean isNullOrEmptyList(LinkedList list){ + + if(list == null){ + return true; + } + else if(list.isEmpty()){ + return true; + } + return false; + + } 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); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().match_parameters.actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().match_parameters.recipe); + System.out.println("freq_limit_per_target: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().freq_limit_per_target); + System.out.println("time_window: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_window); + System.out.println("active_time_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range); Path xacmlTemplatePath = Paths.get(xacmlTemplate); String xacmlTemplateContent; @@ -136,11 +188,12 @@ public class PolicyGuardYamlToXacml { xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, - yamlGuardObject.guards.getFirst().actor, - yamlGuardObject.guards.getFirst().recipe, + yamlGuardObject.guards.getFirst().match_parameters.controlLoopName, + yamlGuardObject.guards.getFirst().match_parameters.actor, + yamlGuardObject.guards.getFirst().match_parameters.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") + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("start"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().active_time_range.get("end") ); @@ -154,18 +207,27 @@ public class PolicyGuardYamlToXacml { } public static String generateXacmlGuardBlacklist(String xacmlFileContent, + String clname, String actor, String recipe, List blacklist, String guardActiveStart, String guardActiveEnd) { - Pattern p = Pattern.compile("\\$\\{actor\\}"); + + Pattern p = Pattern.compile("\\$\\{clname\\}"); Matcher m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(clname)) clname = ".*"; + xacmlFileContent = m.replaceAll(clname); + + p = Pattern.compile("\\$\\{actor\\}"); + m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(actor)) actor = ".*"; xacmlFileContent = m.replaceAll(actor); p = Pattern.compile("\\$\\{recipe\\}"); m = p.matcher(xacmlFileContent); + if(isNullOrEmpty(recipe)) recipe = ".*"; xacmlFileContent = m.replaceAll(recipe); p = Pattern.compile("\\$\\{guardActiveStart\\}"); diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java index 54f230876..e13318089 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java @@ -27,10 +27,9 @@ import java.util.Map; public class Constraint { - public Integer num; - //public String duration; - public Map duration; - public Map time_in_range; + public Integer freq_limit_per_target; + public Map time_window; + public Map active_time_range; public LinkedList blacklist; @@ -38,9 +37,11 @@ public class Constraint { } - public Constraint(Integer num, Map duration) { - this.num = num; - this.duration = duration; + public Constraint(Integer freq_limit_per_target, Map time_window) { + this.freq_limit_per_target = freq_limit_per_target; + if (time_window != null) { + this.time_window = Collections.unmodifiableMap(time_window); + } } public Constraint(List blacklist) { @@ -48,38 +49,43 @@ public class Constraint { } - public Constraint(Integer num, Map duration, List blacklist) { - this.num = num; - this.duration = Collections.unmodifiableMap(duration); + public Constraint(Integer freq_limit_per_target, Map time_window, List blacklist) { + this.freq_limit_per_target = freq_limit_per_target; + this.time_window = Collections.unmodifiableMap(time_window); this.blacklist = new LinkedList(blacklist); } - public Constraint(Integer num, Map duration, Map time_in_range, List blacklist) { - //this(num, duration); - if (duration != null) { - this.duration = Collections.unmodifiableMap(duration); - } - if (time_in_range != null) { - this.time_in_range = Collections.unmodifiableMap(time_in_range); + public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range, List blacklist) { + this(freq_limit_per_target, time_window); + if (active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(active_time_range); } this.blacklist = new LinkedList(blacklist); } + public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range) { + this(freq_limit_per_target, time_window); + if (active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(active_time_range); + } + } + public Constraint(Constraint constraint) { - this.num = constraint.num; - this.duration = constraint.duration; - if (constraint.time_in_range != null) { - this.time_in_range = Collections.unmodifiableMap(constraint.time_in_range); + this.freq_limit_per_target = constraint.freq_limit_per_target; + this.time_window = constraint.time_window; + if (constraint.active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range); } this.blacklist = new LinkedList(constraint.blacklist); } public boolean isValid() { + //System.out.println("freq_limit_per_target: " + freq_limit_per_target + " time_window" + time_window ); try { - if (num == null && duration != null) { + if (freq_limit_per_target == null && time_window != null) { throw new NullPointerException(); } - if (duration == null && num != null) { + if (time_window == null && freq_limit_per_target != null) { throw new NullPointerException(); } } catch (Exception e) { @@ -90,16 +96,16 @@ public class Constraint { @Override public String toString() { - return "Constraint [num=" + num + ", duration=" + duration + ", time_in_range=" + time_in_range + ", blacklist=" + blacklist + "]"; + return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((num == null) ? 0 : num.hashCode()); - result = prime * result + ((duration == null) ? 0 : duration.hashCode()); - result = prime * result + ((time_in_range == null) ? 0 : time_in_range.hashCode()); + result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode()); + result = prime * result + ((time_window == null) ? 0 : time_window.hashCode()); + result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode()); result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); return result; } @@ -113,20 +119,20 @@ public class Constraint { if (getClass() != obj.getClass()) return false; Constraint other = (Constraint) obj; - if (num == null) { - if (other.num != null) + if (freq_limit_per_target == null) { + if (other.freq_limit_per_target != null) return false; - } else if (!num.equals(other.num)) + } else if (!freq_limit_per_target.equals(other.freq_limit_per_target)) return false; - if (duration == null) { - if (other.duration != null) + if (time_window == null) { + if (other.time_window != null) return false; - } else if (!duration.equals(other.duration)) + } else if (!time_window.equals(other.time_window)) return false; - if (time_in_range == null) { - if (other.time_in_range != null) + if (active_time_range == null) { + if (other.active_time_range != null) return false; - } else if (!time_in_range.equals(other.time_in_range)) + } else if (!active_time_range.equals(other.active_time_range)) return false; if (blacklist == null) { if (other.blacklist != null) diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java index a850b36ed..f0267b3ad 100644 --- a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java @@ -30,11 +30,11 @@ public class GuardPolicy { public String id = UUID.randomUUID().toString(); public String name; public String description; - public String actor; - public String recipe; + public MatchParameters match_parameters; public LinkedList limit_constraints; - public GuardPolicy() { + +public GuardPolicy() { } @@ -42,41 +42,45 @@ public class GuardPolicy { this.id = id; } - public GuardPolicy(String name, String actor, String recipe) { + public GuardPolicy(String name, MatchParameters match_parameters) { this.name = name; - this.actor = actor; - this.recipe = recipe; + System.out.println("match_parameters: " + match_parameters); + this.match_parameters = new MatchParameters(match_parameters); } - public GuardPolicy(String id, String name, String description, String actor, String recipe) { - this(name, actor, recipe); + public GuardPolicy(String id, String name, String description, MatchParameters match_parameters) { + this(name, match_parameters); this.id = id; this.description = description; } - public GuardPolicy(String name, String actor, String recipe, List limit_constraints) { - this(name, actor, recipe); + public GuardPolicy(String name, MatchParameters match_parameters, List limit_constraints) { + this(name, match_parameters); if (limit_constraints != null) { this.limit_constraints = (LinkedList) Collections.unmodifiableList(limit_constraints); } } - public GuardPolicy(String name, String description, String actor, String recipe, List limit_constraints) { - this(name, actor, recipe, limit_constraints); + public GuardPolicy(String name, String description, MatchParameters match_parameters, List limit_constraints) { + this(name, match_parameters, limit_constraints); this.description = description; } - public GuardPolicy(String id, String name, String description, String actor, String recipe, List limit_constraints) { - this(name, description, actor, recipe, limit_constraints); + public GuardPolicy(String id, String name, String description, MatchParameters match_parameters, List limit_constraints) { + this(name, description, match_parameters, limit_constraints); this.id = id; } + + + + + public GuardPolicy(GuardPolicy policy) { this.id = policy.id; this.name = policy.name; this.description = policy.description; - this.actor = policy.actor; - this.recipe = policy.recipe; + this.match_parameters = new MatchParameters(policy.match_parameters); if (policy.limit_constraints != null) { this.limit_constraints = (LinkedList) Collections.unmodifiableList(policy.limit_constraints); } @@ -90,12 +94,7 @@ public class GuardPolicy { if (name == null) { throw new NullPointerException(); } - if (actor == null) { - throw new NullPointerException(); - } - if (recipe == null) { - throw new NullPointerException(); - } + } catch (Exception e) { return false; } @@ -104,20 +103,19 @@ public class GuardPolicy { @Override public String toString() { - return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" - + recipe + ", limit_constraints=" + limit_constraints + "]"; + return "GuardPolicy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" + + match_parameters + ", limit_constraints=" + limit_constraints + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @@ -130,11 +128,6 @@ public class GuardPolicy { if (getClass() != obj.getClass()) return false; GuardPolicy other = (GuardPolicy) obj; - if (actor == null) { - if (other.actor != null) - return false; - } else if (!actor.equals(other.actor)) - return false; if (description == null) { if (other.description != null) return false; @@ -145,20 +138,20 @@ public class GuardPolicy { return false; } else if (!id.equals(other.id)) return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; if (limit_constraints == null) { if (other.limit_constraints != null) return false; } else if (!limit_constraints.equals(other.limit_constraints)) return false; - if (recipe == null) { - if (other.recipe != null) + if (match_parameters == null) { + if (other.match_parameters != null) + return false; + } else if (!match_parameters.equals(other.match_parameters)) + return false; + if (name == null) { + if (other.name != null) return false; - } else if (!recipe.equals(other.recipe)) + } else if (!name.equals(other.name)) return false; return true; } diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java new file mode 100644 index 000000000..c96ecf710 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml + * ================================================================================ + * 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.controlloop.policy.guard; + +import java.util.LinkedList; + + +public class MatchParameters { + + //public ControlLoopParameter controlLoop; + public String controlLoopName; + public String actor; + public String recipe; + public LinkedList targets; + + + public MatchParameters() { + + } + + public MatchParameters(String actor, String recipe) { + this.actor = actor; + this.recipe = recipe; + } + + public MatchParameters(String actor, String recipe, LinkedList targets) { + this(actor, recipe); + if (targets != null) { + this.targets = new LinkedList(targets); + } + } + + + public MatchParameters(String controlLoopName, String actor, String recipe, LinkedList targets) { + this(actor, recipe, targets); + this.controlLoopName = controlLoopName; + } + + + + + + public MatchParameters(MatchParameters matchParameters) { + + this.controlLoopName = matchParameters.controlLoopName; + this.actor = matchParameters.actor; + this.recipe = matchParameters.recipe; + if (matchParameters.targets != null) { + //this.targets = (LinkedList) Collections.unmodifiableList(matchParameters.targets); + this.targets = new LinkedList(matchParameters.targets); + } + } + + /* + public boolean isValid() { + try { + if (actor == null) { + throw new NullPointerException(); + } + if (recipe == null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + return true; + } + */ + + @Override + public String toString() { + return "MatchParameters [controlLoopName=" + controlLoopName + ", actor=" + actor + ", recipe=" + recipe + + ", targets=" + targets + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((targets == null) ? 0 : targets.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MatchParameters other = (MatchParameters) obj; + if (actor == null) { + if (other.actor != null) + return false; + } else if (!actor.equals(other.actor)) + return false; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (targets == null) { + if (other.targets != null) + return false; + } else if (!targets.equals(other.targets)) + return false; + return true; + } + + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java index ddee23cef..f381aa207 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java @@ -33,11 +33,20 @@ import org.junit.Test; import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; public class ControlLoopGuardCompilerTest { - + @Test public void testTest1() { try { - this.test("src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml"); + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testTest2() { + try { + this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } catch (Exception e) { fail(e.getMessage()); } diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java index 28e3622f8..9cc1bbd6a 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -20,7 +20,6 @@ package org.onap.policy.controlloop.policy.guard; -import org.junit.Ignore; import org.junit.Test; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -47,7 +46,6 @@ import org.onap.policy.controlloop.poligy.guard.builder.ControlLoopGuardBuilder; public class ControlLoopGuardBuilderTest { - @Ignore @Test public void testControlLoopGuard() { try { @@ -70,7 +68,13 @@ public class ControlLoopGuardBuilderTest { // // Add a guard policy without limit constraint // - GuardPolicy policy1 = new GuardPolicy("1111", "guardpolicy1", "guardpolicy1", "APPC", "restart"); + String clname = "CL_vUSP123"; + LinkedList targets = new LinkedList(); + targets.add("s1"); + targets.add("s2"); + targets.add("s3"); + MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets); + GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters); builder = builder.addGuardPolicy(policy1); // // Assert there is no limit constraint associated with the only guard policy @@ -87,16 +91,16 @@ public class ControlLoopGuardBuilderTest { // // Add a constraint to policy1 // - Map time_in_range = new HashMap(); - time_in_range.put("arg2", "PT5H"); - time_in_range.put("arg3", "PT24H"); + Map active_time_range = new HashMap(); + active_time_range.put("start", "00:00:00-05:00"); + active_time_range.put("end", "23:59:59-05:00"); List blacklist = new LinkedList(); blacklist.add("eNodeB_common_id1"); blacklist.add("eNodeB_common_id2"); - Map duration = new HashMap(); - duration.put("value", "10"); - duration.put("units", "minute"); - Constraint cons = new Constraint(5, duration, time_in_range, blacklist); + Map time_window = new HashMap(); + time_window.put("value", "10"); + time_window.put("units", "minute"); + Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); builder = builder.addLimitConstraint(policy1.id, cons); // // Add a duplicate constraint to policy1 @@ -152,7 +156,12 @@ public class ControlLoopGuardBuilderTest { @Test public void test1() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml"); + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } + + @Test + public void test2() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } public void test(String testFile) { diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java index 1475553d4..61ad4dfbf 100644 --- a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java @@ -39,12 +39,12 @@ public class ControlLoopGuardTest { @Test public void testGuardvDNS() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); } @Test public void testGuardvUSP() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml"); + this.test("src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml"); } diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml new file mode 100644 index 000000000..f2390fae0 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml @@ -0,0 +1,19 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_ONAP_vDNS_1 + name: MSO Spinup + description: We only spin up 1 instance over a 10 minute window + match_parameters: + actor: MSO + recipe: VF Module Create + limit_constraints: + - freq_limit_per_target: 1 + # + # https://www.w3.org/TR/xmlschema-2/#duration + # + time_window: + value: 10 + units: hour + \ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml deleted file mode 100644 index 7b5f17c61..000000000 --- a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml +++ /dev/null @@ -1,14 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_ONAP_vDNS_1 - name: MSO Spinup - description: We only spin up 1 instance over a 10 minute window - actor: MSO - recipe: VF Module Create - limit_constraints: - - num: 1 - duration: - value: 15 - units: minute diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml~ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml~ deleted file mode 100644 index a0d76d225..000000000 --- a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml~ +++ /dev/null @@ -1,12 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_ONAP_vDNS_1 - name: MSO Spinup - description: We only spin up 1 instance over a 10 minute window - actor: MSO - recipe: VF Module Create - limit_constraints: - - num: 1 - duration: PT10M diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml new file mode 100644 index 000000000..6e47ca2b4 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_appc_restart.yaml @@ -0,0 +1,24 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_1 + name: APPC 5 Restart + description: + We only allow 5 restarts over 15 minute window during the day time hours (i.e. avoid midnight to 5am) + match_parameters: + controlLoopName: CL_NAME_ABC_123 + actor: APPC + recipe: Restart + targets: + - s1 + s2 + s3 + limit_constraints: + - freq_limit_per_target: 5 + time_window: + value: 15 + units: minute + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 \ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml deleted file mode 100644 index a487210cd..000000000 --- a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml +++ /dev/null @@ -1,26 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1 - name: APPC 5 Restart - description: - We only allow 5 restarts over 15 minute window during the day time hours (i.e. avoid midnight to 5am) - actor: APPC - recipe: Restart - limit_constraints: - - num: 5 - # - # https://www.w3.org/TR/xmlschema-2/#duration - # - duration: - value: 15 - units: minute - # - # XACML function time-in-range - # - # Assumption is that the "current time" is the 1st argument - # - time_in_range: - arg2: PT5H - arg3: PT24H \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_xacml_guard.drl b/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_xacml_guard.drl index 330f41b56..a141f4956 100644 --- a/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_xacml_guard.drl +++ b/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_xacml_guard.drl @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - -package com.att.ecomp.policy.controlloop; + +package org.onap.policy.controlloop; import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.VirtualControlLoopNotification; @@ -528,8 +528,6 @@ rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" Logger.metrics($lock); - - // // We are starting the operation but the actor won't be contacted until Guard is queried and permitted. // @@ -561,7 +559,8 @@ rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" Thread t = new Thread(new org.onap.policy.guard.CallGuardTask( XacmlPdpEngine, "", - drools.getWorkingMemory(), + drools.getWorkingMemory(), + $event.closedLoopControlName, $operation.policy.actor.toString(), $operation.policy.recipe, $manager.getTargetInstance($operation.policy), diff --git a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml index 560fa57f1..5d31730db 100644 --- a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml @@ -4,11 +4,18 @@ - + + + ${clname} + + + + + ${actor} - + ${recipe} diff --git a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml index 221fd6ddf..2d73a1e6d 100644 --- a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml @@ -4,14 +4,28 @@ - + + + + ${clname} + + + + + ${actor} - + ${recipe} + + + ${targets} + + + diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/ControlLoopXacmlGuardTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/ControlLoopXacmlGuardTest.java deleted file mode 100644 index 1562c0ce6..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/ControlLoopXacmlGuardTest.java +++ /dev/null @@ -1,674 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * 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.controlloop.processor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.Instant; -import java.util.HashMap; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Ignore; -import org.junit.Test; -import org.kie.api.KieServices; -import org.kie.api.builder.KieBuilder; -import org.kie.api.builder.KieFileSystem; -import org.kie.api.builder.Message; -import org.kie.api.builder.ReleaseId; -import org.kie.api.builder.Results; -import org.kie.api.builder.model.KieModuleModel; -import org.kie.api.event.rule.AfterMatchFiredEvent; -import org.kie.api.event.rule.AgendaEventListener; -import org.kie.api.event.rule.AgendaGroupPoppedEvent; -import org.kie.api.event.rule.AgendaGroupPushedEvent; -import org.kie.api.event.rule.BeforeMatchFiredEvent; -import org.kie.api.event.rule.MatchCancelledEvent; -import org.kie.api.event.rule.MatchCreatedEvent; -import org.kie.api.event.rule.ObjectDeletedEvent; -import org.kie.api.event.rule.ObjectInsertedEvent; -import org.kie.api.event.rule.ObjectUpdatedEvent; -import org.kie.api.event.rule.RuleFlowGroupActivatedEvent; -import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent; -import org.kie.api.event.rule.RuleRuntimeEventListener; -import org.kie.api.runtime.KieContainer; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.appc.Request; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.appc.ResponseValue; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; - -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.ControlLoopLogger; -import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.controlloop.policy.TargetType; -import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; -import org.onap.policy.guard.PolicyGuard; -import org.onap.policy.guard.PolicyGuardYamlToXacml; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; - -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; - - -public class ControlLoopXacmlGuardTest { - - - - @Ignore - @Test - public void test() { - try { - this.runTest("src/main/resources/ControlLoop_Template_1707_xacml_guard.drl", - "src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml", - "service=vUSP;resource=vCTS;type=operational", - "CL_VUSP_8888", - "com.att.ecomp.closed_loop.vUSP:VNFS:0.0.1"); - } catch (IOException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - public void runTest(String droolsTemplate, - String yamlFile, - String policyScope, - String policyName, - String policyVersion) throws IOException { - // - // Pull info from the yaml - // - final Util.Pair pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.controlLoop); - assertNotNull(pair.a.controlLoop.controlLoopName); - assertTrue(pair.a.controlLoop.controlLoopName.length() > 0); - // - // Build a container - // - final KieSession kieSession = buildContainer(droolsTemplate, - pair.a.controlLoop.controlLoopName, - policyScope, - policyName, - policyVersion, - URLEncoder.encode(pair.b, "UTF-8")); - - - - System.out.println("============"); - System.out.println(URLEncoder.encode(pair.b, "UTF-8")); - System.out.println("============"); - - - kieSession.addEventListener(new RuleRuntimeEventListener() { - - @Override - public void objectInserted(ObjectInsertedEvent event) { - } - - @Override - public void objectUpdated(ObjectUpdatedEvent event) { - } - - @Override - public void objectDeleted(ObjectDeletedEvent event) { - } - }); - kieSession.addEventListener(new AgendaEventListener() { - - @Override - public void matchCreated(MatchCreatedEvent event) { - //System.out.println("matchCreated: " + event.getMatch().getRule()); - } - - @Override - public void matchCancelled(MatchCancelledEvent event) { - } - - @Override - public void beforeMatchFired(BeforeMatchFiredEvent event) { - //System.out.println("beforeMatchFired: " + event.getMatch().getRule() + event.getMatch().getObjects()); - } - - @Override - public void afterMatchFired(AfterMatchFiredEvent event) { - } - - @Override - public void agendaGroupPopped(AgendaGroupPoppedEvent event) { - } - - @Override - public void agendaGroupPushed(AgendaGroupPushedEvent event) { - } - - @Override - public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) { - } - - @Override - public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) { - } - - @Override - public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { - } - - @Override - public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { - } - - }); - - // - // Create XACML Guard policy from YAML - // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) - // - fromYamlToXacml("src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); - - fromYamlToXacml("src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); - - fromYamlToXacml("src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); - - fromYamlToXacml("src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml", - "src/main/resources/blacklist_template.xml", - "src/test/resources/xacml/autogenerated_blacklist.xml"); - - - // - // Insert our globals - // - final ControlLoopLogger logger = new ControlLoopLoggerStdOutImpl(); - kieSession.setGlobal("Logger", logger); - final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl(); - kieSession.setGlobal("Engine", engine); - - - // - // Creating an embedded XACML PDP - // - final PDPEngine xacmlPdpEngine; - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); - - PDPEngineFactory factory; - try { - factory = PDPEngineFactory.newInstance(); - xacmlPdpEngine = factory.newEngine(); - kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine); - } catch (FactoryException e1) { - e1.printStackTrace(); - } - - - - // - // Initial fire of rules - // - kieSession.fireAllRules(); - // - // Kick a thread that starts testing - // - new Thread(new Runnable() { - - - @Override - public void run() { - try { - - - // - // Let's use a unique ID for the request and - // a unique trigger source. - // - UUID requestID = UUID.randomUUID(); - String triggerSourceName = "foobartriggersource36"; - - Object obj = null; - - sendGoodEvents(kieSession, pair.a, requestID, triggerSourceName); - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE)); - // - // Give the control loop a little time to acquire the lock and publish the request - // - Thread.sleep(2000); - - - // "About to query Guard" notification (Querying about Restart) - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!"); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - Thread.sleep(2000); - // "Response from Guard" notification - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - - if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ - - // "About to query Guard" notification (Querying about Rebuild) - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("\n\n####################### GOING TO QUERY GUARD about Rebuild!!!!!!"); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - Thread.sleep(2000); - - // "Response from Guard" notification - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - - if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ - - // "About to query Guard" notification (Querying about Migrate) - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("\n\n####################### GOING TO QUERY GUARD!!!!!!"); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - Thread.sleep(2000); - - // "Response from Guard" notification - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - - if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ - //All the 3 operations were Denied by Guard - Thread.sleep(30000); - - } - } - } - - // - // In case one of the operations was permitted by Guard - // - if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")){ - obj = engine.subscribe("UEB", "POLICY-CL-MGT"); - assertNotNull(obj); - System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); - assertTrue(obj instanceof VirtualControlLoopNotification); - assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); - - Thread.sleep(500); - - obj = engine.subscribe("UEB", "APPC-CL"); - assertNotNull(obj); - assertTrue(obj instanceof Request); - assertTrue(((Request)obj).CommonHeader.SubRequestID.equals("1")); - - System.out.println("\n============ APP-C Got request!!! ===========\n"); - // - // Ok - let's simulate ACCEPT - // - - // - // now wait for it to finish - // - Thread.sleep(500); - - // - // Now we are going to success it - // - Response response = new Response((Request) obj); - response.Status.Code = ResponseCode.SUCCESS.getValue(); - response.Status.Value = ResponseValue.SUCCESS.toString(); - response.Status.Description = "AppC success"; - kieSession.insert(response); - // - // Give it some time to process - // - Thread.sleep(2000); - // - // Insert the abatement event - // - sendAbatement(kieSession, pair.a, requestID, triggerSourceName); - // - // now wait for it to finish - // - Thread.sleep(5000); - // - // Ensure they released the lock - // - assertFalse(PolicyGuard.isLocked(TargetType.VM, triggerSourceName, requestID)); - - } - - - - } catch (InterruptedException e) { - System.err.println("Test thread got InterruptedException " + e.getLocalizedMessage()); - } catch (AssertionError e) { - System.err.println("Test thread got AssertionError " + e.getLocalizedMessage()); - e.printStackTrace(); - } catch (Exception e) { - System.err.println("Test thread got Exception " + e.getLocalizedMessage()); - e.printStackTrace(); - } - kieSession.halt(); - } - - }).start(); - // - // Start firing rules - // - kieSession.fireUntilHalt(); - // - // Dump working memory - // - dumpFacts(kieSession); - // - // See if there is anything left in memory - // - assertEquals(1, kieSession.getFactCount()); - - for (FactHandle handle : kieSession.getFactHandles()) { - Object fact = kieSession.getObject(handle); - assertEquals("", "com.att.ecomp.policy.controlloop.Params", fact.getClass().getName()); - } - } - - - - - public static void dumpFacts(KieSession kieSession) { - System.out.println("Fact Count: " + kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - System.out.println("FACT: " + handle); - } - } - - protected void sendAbatement(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.closedLoopControlName = policy.controlLoop.controlLoopName; - event.requestID = requestID; - event.target = "vserver.vserver-name"; - event.closedLoopAlarmStart = Instant.now().minusSeconds(5); - event.closedLoopAlarmEnd = Instant.now(); - event.AAI = new HashMap(); - event.AAI.put("cloud-region.identity-url", "foo"); - event.AAI.put("vserver.selflink", "bar"); - event.AAI.put("vserver.is-closed-loop-disabled", "false"); - event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName"); - event.closedLoopEventStatus = ControlLoopEventStatus.ABATED; - kieSession.insert(event); - } - - protected void sendGoodEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.closedLoopControlName = policy.controlLoop.controlLoopName; - event.requestID = requestID; - event.target = "vserver.vserver-name"; - event.closedLoopAlarmStart = Instant.now(); - event.AAI = new HashMap(); - event.AAI.put("cloud-region.identity-url", "foo"); - event.AAI.put("vserver.selflink", "bar"); - event.AAI.put("vserver.is-closed-loop-disabled", "false"); - event.AAI.put("vserver.vserver-name", "testGenericVnfName"); - event.closedLoopEventStatus = ControlLoopEventStatus.ONSET; - kieSession.insert(event); - Thread.sleep(1000); - - /* - event = new ATTControlLoopEvent(event); - event.triggerID = "107.250.169.145_f5BigIP" + Instant.now().toEpochMilli(); - kieSession.insert(event); - Thread.sleep(1000); - - event = new ATTControlLoopEvent(event); - event.triggerID = "107.250.169.145_f5BigIP" + Instant.now().toEpochMilli(); - kieSession.insert(event); - Thread.sleep(1000); - - event = new ATTControlLoopEvent(event); - event.triggerID = "107.250.169.145_f5BigIP" + Instant.now().toEpochMilli(); - kieSession.insert(event); - Thread.sleep(1000); - */ - - } - - protected void sendBadEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { - // - // Insert a bad Event - // - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.closedLoopControlName = policy.controlLoop.controlLoopName; - kieSession.insert(event); - Thread.sleep(250); - // - // add the request id - // - event.requestID = requestID; - kieSession.insert(event); - Thread.sleep(250); - // - // add some aai - // - event.AAI = new HashMap(); - event.AAI.put("cloud-region.identity-url", "foo"); - event.AAI.put("vserver.selflink", "bar"); - event.AAI.put("vserver.vserver-name", "vmfoo"); - kieSession.insert(event); - Thread.sleep(250); - // - // set a valid status - // - event.closedLoopEventStatus = ControlLoopEventStatus.ONSET; - kieSession.insert(event); - Thread.sleep(250); - // - // add a trigger sourcename - // - kieSession.insert(event); - Thread.sleep(250); - // - // add is closed-loop-disabled - // - event.AAI.put("vserver.is-closed-loop-disabled", "true"); - kieSession.insert(event); - Thread.sleep(250); - // - // now enable - // - event.AAI.put("vserver.is-closed-loop-disabled", "false"); - kieSession.insert(event); - Thread.sleep(250); - // - // Add target, but bad. - // - event.target = "VM_BLAH"; - kieSession.insert(event); - Thread.sleep(250); - } - - - 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 = PolicyGuardYamlToXacml.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) { - e.printStackTrace(); - } - - } - - - - public static String generatePolicy(String ruleContents, - String closedLoopControlName, - String policyScope, - String policyName, - String policyVersion, - String controlLoopYaml) { - - Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}"); - Matcher m = p.matcher(ruleContents); - ruleContents = m.replaceAll(closedLoopControlName); - - p = Pattern.compile("\\$\\{policyScope\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyScope); - - p = Pattern.compile("\\$\\{policyName\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyName); - - p = Pattern.compile("\\$\\{policyVersion\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyVersion); - - p = Pattern.compile("\\$\\{controlLoopYaml\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(controlLoopYaml); - System.out.println(ruleContents); - - return ruleContents; - } - - public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException { - // - // Get our Drools Kie factory - // - KieServices ks = KieServices.Factory.get(); - - KieModuleModel kModule = ks.newKieModuleModel(); - - System.out.println("KMODULE:" + System.lineSeparator() + kModule.toXML()); - - // - // Generate our drools rule from our template - // - KieFileSystem kfs = ks.newKieFileSystem(); - - kfs.writeKModuleXML(kModule.toXML()); - { - Path rule = Paths.get(droolsTemplate); - String ruleTemplate = new String(Files.readAllBytes(rule)); - String drlContents = generatePolicy(ruleTemplate, - closedLoopControlName, - policyScope, - policyName, - policyVersion, - yamlSpecification); - - kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes())); - } - // - // Compile the rule - // - KieBuilder builder = ks.newKieBuilder(kfs).buildAll(); - Results results = builder.getResults(); - if (results.hasMessages(Message.Level.ERROR)) { - for (Message msg : results.getMessages()) { - System.err.println(msg.toString()); - } - throw new RuntimeException("Drools Rule has Errors"); - } - for (Message msg : results.getMessages()) { - System.out.println(msg.toString()); - } - // - // Create our kie Session and container - // - ReleaseId releaseId = ks.getRepository().getDefaultReleaseId(); - System.out.println(releaseId); - KieContainer kContainer = ks.newKieContainer(releaseId); - - return kContainer.newKieSession(); - } - - - - -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/Util.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/Util.java deleted file mode 100644 index afb1e9b22..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/Util.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * 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.controlloop.processor; - -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/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopXacmlGuardTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopXacmlGuardTest.java new file mode 100644 index 000000000..56ef3c641 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopXacmlGuardTest.java @@ -0,0 +1,623 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Instant; +import java.util.HashMap; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Ignore; +import org.junit.Test; +import org.kie.api.KieServices; +import org.kie.api.builder.KieBuilder; +import org.kie.api.builder.KieFileSystem; +import org.kie.api.builder.Message; +import org.kie.api.builder.ReleaseId; +import org.kie.api.builder.Results; +import org.kie.api.builder.model.KieModuleModel; +import org.kie.api.event.rule.AfterMatchFiredEvent; +import org.kie.api.event.rule.AgendaEventListener; +import org.kie.api.event.rule.AgendaGroupPoppedEvent; +import org.kie.api.event.rule.AgendaGroupPushedEvent; +import org.kie.api.event.rule.BeforeMatchFiredEvent; +import org.kie.api.event.rule.MatchCancelledEvent; +import org.kie.api.event.rule.MatchCreatedEvent; +import org.kie.api.event.rule.ObjectDeletedEvent; +import org.kie.api.event.rule.ObjectInsertedEvent; +import org.kie.api.event.rule.ObjectUpdatedEvent; +import org.kie.api.event.rule.RuleFlowGroupActivatedEvent; +import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent; +import org.kie.api.event.rule.RuleRuntimeEventListener; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseValue; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopLogger; +import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; +import org.onap.policy.guard.PolicyGuard; +import org.onap.policy.guard.PolicyGuardYamlToXacml; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; + +//import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; + + +public class ControlLoopXacmlGuardTest { + + + @Ignore + @Test + public void test() { + try { + this.runTest("src/main/resources/ControlLoop_Template_xacml_guard.drl", + "src/test/resources/yaml/policy_ControlLoop_Service123.yaml", + "service=Service123;resource=Res123;type=operational", + "CL_SERV123_8888", + "org.onap.closed_loop.Service123:VNFS:0.0.1"); + } catch (IOException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + public void runTest(String droolsTemplate, + String yamlFile, + String policyScope, + String policyName, + String policyVersion) throws IOException { + // + // Pull info from the yaml + // + final Util.Pair pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.a); + assertNotNull(pair.a.controlLoop); + assertNotNull(pair.a.controlLoop.controlLoopName); + assertTrue(pair.a.controlLoop.controlLoopName.length() > 0); + // + // Build a container + // + final KieSession kieSession = buildContainer(droolsTemplate, + pair.a.controlLoop.controlLoopName, + policyScope, + policyName, + policyVersion, + URLEncoder.encode(pair.b, "UTF-8")); + + + + System.out.println("============"); + System.out.println(URLEncoder.encode(pair.b, "UTF-8")); + System.out.println("============"); + + + kieSession.addEventListener(new RuleRuntimeEventListener() { + + @Override + public void objectInserted(ObjectInsertedEvent event) { + } + + @Override + public void objectUpdated(ObjectUpdatedEvent event) { + } + + @Override + public void objectDeleted(ObjectDeletedEvent event) { + } + }); + kieSession.addEventListener(new AgendaEventListener() { + + @Override + public void matchCreated(MatchCreatedEvent event) { + //System.out.println("matchCreated: " + event.getMatch().getRule()); + } + + @Override + public void matchCancelled(MatchCancelledEvent event) { + } + + @Override + public void beforeMatchFired(BeforeMatchFiredEvent event) { + //System.out.println("beforeMatchFired: " + event.getMatch().getRule() + event.getMatch().getObjects()); + } + + @Override + public void afterMatchFired(AfterMatchFiredEvent event) { + } + + @Override + public void agendaGroupPopped(AgendaGroupPoppedEvent event) { + } + + @Override + public void agendaGroupPushed(AgendaGroupPushedEvent event) { + } + + @Override + public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) { + } + + @Override + public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) { + } + + @Override + public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { + } + + @Override + public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { + } + + }); + + // + // Create XACML Guard policy from YAML + // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) + // + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", + "src/main/resources/blacklist_template.xml", + "src/test/resources/xacml/autogenerated_blacklist.xml"); + + + // + // Insert our globals + // + final ControlLoopLogger logger = new ControlLoopLoggerStdOutImpl(); + kieSession.setGlobal("Logger", logger); + final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl(); + kieSession.setGlobal("Engine", engine); + + + // + // Creating an embedded XACML PDP + // + final PDPEngine xacmlPdpEngine; + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); + + PDPEngineFactory factory; + try { + factory = PDPEngineFactory.newInstance(); + xacmlPdpEngine = factory.newEngine(); + kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine); + } catch (FactoryException e1) { + e1.printStackTrace(); + } + + + + // + // Initial fire of rules + // + kieSession.fireAllRules(); + // + // Kick a thread that starts testing + // + new Thread(new Runnable() { + + + @Override + public void run() { + try { + + + // + // Let's use a unique ID for the request and + // a unique trigger source. + // + UUID requestID = UUID.randomUUID(); + String triggerSourceName = "foobartriggersource36"; + + Object obj = null; + + sendGoodEvents(kieSession, pair.a, requestID, triggerSourceName); + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE)); + // + // Give the control loop a little time to acquire the lock and publish the request + // + Thread.sleep(2000); + + + // "About to query Guard" notification (Querying about Restart) + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!"); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + Thread.sleep(2000); + // "Response from Guard" notification + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + + if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ + + // "About to query Guard" notification (Querying about Rebuild) + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("\n\n####################### GOING TO QUERY GUARD about Rebuild!!!!!!"); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + Thread.sleep(2000); + + // "Response from Guard" notification + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + + if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ + + // "About to query Guard" notification (Querying about Migrate) + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("\n\n####################### GOING TO QUERY GUARD!!!!!!"); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + Thread.sleep(2000); + + // "Response from Guard" notification + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + + if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){ + //All the 3 operations were Denied by Guard + Thread.sleep(30000); + + } + } + } + + // + // In case one of the operations was permitted by Guard + // + if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")){ + obj = engine.subscribe("UEB", "POLICY-CL-MGT"); + assertNotNull(obj); + System.out.println("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message); + assertTrue(obj instanceof VirtualControlLoopNotification); + assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION)); + + Thread.sleep(500); + + obj = engine.subscribe("UEB", "APPC-CL"); + assertNotNull(obj); + assertTrue(obj instanceof Request); + assertTrue(((Request)obj).CommonHeader.SubRequestID.equals("1")); + + System.out.println("\n============ APP-C Got request!!! ===========\n"); + // + // Ok - let's simulate ACCEPT + // + + // + // now wait for it to finish + // + Thread.sleep(500); + + // + // Now we are going to success it + // + Response response = new Response((Request) obj); + response.Status.Code = ResponseCode.SUCCESS.getValue(); + response.Status.Value = ResponseValue.SUCCESS.toString(); + response.Status.Description = "AppC success"; + kieSession.insert(response); + // + // Give it some time to process + // + Thread.sleep(2000); + // + // Insert the abatement event + // + sendAbatement(kieSession, pair.a, requestID, triggerSourceName); + // + // now wait for it to finish + // + Thread.sleep(5000); + // + // Ensure they released the lock + // + assertFalse(PolicyGuard.isLocked(TargetType.VM, triggerSourceName, requestID)); + + } + + + + } catch (InterruptedException e) { + System.err.println("Test thread got InterruptedException " + e.getLocalizedMessage()); + } catch (AssertionError e) { + System.err.println("Test thread got AssertionError " + e.getLocalizedMessage()); + e.printStackTrace(); + } catch (Exception e) { + System.err.println("Test thread got Exception " + e.getLocalizedMessage()); + e.printStackTrace(); + } + kieSession.halt(); + } + + }).start(); + // + // Start firing rules + // + kieSession.fireUntilHalt(); + // + // Dump working memory + // + dumpFacts(kieSession); + // + // See if there is anything left in memory + // + assertEquals(1, kieSession.getFactCount()); + + for (FactHandle handle : kieSession.getFactHandles()) { + Object fact = kieSession.getObject(handle); + assertEquals("", "org.onap.policy.controlloop.Params", fact.getClass().getName()); + } + } + + + + + public static void dumpFacts(KieSession kieSession) { + System.out.println("Fact Count: " + kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + System.out.println("FACT: " + handle); + } + } + + protected void sendAbatement(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.closedLoopControlName = policy.controlLoop.controlLoopName; + event.requestID = requestID; + event.target = "vserver.vserver-name"; + event.closedLoopAlarmStart = Instant.now().minusSeconds(5); + event.closedLoopAlarmEnd = Instant.now(); + event.AAI = new HashMap(); + event.AAI.put("cloud-region.identity-url", "foo"); + event.AAI.put("vserver.selflink", "bar"); + event.AAI.put("vserver.is-closed-loop-disabled", "false"); + event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName"); + event.closedLoopEventStatus = ControlLoopEventStatus.ABATED; + kieSession.insert(event); + } + + protected void sendGoodEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.closedLoopControlName = policy.controlLoop.controlLoopName; + event.requestID = requestID; + event.target = "vserver.vserver-name"; + event.closedLoopAlarmStart = Instant.now(); + event.AAI = new HashMap(); + event.AAI.put("cloud-region.identity-url", "foo"); + event.AAI.put("vserver.selflink", "bar"); + event.AAI.put("vserver.is-closed-loop-disabled", "false"); + event.AAI.put("vserver.vserver-name", "testGenericVnfName"); + event.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + kieSession.insert(event); + Thread.sleep(1000); + + } + + protected void sendBadEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException { + // + // Insert a bad Event + // + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.closedLoopControlName = policy.controlLoop.controlLoopName; + kieSession.insert(event); + Thread.sleep(250); + // + // add the request id + // + event.requestID = requestID; + kieSession.insert(event); + Thread.sleep(250); + // + // add some aai + // + event.AAI = new HashMap(); + event.AAI.put("cloud-region.identity-url", "foo"); + event.AAI.put("vserver.selflink", "bar"); + event.AAI.put("vserver.vserver-name", "vmfoo"); + kieSession.insert(event); + Thread.sleep(250); + // + // set a valid status + // + event.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + kieSession.insert(event); + Thread.sleep(250); + // + // add a trigger sourcename + // + kieSession.insert(event); + Thread.sleep(250); + // + // add is closed-loop-disabled + // + event.AAI.put("vserver.is-closed-loop-disabled", "true"); + kieSession.insert(event); + Thread.sleep(250); + // + // now enable + // + event.AAI.put("vserver.is-closed-loop-disabled", "false"); + kieSession.insert(event); + Thread.sleep(250); + // + // Add target, but bad. + // + event.target = "VM_BLAH"; + kieSession.insert(event); + Thread.sleep(250); + } + + + + + public static String generatePolicy(String ruleContents, + String closedLoopControlName, + String policyScope, + String policyName, + String policyVersion, + String controlLoopYaml) { + + Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}"); + Matcher m = p.matcher(ruleContents); + ruleContents = m.replaceAll(closedLoopControlName); + + p = Pattern.compile("\\$\\{policyScope\\}"); + m = p.matcher(ruleContents); + ruleContents = m.replaceAll(policyScope); + + p = Pattern.compile("\\$\\{policyName\\}"); + m = p.matcher(ruleContents); + ruleContents = m.replaceAll(policyName); + + p = Pattern.compile("\\$\\{policyVersion\\}"); + m = p.matcher(ruleContents); + ruleContents = m.replaceAll(policyVersion); + + p = Pattern.compile("\\$\\{controlLoopYaml\\}"); + m = p.matcher(ruleContents); + ruleContents = m.replaceAll(controlLoopYaml); + System.out.println(ruleContents); + + return ruleContents; + } + + public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException { + // + // Get our Drools Kie factory + // + KieServices ks = KieServices.Factory.get(); + + KieModuleModel kModule = ks.newKieModuleModel(); + + System.out.println("KMODULE:" + System.lineSeparator() + kModule.toXML()); + + // + // Generate our drools rule from our template + // + KieFileSystem kfs = ks.newKieFileSystem(); + + kfs.writeKModuleXML(kModule.toXML()); + { + Path rule = Paths.get(droolsTemplate); + String ruleTemplate = new String(Files.readAllBytes(rule)); + String drlContents = generatePolicy(ruleTemplate, + closedLoopControlName, + policyScope, + policyName, + policyVersion, + yamlSpecification); + + kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes())); + } + // + // Compile the rule + // + KieBuilder builder = ks.newKieBuilder(kfs).buildAll(); + Results results = builder.getResults(); + if (results.hasMessages(Message.Level.ERROR)) { + for (Message msg : results.getMessages()) { + System.err.println(msg.toString()); + } + throw new RuntimeException("Drools Rule has Errors"); + } + for (Message msg : results.getMessages()) { + System.out.println(msg.toString()); + } + // + // Create our kie Session and container + // + ReleaseId releaseId = ks.getRepository().getDefaultReleaseId(); + System.out.println(releaseId); + KieContainer kContainer = ks.newKieContainer(releaseId); + + return kContainer.newKieSession(); + } + + + + +} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java new file mode 100644 index 000000000..2793f9aa2 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * 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.template.demo; + +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/templates/template.demo/src/test/resources/xacml/xacml_guard_old.properties b/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard_old.properties deleted file mode 100644 index 0f858da8d..000000000 --- a/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard_old.properties +++ /dev/null @@ -1,277 +0,0 @@ -# -# -# This files defines PIPs that will be used by XACML Guard Policies. One PIP per time window (5 min, 10min,...,1 month). -# -# -# - -# -# Default XACML Properties File -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory -xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - - -# -# NOTE: If you are testing against a RESTful PDP, then the PDP must be configured with the -# policies and PIP configuration as defined below. Otherwise, this is the configuration that -# the embedded PDP uses. -# - -# In case we have multiple applicable Guard policies, we will deny if any of them denies. -#xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides -xacml.att.policyFinderFactory.combineRootPolicies=urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:permit-unless-deny - - -# Policies to load -# -xacml.rootPolicies=p1,p2,p3,p4 -p1.file=src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml -p2.file=src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml -p3.file=src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml -p4.file=src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml -#p5.file=src/test/resources/xacml/autogenerated_blacklist.xml -#p6.file=src/test/resources/xacml/new_restart1.xml -#p7.file=src/test/resources/xacml/new_restart2.xml -#p8.file=src/test/resources/xacml/new_rebuild1.xml -#p9.file=src/test/resources/xacml/new_rebuild2.xml -#p10.file=src/test/resources/xacml/new_migrate1.xml -#p11.file=src/test/resources/xacml/new_migrate2.xml - -# PIP Engine Definition -# -xacml.pip.engines=sql1,test1 -test1.classname=com.att.ecomp.policy.guard.PIPEngineGetHistory -test1.issuer=com:att:research:xacml:guard:historydb - - -sql1.classname=com.att.research.xacml.std.pip.engines.jdbc.JDBCEngine -sql1.name=OperationsHistory -sql1.description=Database of operations performed via closed loop. -sql1.issuer=com:att:research:xacml:test:sql123 -sql1.type=jdbc -sql1.jdbc.driver=org.mariadb.jdbc.Driver -#sql1.jdbc.url=jdbc:mariadb://localhost:7779/policy -sql1.jdbc.url=jdbc:mariadb://135.207.129.112:3306/policy -sql1.jdbc.conn.user=root -sql1.jdbc.conn.password=lmpg - -#Each of the following resolvers corresponds to a specific time window. The only difference between them is the "interval" in the "select" SQL query and the "issuer". -sql1.resolvers=tw5min,tw10min,tw30min,tw1h,tw12h,tw1d,tw5d,tw1w,tw1mon - - - -############################################## -sql1.resolver.tw5min.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 5 minute) and now() -sql1.resolver.tw5min.field.count.issuer=com:att:research:xacml:test:sql:tw5min - -sql1.resolver.tw5min.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw5min.name=OperationsCount -sql1.resolver.tw5min.description=This returns the number of previous operations within the given time window -sql1.resolver.tw5min.fields=count -sql1.resolver.tw5min.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw5min.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw5min.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw5min.parameters=actor,operation,target -sql1.resolver.tw5min.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw5min.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5min.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw5min.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw5min.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5min.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw5min.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw5min.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5min.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - -############################################## -sql1.resolver.tw10min.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 10 minute) and now() -sql1.resolver.tw10min.field.count.issuer=com:att:research:xacml:test:sql:tw10min - -sql1.resolver.tw10min.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw10min.name=OperationsCount -sql1.resolver.tw10min.description=This returns the number of previous operations within the given time window -sql1.resolver.tw10min.fields=count -sql1.resolver.tw10min.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw10min.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw10min.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw10min.parameters=actor,operation,target -sql1.resolver.tw10min.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw10min.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw10min.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw10min.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw10min.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw10min.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw10min.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw10min.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw10min.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - -############################################## -sql1.resolver.tw30min.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 30 minute) and now() -sql1.resolver.tw30min.field.count.issuer=com:att:research:xacml:test:sql:tw30min - -sql1.resolver.tw30min.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw30min.name=OperationsCount -sql1.resolver.tw30min.description=This returns the number of previous operations within the given time window -sql1.resolver.tw30min.fields=count -sql1.resolver.tw30min.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw30min.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw30min.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw30min.parameters=actor,operation,target -sql1.resolver.tw30min.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw30min.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw30min.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw30min.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw30min.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw30min.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw30min.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw30min.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw30min.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - -############################################## -sql1.resolver.tw1h.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 1 hour) and now() -sql1.resolver.tw1h.field.count.issuer=com:att:research:xacml:test:sql:tw1h - -sql1.resolver.tw1h.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw1h.name=OperationsCount -sql1.resolver.tw1h.description=This returns the number of previous operations within the given time window -sql1.resolver.tw1h.fields=count -sql1.resolver.tw1h.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw1h.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw1h.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw1h.parameters=actor,operation,target -sql1.resolver.tw1h.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw1h.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1h.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw1h.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw1h.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1h.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw1h.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw1h.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1h.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - - -############################################## -sql1.resolver.tw12h.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 12 hour) and now() -sql1.resolver.tw12h.field.count.issuer=com:att:research:xacml:test:sql:tw12h - -sql1.resolver.tw12h.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw12h.name=OperationsCount -sql1.resolver.tw12h.description=This returns the number of previous operations within the given time window -sql1.resolver.tw12h.fields=count -sql1.resolver.tw12h.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw12h.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw12h.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw12h.parameters=actor,operation,target -sql1.resolver.tw12h.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw12h.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw12h.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw12h.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw12h.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw12h.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw12h.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw12h.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw12h.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - - -############################# -sql1.resolver.tw1d.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 1 day) and now() -sql1.resolver.tw1d.field.count.issuer=com:att:research:xacml:test:sql:tw1d - -sql1.resolver.tw1d.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw1d.name=OperationsCount -sql1.resolver.tw1d.description=This returns the number of previous operations within the given time window -sql1.resolver.tw1d.fields=count -sql1.resolver.tw1d.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw1d.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw1d.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw1d.parameters=actor,operation,target -sql1.resolver.tw1d.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw1d.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1d.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw1d.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw1d.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1d.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw1d.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw1d.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1d.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - - -############################# -sql1.resolver.tw5d.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 5 day) and now() -sql1.resolver.tw5d.field.count.issuer=com:att:research:xacml:test:sql:tw5d - -sql1.resolver.tw5d.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw5d.name=OperationsCount -sql1.resolver.tw5d.description=This returns the number of previous operations within the given time window -sql1.resolver.tw5d.fields=count -sql1.resolver.tw5d.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw5d.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw5d.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw5d.parameters=actor,operation,target -sql1.resolver.tw5d.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw5d.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5d.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw5d.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw5d.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5d.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw5d.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw5d.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw5d.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - - -############################# -sql1.resolver.tw1w.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 1 week) and now() -sql1.resolver.tw1w.field.count.issuer=com:att:research:xacml:test:sql:tw1w - -sql1.resolver.tw1w.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw1w.name=OperationsCount -sql1.resolver.tw1w.description=This returns the number of previous operations within the given time window -sql1.resolver.tw1w.fields=count -sql1.resolver.tw1w.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw1w.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw1w.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw1w.parameters=actor,operation,target -sql1.resolver.tw1w.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw1w.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1w.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw1w.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw1w.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1w.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw1w.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw1w.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1w.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - -############################# -sql1.resolver.tw1mon.select=select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=? and operation=? and target=? and endtime between date_sub(now(),interval 1 month) and now() -sql1.resolver.tw1mon.field.count.issuer=com:att:research:xacml:test:sql:tw1mon - -sql1.resolver.tw1mon.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver -sql1.resolver.tw1mon.name=OperationsCount -sql1.resolver.tw1mon.description=This returns the number of previous operations within the given time window -sql1.resolver.tw1mon.fields=count -sql1.resolver.tw1mon.field.count.id=com:att:research:xacml:test:sql:resource:operations:count -sql1.resolver.tw1mon.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer -sql1.resolver.tw1mon.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource -sql1.resolver.tw1mon.parameters=actor,operation,target -sql1.resolver.tw1mon.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id -sql1.resolver.tw1mon.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1mon.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject -sql1.resolver.tw1mon.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id -sql1.resolver.tw1mon.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1mon.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action -sql1.resolver.tw1mon.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id -sql1.resolver.tw1mon.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string -sql1.resolver.tw1mon.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource - - diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_Service123.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_Service123.yaml new file mode 100644 index 000000000..ef9528850 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_Service123.yaml @@ -0,0 +1,62 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-Service123-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: Service123 + resources: + - resourceName: res1 + resourceType: VFC + - resourceName: res2 + resourceType: VFC + trigger_policy: unique-policy-id-1-restart + timeout: 60 + abatement: true + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: + type: VM + retry: 3 + timeout: 20 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_guard: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: + type: VM + retry: 0 + timeout: 10 + success: final_success + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: unique-policy-id-3-migrate + failure_guard: unique-policy-id-3-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: + type: VM + retry: 0 + timeout: 30 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_guard: final_failure_guard + failure_exception: final_failure_exception diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml deleted file mode 100644 index 62bf986bd..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml +++ /dev/null @@ -1,68 +0,0 @@ -controlLoop: - version: 1.0.0 - controlLoopName: ControlLoop-vUSP-vCTS-cbed919f-2212-4ef7-8051-fe6308da1bda - services: - - serviceName: vUSP - resources: - - resourceName: vCTS - resourceType: VF - - resourceName: vCOM - resourceType: VF - - resourceName: vRAR - resourceType: VF - - resourceName: vLCS - resourceType: VF - - resourceName: v3CB - resourceType: VF - trigger_policy: unique-policy-id-1-restart - timeout: 60 - abatement: true - -policies: - - id: unique-policy-id-1-restart - name: Restart Policy - description: - actor: APPC - recipe: Restart - target: - type: VM - retry: 3 - timeout: 20 - success: final_success - failure: unique-policy-id-2-rebuild - failure_timeout: unique-policy-id-2-rebuild - failure_retries: unique-policy-id-2-rebuild - failure_guard: unique-policy-id-2-rebuild - failure_exception: final_failure_exception - - - id: unique-policy-id-2-rebuild - name: Rebuild Policy - description: - actor: APPC - recipe: Rebuild - target: - type: VM - retry: 0 - timeout: 10 - success: final_success - failure: unique-policy-id-3-migrate - failure_timeout: unique-policy-id-3-migrate - failure_retries: unique-policy-id-3-migrate - failure_guard: unique-policy-id-3-migrate - failure_exception: final_failure_exception - - - id: unique-policy-id-3-migrate - name: Migrate Policy - description: - actor: APPC - recipe: Migrate - target: - type: VM - retry: 0 - timeout: 30 - success: final_success - failure: final_failure - failure_timeout: final_failure_timeout - failure_retries: final_failure_retries - failure_guard: final_failure_guard - failure_exception: final_failure_exception diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_migrate.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_migrate.yaml new file mode 100644 index 000000000..46f245994 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_migrate.yaml @@ -0,0 +1,26 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_1 + name: APPC 5 Migrate + description: | + We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) + match_parameters: + #controlLoopName: ControlLoop-Service123-cbed919f-2212-4ef7-8051-fe6308da1bda + actor: APPC + recipe: Migrate + limit_constraints: + - freq_limit_per_target: 1 + time_window: + value: 10 + units: minute + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 + + + + + + \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild.yaml new file mode 100644 index 000000000..a801cde0f --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild.yaml @@ -0,0 +1,26 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_3 + name: APPC 5 Rebuild + description: | + We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) + match_parameters: + controlLoopName: ControlLoop-Service123-cbed919f-2212-4ef7-8051-fe6308da1bda + actor: APPC + recipe: Rebuild + limit_constraints: + - freq_limit_per_target: 2 + time_window: + value: 10 + units: minute + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 + + + + + + \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml new file mode 100644 index 000000000..d703955b7 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml @@ -0,0 +1,26 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_2 + name: APPC 5 Rebuild + description: | + We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) + match_parameters: + controlLoopName: ControlLoop-Service123-cbed919f-2212-4ef7-8051-fe6308da1bda + actor: + recipe: Rebuild + limit_constraints: + - freq_limit_per_target: 25 + time_window: + value: 1 + units: week + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 + + + + + + \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart.yaml new file mode 100644 index 000000000..36b971fee --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart.yaml @@ -0,0 +1,27 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_5 + name: APPC 5 Restart + description: | + We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) + match_parameters: + controlLoopName: ControlLoop-Service123-cbed919f-2212-4ef7-8051-fe6308da1bda + actor: APPC + recipe: Restart + targets: + - s1 + - s2 + - foobartriggersource36 + - s3 + - testGenericVnfName + limit_constraints: + - freq_limit_per_target: 1 + time_window: + value: 10 + units: minute + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 + diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml new file mode 100644 index 000000000..acdb2e660 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml @@ -0,0 +1,27 @@ +guard: + version: 2.0.0 + +guards: + - id: unique_guard_4_Blacklist + name: APPC Restart Blacklist + description: | + We deny restart of the blacklisted targets (avoid midnight to 5am) + match_parameters: + actor: APPC + recipe: Restart + limit_constraints: + - blacklist: + - server123 + - server2234 + - vserver.vserver-name22 + - aaabbbccc + - foobartriggersource35 + active_time_range: + start: 00:00:00-05:00 + end: 23:59:59-05:00 + + + + + + \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml deleted file mode 100644 index 333895b2e..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml +++ /dev/null @@ -1,24 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1 - name: APPC 5 Migrate - description: | - We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) - actor: APPC - recipe: Migrate - limit_constraints: - - num: 1 - duration: - value: 10 - units: minute - time_in_range: - arg2: 00:00:00-05:00 - arg3: 23:59:59-05:00 - - - - - - \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml deleted file mode 100644 index 865915f82..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml +++ /dev/null @@ -1,24 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1 - name: APPC 5 Rebuild - description: | - We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) - actor: APPC - recipe: Rebuild - limit_constraints: - - num: 2 - duration: - value: 10 - units: minute - time_in_range: - arg2: 00:00:00-05:00 - arg3: 23:59:59-05:00 - - - - - - \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml deleted file mode 100644 index 6905d733f..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml +++ /dev/null @@ -1,24 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1 - name: APPC 5 Rebuild - description: | - We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) - actor: APPC - recipe: Rebuild - limit_constraints: - - num: 25 - duration: - value: 1 - units: week - time_in_range: - arg2: 00:00:00-05:00 - arg3: 23:59:59-05:00 - - - - - - \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml deleted file mode 100644 index b44ff00df..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml +++ /dev/null @@ -1,24 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1 - name: APPC 5 Restart - description: | - We only allow 2 restarts over 10 minute window during the day time hours (avoid midnight to 5am) - actor: APPC - recipe: Restart - limit_constraints: - - num: 2 - duration: - value: 10 - units: minute - time_in_range: - arg2: 00:00:00-05:00 - arg3: 23:59:59-05:00 - - - - - - \ No newline at end of file diff --git a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml deleted file mode 100644 index 50af17af6..000000000 --- a/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml +++ /dev/null @@ -1,26 +0,0 @@ -guard: - version: 2.0.0 - -guards: - - id: unique_guard_vUSP_1_Blacklist - name: APPC Restart Blacklist - description: | - We deny restart of the blacklisted targets (avoid midnight to 5am) - actor: APPC - recipe: Restart - limit_constraints: - - blacklist: - - server123 - - server2234 - - vserver.vserver-name22 - - aaabbbccc - - foobartriggersource35 - time_in_range: - arg2: 00:00:00-05:00 - arg3: 23:59:59-05:00 - - - - - - \ No newline at end of file -- cgit 1.2.3-korg