diff options
author | Gao, Chenfei (cg287m) <cgao@research.att.com> | 2017-06-22 14:48:41 -0400 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2017-06-29 12:50:23 -0400 |
commit | 68377161605e39c8c74ea77d0b504177480788f3 (patch) | |
tree | fb0fb8a27178da607866e1850f73ac056e046ee8 /controlloop | |
parent | f0c29b57e132e6335f0fa7bbad885d403e4c85df (diff) |
[POLICY-22] Reorganizing drools-apps
Change-Id: I5f9bb3908f8d55c466dd847ae5e01a424e9ba364
Signed-off-by: Gao, Chenfei (cg287m) <chenfei.gao11@gmail.com>
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'controlloop')
268 files changed, 31352 insertions, 64 deletions
diff --git a/controlloop/common/actors/actor.appc/pom.xml b/controlloop/common/actors/actor.appc/pom.xml new file mode 100644 index 000000000..5f6519a47 --- /dev/null +++ b/controlloop/common/actors/actor.appc/pom.xml @@ -0,0 +1,32 @@ +<?xml version="1.0"?> +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actors</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>actor.appc</artifactId> + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java b/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java new file mode 100644 index 000000000..fe6bf40af --- /dev/null +++ b/controlloop/common/actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/APPCActorServiceProvider.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * APPCActorServiceProvider + * ================================================================================ + * 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.actor.appc; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.policy.Policy; + +import org.onap.policy.controlloop.actorServiceProvider.spi.Actor; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + + +public class APPCActorServiceProvider implements Actor { + + private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig"); + private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() + .put("Restart", ImmutableList.of("VM")) + .put("Rebuild", ImmutableList.of("VM")) + .put("Migrate", ImmutableList.of("VM")) + .put("ModifyConfig", ImmutableList.of("VFC")) + .build(); + private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>() + .put("ModifyConfig", ImmutableList.of("generic-vnf.vnf-id")) + .build(); + + @Override + public String actor() { + return "APPC"; + } + + @Override + public List<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> recipePayloads(String recipe) { + return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList())); + } + + + public static Request constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy) { + // + // Construct an APPC request + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = onset.requestID; + request.CommonHeader.SubRequestID = operation.subRequestId; + request.Action = policy.recipe; + + // + // TODO: do we need to take care of the target + // + + // + // Handle the payload + // + if (policy.payload != null && !policy.payload.isEmpty()) { + request.Payload = new HashMap<String, Object>(); + // + // Add each payload entry + // + for (Map.Entry<String, String> entry : policy.payload.entrySet()) { + // + // TODO: entry key has ref$, value has {xxxx} + // + request.Payload.put(entry.getKey(), entry.getValue()); + } + } + + + request.Payload.put("AICVServerSelfLink", onset.AAI.get("vserver.selflink"));//.AICVServerSelfLink); + request.Payload.put("AICIdentity", onset.AAI.get("cloud-region.identity-url"));//AICIdentity); + // + // Return the request + // + return request; + } + + +} diff --git a/controlloop/common/actors/actor.appc/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor b/controlloop/common/actors/actor.appc/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor new file mode 100644 index 000000000..5e76150c4 --- /dev/null +++ b/controlloop/common/actors/actor.appc/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor @@ -0,0 +1 @@ +com.att.ecomp.policy.controlloop.actor.appc.APPCActorServiceProvider
\ No newline at end of file diff --git a/controlloop/common/actors/actor.mso/pom.xml b/controlloop/common/actors/actor.mso/pom.xml new file mode 100644 index 000000000..f0bbf48cb --- /dev/null +++ b/controlloop/common/actors/actor.mso/pom.xml @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actors</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>actor.mso</artifactId> + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/actors/actor.mso/src/main/java/org/onap/policy/controlloop/actor/mso/MSOActorServiceProvider.java b/controlloop/common/actors/actor.mso/src/main/java/org/onap/policy/controlloop/actor/mso/MSOActorServiceProvider.java new file mode 100644 index 000000000..d57e62634 --- /dev/null +++ b/controlloop/common/actors/actor.mso/src/main/java/org/onap/policy/controlloop/actor/mso/MSOActorServiceProvider.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * MSOActorServiceProvider + * ================================================================================ + * 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.actor.mso; + +import java.util.Collections; +import java.util.List; + +import org.onap.policy.controlloop.actorServiceProvider.spi.Actor; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class MSOActorServiceProvider implements Actor { + + private static final ImmutableList<String> recipes = ImmutableList.of( + "VF Module Create"); + private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>() + .put("VF Module Create", ImmutableList.of("VFC")) + .build(); + + @Override + public String actor() { + return "MSO"; + } + + @Override + public List<String> recipes() { + return ImmutableList.copyOf(recipes); + } + + @Override + public List<String> recipeTargets(String recipe) { + return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList())); + } + + @Override + public List<String> recipePayloads(String recipe) { + return Collections.emptyList(); + } + +} diff --git a/controlloop/common/actors/actor.mso/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor b/controlloop/common/actors/actor.mso/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor new file mode 100644 index 000000000..aeed27b3b --- /dev/null +++ b/controlloop/common/actors/actor.mso/src/main/resources/META-INF/services/com.att.ecomp.policy.controlloop.actorServiceProvider.spi.Actor @@ -0,0 +1 @@ +com.att.ecomp.policy.controlloop.actor.mso.MSOActorServiceProvider
\ No newline at end of file diff --git a/controlloop/common/actors/actor.test/pom.xml b/controlloop/common/actors/actor.test/pom.xml new file mode 100644 index 000000000..9d8ffa48d --- /dev/null +++ b/controlloop/common/actors/actor.test/pom.xml @@ -0,0 +1,41 @@ +<?xml version="1.0"?> +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actors</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>actor.test</artifactId> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <version>2.19.1</version> + <configuration> + <additionalClasspathElements> + <additionalClasspathElement>${settings.localRepository}/org/onap/policy/drools-applications/actor.appc/1.1.0-SNAPSHOT/actor.appc-1.1.0-SNAPSHOT.jar</additionalClasspathElement> + <additionalClasspathElement>${settings.localRepository}/org/onap/policy/drools-applications/actor.mso/1.1.0-SNAPSHOT/actor.mso-1.1.0-SNAPSHOT.jar</additionalClasspathElement> + </additionalClasspathElements> + </configuration> + </plugin> + </plugins> + </build> + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/actors/actor.test/src/test/java/org/onap/policy/controlloop/actor/test/Test.java b/controlloop/common/actors/actor.test/src/test/java/org/onap/policy/controlloop/actor/test/Test.java new file mode 100644 index 000000000..f6eba49af --- /dev/null +++ b/controlloop/common/actors/actor.test/src/test/java/org/onap/policy/controlloop/actor/test/Test.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * actor test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.test; + +import static org.junit.Assert.*; + +import org.onap.policy.controlloop.actorServiceProvider.ActorService; +import org.onap.policy.controlloop.actorServiceProvider.spi.Actor; + +public class Test { + + @org.junit.Test + public void test() { + System.out.println("Dumping actors"); + ActorService actorService = ActorService.getInstance(); + assertNotNull(actorService); + int num = 0; + for (Actor actor : actorService.actors()) { + System.out.println(actor.actor()); + for (String recipe : actor.recipes()) { + System.out.println("\t" + recipe + " " + actor.recipeTargets(recipe) + " " + actor.recipePayloads(recipe)); + } + num++; + } + System.out.println("Found " + num + " actors"); + } + +} diff --git a/controlloop/common/actors/actorServiceProvider/pom.xml b/controlloop/common/actors/actorServiceProvider/pom.xml new file mode 100644 index 000000000..874871348 --- /dev/null +++ b/controlloop/common/actors/actorServiceProvider/pom.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actors</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>actorServiceProvider</artifactId> +</project> diff --git a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/ActorService.java b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/ActorService.java new file mode 100644 index 000000000..2632d0752 --- /dev/null +++ b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/ActorService.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ActorService + * ================================================================================ + * 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.actorServiceProvider; + +import java.util.Iterator; +import java.util.ServiceLoader; + +import org.onap.policy.controlloop.actorServiceProvider.spi.Actor; +import com.google.common.collect.ImmutableList; + +public class ActorService { + + private static ActorService service; + + private ServiceLoader<Actor> loader; + + private ActorService() { + loader = ServiceLoader.load(Actor.class); + } + + public static synchronized ActorService getInstance() { + if (service == null) { + service = new ActorService(); + } + return service; + } + + public ImmutableList<Actor> actors() { + Iterator<Actor> iter = loader.iterator(); + System.out.println("returning actors"); + while (iter.hasNext()) { + System.out.println("Got " + iter.next().actor()); + } + + return ImmutableList.copyOf(loader.iterator()); + } + +} diff --git a/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/spi/Actor.java b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/spi/Actor.java new file mode 100644 index 000000000..2492063c8 --- /dev/null +++ b/controlloop/common/actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorServiceProvider/spi/Actor.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * Actor + * ================================================================================ + * 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.actorServiceProvider.spi; + +import java.util.List; + +public interface Actor { + + public String actor(); + + public List<String> recipes(); + + public List<String> recipeTargets(String recipe); + + public List<String> recipePayloads(String recipe); + +} diff --git a/controlloop/common/actors/pom.xml b/controlloop/common/actors/pom.xml new file mode 100644 index 000000000..a00a3af52 --- /dev/null +++ b/controlloop/common/actors/pom.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>actors</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>actorServiceProvider</module> + <module>actor.appc</module> + <module>actor.mso</module> + <module>actor.test</module> + </modules> + <dependencies> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>19.0</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>policy-yaml</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/eventmanager/README.md b/controlloop/common/eventmanager/README.md new file mode 100644 index 000000000..38f62de82 --- /dev/null +++ b/controlloop/common/eventmanager/README.md @@ -0,0 +1,3 @@ +ECOMP Policy Closed Loop Event Management Code + + diff --git a/controlloop/common/eventmanager/pom.xml b/controlloop/common/eventmanager/pom.xml new file mode 100644 index 000000000..e5ba6defa --- /dev/null +++ b/controlloop/common/eventmanager/pom.xml @@ -0,0 +1,125 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>eventmanager</artifactId> + <dependencies> + <dependency> + <groupId>com.att.nsa</groupId> + <artifactId>dmaapClient</artifactId> + <version>0.2.12</version> + </dependency> + <dependency> + <groupId>com.att.nsa</groupId> + <artifactId>cambriaClient</artifactId> + <version>0.0.1</version> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-core</artifactId> + <version>6.3.0.Final</version> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-compiler</artifactId> + <version>6.3.0.Final</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.17</version> + </dependency> + <dependency> + <groupId>org.jgrapht</groupId> + <artifactId>jgrapht-core</artifactId> + <version>0.9.2</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>policy-yaml</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actor.appc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>guard</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>postgresql</groupId> + <artifactId>postgresql</artifactId> + <version>9.1-901.jdbc4</version> + </dependency> + + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + <version>1.5.5</version> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>14.0.1</version> + </dependency> + + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>sdc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>javax.persistence</groupId> + <artifactId>persistence-api</artifactId> + <version>1.0.2</version> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>org.eclipse.persistence.jpa</artifactId> + <version>2.6.4</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java new file mode 100644 index 000000000..e828150a0 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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; + +public class ControlLoopException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 6400725747325923701L; + + public ControlLoopException() { + super(); + } + + public ControlLoopException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public ControlLoopException(String message, Throwable cause) { + super(message, cause); + } + + public ControlLoopException(String message) { + super(message); + } + + public ControlLoopException(Throwable cause) { + super(cause); + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java new file mode 100644 index 000000000..4495f2a71 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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; + +import java.lang.reflect.Constructor; + +public interface ControlLoopLogger { + + public void info(String... parameters); + + public void metrics(String... msgs); + + public void metrics(Object obj); + + public static class Factory { + + public ControlLoopLogger buildLogger(String className) { + try { + Constructor<?> constr = Class.forName(className).getConstructor(); + return (ControlLoopLogger) constr.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Cannot load class " + className); + } + } + + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java new file mode 100644 index 000000000..3ed6f8d58 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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; + +import java.lang.reflect.Constructor; + +public interface ControlLoopPublisher { + + public void publish(Object object); + + public static class Factory { + + public ControlLoopPublisher buildLogger(String className) { + try { + Constructor<?> constr = Class.forName(className).getConstructor(); + return (ControlLoopPublisher) constr.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Cannot load class " + className); + } + } + + } + + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java new file mode 100644 index 000000000..1892746f1 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java @@ -0,0 +1,572 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop event manager + * ================================================================================ + * 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.eventmanager; + +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.UUID; + +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; + +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.processor.ControlLoopProcessor; +import org.onap.policy.guard.GuardResult; +import org.onap.policy.guard.LockCallback; +import org.onap.policy.guard.PolicyGuard; +import org.onap.policy.guard.PolicyGuard.LockResult; +import org.onap.policy.guard.TargetLock; + +public class ControlLoopEventManager implements LockCallback, Serializable { + + /** + * + */ + private static final long serialVersionUID = -1216568161322872641L; + public final String closedLoopControlName; + public final UUID requestID; + + private String controlLoopResult; + private ControlLoopProcessor processor = null; + private VirtualControlLoopEvent onset; + private Integer numOnsets = 0; + private Integer numAbatements = 0; + private VirtualControlLoopEvent abatement; + private FinalResult controlLoopTimedOut = null; + + private boolean isActivated = false; + private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<ControlLoopOperation>(); + private ControlLoopOperationManager currentOperation = null; + private TargetLock targetLock = null; + + private static Collection<String> requiredAAIKeys = new ArrayList<String>(); + static { + requiredAAIKeys.add("AICVServerSelfLink"); + requiredAAIKeys.add("AICIdentity"); + requiredAAIKeys.add("is_closed_loop_disabled"); + requiredAAIKeys.add("VM_NAME"); + } + + public ControlLoopEventManager(String closedLoopControlName, UUID requestID) { + this.closedLoopControlName = closedLoopControlName; + this.requestID = requestID; + } + + public String getControlLoopResult() { + return controlLoopResult; + } + + public void setControlLoopResult(String controlLoopResult) { + this.controlLoopResult = controlLoopResult; + } + + public Integer getNumOnsets() { + return numOnsets; + } + + public void setNumOnsets(Integer numOnsets) { + this.numOnsets = numOnsets; + } + + public Integer getNumAbatements() { + return numAbatements; + } + + public void setNumAbatements(Integer numAbatements) { + this.numAbatements = numAbatements; + } + + public boolean isActivated() { + return isActivated; + } + + public void setActivated(boolean isActivated) { + this.isActivated = isActivated; + } + + public VirtualControlLoopEvent getOnsetEvent() { + return this.onset; + } + + public VirtualControlLoopEvent getAbatementEvent() { + return this.abatement; + } + + public ControlLoopProcessor getProcessor() { + return this.processor; + } + + public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); + try { + // + // This method should ONLY be called ONCE + // + if (this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager has already been activated."); + } + // + // Syntax check the event + // + checkEventSyntax(event); + // + // At this point we are good to go with this event + // + this.onset = event; + this.numOnsets = 1; + // + notification.notification = ControlLoopNotificationType.ACTIVE; + // + // Set ourselves as active + // + this.isActivated = true; + } catch (ControlLoopException e) { + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = e.getMessage(); + } + return notification; + } + + + + public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); + try { + // + // This method should ONLY be called ONCE + // + if (this.isActivated) { + throw new ControlLoopException("ControlLoopEventManager has already been activated."); + } + // + // Syntax check the event + // + checkEventSyntax(event); + + // + // Check the YAML + // + if (yamlSpecification == null || yamlSpecification.length() < 1) { + throw new ControlLoopException("yaml specification is null or 0 length"); + } + String decodedYaml = null; + try { + decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); + if (decodedYaml != null && decodedYaml.length() > 0) { + yamlSpecification = decodedYaml; + } + } catch (UnsupportedEncodingException e) { + } + // + // Parse the YAML specification + // + this.processor = new ControlLoopProcessor(yamlSpecification); + + // + // At this point we are good to go with this event + // + this.onset = event; + this.numOnsets = 1; + // + // + // + notification.notification = ControlLoopNotificationType.ACTIVE; + // + // Set ourselves as active + // + this.isActivated = true; + } catch (ControlLoopException e) { + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = e.getMessage(); + } + return notification; + } + + public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { + // + // Check if they activated us + // + if (this.isActivated == false) { + throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); + } + // + // Make sure we are expecting this call. + // + if (this.onset == null) { + throw new ControlLoopException("No onset event for ControlLoopEventManager."); + } + // + // Ok, start creating the notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); + // + // Check if the overall control loop has timed out + // + if (this.isControlLoopTimedOut()) { + // + // Yes we have timed out + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Control Loop timed out"; + notification.history.addAll(this.controlLoopHistory); + return notification; + } + // + // Check if the current policy is Final + // + FinalResult result = this.processor.checkIsCurrentPolicyFinal(); + if (result == null) { + // + // we are not at a final result + // + return null; + } + + switch (result) { + case FINAL_FAILURE: + case FINAL_FAILURE_EXCEPTION: + case FINAL_FAILURE_RETRIES: + case FINAL_FAILURE_TIMEOUT: + case FINAL_FAILURE_GUARD: + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + break; + case FINAL_OPENLOOP: + notification.notification = ControlLoopNotificationType.FINAL_OPENLOOP; + break; + case FINAL_SUCCESS: + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + break; + default: + return null; + } + // + // Be sure to add all the history + // + notification.history.addAll(this.controlLoopHistory); + return notification; + } + + public ControlLoopOperationManager processControlLoop() throws ControlLoopException { + // + // Check if they activated us + // + if (this.isActivated == false) { + throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); + } + // + // Make sure we are expecting this call. + // + if (this.onset == null) { + throw new ControlLoopException("No onset event for ControlLoopEventManager."); + } + // + // Is there a current operation? + // + if (this.currentOperation != null) { + // + // Throw an exception, or simply return the current operation? + // + throw new ControlLoopException("Already working an Operation, do not call this method."); + } + // + // Ensure we are not FINAL + // + VirtualControlLoopNotification notification = this.isControlLoopFinal(); + if (notification != null) { + // + // This is weird, we require them to call the isControlLoopFinal() method first + // + // We should really abstract this and avoid throwing an exception, because it really + // isn't an exception. + // + throw new ControlLoopException("Control Loop is in FINAL state, do not call this method."); + } + // + // Not final so get the policy that needs to be worked on. + // + Policy policy = this.processor.getCurrentPolicy(); + if (policy == null) { + throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy."); + } + // + // And setup an operation + // + this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this); + // + // Return it + // + return this.currentOperation; + } + + public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException { + // + // Verify we have a current operation + // + if (this.currentOperation != null) { + // + // Validate they are finishing the current operation + // PLD - this is simply comparing the policy. Do we want to equals the whole object? + // + if (this.currentOperation.policy.equals(operation.policy)) { + System.out.println("Finishing " + this.currentOperation.policy.recipe + " result is " + this.currentOperation.getOperationResult()); + // + // Save history + // + this.controlLoopHistory.addAll(this.currentOperation.getHistory()); + // + // Move to the next Policy + // + this.processor.nextPolicyForResult(this.currentOperation.getOperationResult()); + // + // Just null this out + // + this.currentOperation = null; + // + // TODO: Release our lock + // + return; + } + System.out.println("Cannot finish current operation " + this.currentOperation.policy + " does not match given operation " + operation.policy); + return; + } + throw new ControlLoopException("No operation to finish."); + } + + public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException { + // + // Sanity check + // + if (this.currentOperation == null) { + throw new ControlLoopException("Do not have a current operation."); + } + // + // Have we acquired it already? + // + if (this.targetLock != null) { + // + // TODO: Make sure the current lock is for the same target. + // Currently, it should be. But in the future it may not. + // + return new LockResult<GuardResult, TargetLock>(GuardResult.LOCK_ACQUIRED, this.targetLock); + } else { + // + // Ask the Guard + // + LockResult<GuardResult, TargetLock> lockResult = PolicyGuard.lockTarget( + this.currentOperation.policy.target.type, + this.getTargetInstance(this.currentOperation.policy), + this.onset.requestID, + this); + // + // Was it acquired? + // + if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) { + // + // Yes, let's save it + // + this.targetLock = lockResult.getB(); + } + return lockResult; + } + } + + public synchronized TargetLock unlockCurrentOperation() { + if (this.targetLock == null) { + return null; + } + if (PolicyGuard.unlockTarget(this.targetLock) == true) { + TargetLock returnLock = this.targetLock; + this.targetLock = null; + return returnLock; + } + return null; + } + + public enum NEW_EVENT_STATUS { + FIRST_ONSET, + SUBSEQUENT_ONSET, + FIRST_ABATEMENT, + SUBSEQUENT_ABATEMENT, + SYNTAX_ERROR + ; + } + + public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) { + try { + ControlLoopEventManager.checkEventSyntax(event); + if (event.closedLoopEventStatus == ControlLoopEventStatus.ONSET) { + // + // Check if this is our original ONSET + // + if (event.equals(this.onset)) { + // + // DO NOT retract it + // + return NEW_EVENT_STATUS.FIRST_ONSET; + } + // + // Log that we got an onset + // + this.numOnsets++; + return NEW_EVENT_STATUS.SUBSEQUENT_ONSET; + } else if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) { + // + // Have we already got an abatement? + // + if (this.abatement == null) { + // + // Save this + // + this.abatement = event; + // + // Keep track that we received another + // + this.numAbatements++; + // + // + // + return NEW_EVENT_STATUS.FIRST_ABATEMENT; + } else { + // + // Keep track that we received another + // + this.numAbatements++; + // + // + // + return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT; + } + } else { + return NEW_EVENT_STATUS.SYNTAX_ERROR; + } + } catch (ControlLoopException e) { + return NEW_EVENT_STATUS.SYNTAX_ERROR; + } + } + + public VirtualControlLoopNotification setControlLoopTimedOut() { + this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT; + VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Control Loop timed out"; + notification.history.addAll(this.controlLoopHistory); + return notification; + } + + public boolean isControlLoopTimedOut() { + return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT); + } + + public int getControlLoopTimeout(Integer defaultTimeout) { + if (this.processor != null && this.processor.getControlLoop() != null) { + return this.processor.getControlLoop().timeout; + } + if (defaultTimeout != null) { + return defaultTimeout; + } + return 0; + } + + public static void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { + if (event.closedLoopEventStatus == null || + (event.closedLoopEventStatus != ControlLoopEventStatus.ONSET && + event.closedLoopEventStatus != ControlLoopEventStatus.ABATED)) { + throw new ControlLoopException("Invalid value in closedLoopEventStatus"); + } + if (event.closedLoopControlName == null || event.closedLoopControlName.length() < 1) { + throw new ControlLoopException("No control loop name"); + } + if (event.requestID == null) { + throw new ControlLoopException("No request ID"); + } + if (event.AAI == null) { + throw new ControlLoopException("AAI is null"); + } + if (event.AAI.get("vserver.is-closed-loop-disabled") == null) { + throw new ControlLoopException("vserver.is-closed-loop-disabled information missing"); + } + if (event.AAI.get("vserver.is-closed-loop-disabled").equalsIgnoreCase("true") || + event.AAI.get("vserver.is-closed-loop-disabled").equalsIgnoreCase("T") || + event.AAI.get("vserver.is-closed-loop-disabled").equalsIgnoreCase("yes") || + event.AAI.get("vserver.is-closed-loop-disabled").equalsIgnoreCase("Y")) { + throw new ControlLoopException("vserver.is-closed-loop-disabled is set to true"); + } + if (event.target == null || event.target.length() < 1) { + throw new ControlLoopException("No target field"); + } else { + if (! event.target.equalsIgnoreCase("VM_NAME") && + ! event.target.equalsIgnoreCase("VNF_NAME") && + ! event.target.equalsIgnoreCase("vserver.vserver-name") && + ! event.target.equalsIgnoreCase("generic-vnf.vnf-name") ) { + throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); + } + } + } + + @Override + public boolean isActive() { + // TODO + return true; + } + + @Override + public boolean releaseLock() { + // TODO + return false; + } + + public String getTargetInstance(Policy policy) { + if (policy.target != null) { + if (policy.target.type != null) { + switch(policy.target.type) { + case PNF: + break; + case VM: + if (this.onset.target.equalsIgnoreCase("vserver.vserver-name")) { + return this.onset.AAI.get("vserver.vserver-name"); + } + break; + default: + break; + } + } + } + return null; + } + + @Override + public String toString() { + return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID + + ", processor=" + processor + ", onset=" + (onset != null ? onset.requestID : "null") + ", numOnsets=" + numOnsets + ", numAbatements=" + + numAbatements + ", isActivated=" + + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]"; + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java new file mode 100644 index 000000000..81c85b1e8 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java @@ -0,0 +1,520 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop operation manager + * ================================================================================ + * 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.eventmanager; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.LinkedList; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; + +import org.onap.policy.controlloop.ControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.VirtualControlLoopEvent; + +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider; + + +public class ControlLoopOperationManager implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3773199283624595410L; + + @Override + public String toString() { + return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy=" + + (policy != null ? policy.id : "null") + ", attempts=" + attempts + + ", policyResult=" + policyResult + + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory + + "]"; + } + + // + // These properties are not changeable, but accessible + // for Drools Rule statements. + // + //public final ATTControlLoopEvent onset; + public final ControlLoopEvent onset; + public final Policy policy; + + // + // Properties used to track the Operation + // + private int attempts = 0; + private Operation currentOperation = null; + private LinkedList<Operation> operationHistory = new LinkedList<Operation>(); + private PolicyResult policyResult = null; + private ControlLoopEventManager eventManager = null; + + public ControlLoopEventManager getEventManager() { + return eventManager; + } + + public void setEventManager(ControlLoopEventManager eventManager) { + this.eventManager = eventManager; + } + + + // + // Internal class used for tracking + // + private class Operation { + public ControlLoopOperation operation = new ControlLoopOperation(); + public PolicyResult policyResult = null; + public int attempt = 0; + + @Override + public String toString() { + return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation + + "]"; + } + } + + private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY" + private Object operationRequest; + + public Object getOperationRequest() { + return operationRequest; + } + + public String getGuardApprovalStatus() { + return guardApprovalStatus; + } + public void setGuardApprovalStatus(String guardApprovalStatus) { + this.guardApprovalStatus = guardApprovalStatus; + } + + + public ControlLoopOperationManager(/*ATTControlLoopEvent*/ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException { + this.onset = onset; + this.policy = policy; + this.guardApprovalStatus = "NONE"; + this.eventManager = em; + + // + // Let's make a sanity check + // + switch (policy.actor) { + case "APPC": + break; + case "AOTS": + break; + case "MSO": + break; + case "SDNO": + break; + case "SDNR": + break; + default: + throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor."); + } + } + + public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) { + // + // They shouldn't call us if we currently running something + // + if (this.currentOperation != null) { + // + // what do we do if we are already running an operation? + // + return null; + } + // + // Check if we have maxed out on retries + // + if (this.policy.retry == null || this.policy.retry < 1) { + // + // No retries are allowed, so check have we even made + // one attempt to execute the operation? + // + if (this.attempts >= 1) { + // + // We have, let's ensure our PolicyResult is set + // + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + // + // + // + return null; + } + } else { + // + // Have we maxed out on retries? + // + if (this.attempts > this.policy.retry) { + if (this.policyResult == null) { + this.policyResult = PolicyResult.FAILURE_RETRIES; + } + return null; + } + } + // + // Setup + // + this.policyResult = null; + Operation operation = new Operation(); + operation.attempt = ++this.attempts; + operation.operation.actor = this.policy.actor.toString(); + operation.operation.operation = this.policy.recipe; + operation.operation.target = this.policy.target.toString(); + operation.operation.subRequestId = Integer.toString(operation.attempt); + // + // Now determine which actor we need to construct a request for + // + switch (policy.actor) { + case "APPC": + //Request request = APPCActorServiceProvider.constructRequest(onset, operation.operation, this.policy); + this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy); + // + // Save the operation + // + this.currentOperation = operation; + //System.out.print("************* BEFORE STORING....."); + //this.storeOperationInDataBase("startOperation"); + //System.out.print("************* AFTER STORING....."); + // + return operationRequest; + case "MSO": + // + // We are not supporting MSO interface at the moment + // + System.out.println("We are not supporting MSO actor in the latest release."); + return null; + } + return null; + } + + public PolicyResult onResponse(Object response) { + // + // Which response is it? + // + if (response instanceof Response) { + // + // Cast it + // + Response appcResponse = (Response) response; + // + // Determine which subrequestID (ie. attempt) + // + Integer operationAttempt = null; + try { + operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID); + } catch (NumberFormatException e) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Sanity check the response message + // + if (appcResponse.Status == null) { + // + // We cannot tell what happened if this doesn't exist + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code); + if (code == null) { + // + // We are unaware of this code + // + this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; + } + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + // + // This is good, they got our original message and + // acknowledged it. + // + // Is there any need to track this? + // + return null; + case ERROR: + case REJECT: + // + // We'll consider these two codes as exceptions + // + this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE_EXCEPTION; + case SUCCESS: + // + // + // + this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.SUCCESS; + case FAILURE: + // + // + // + this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE); + if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + return null; + } + return PolicyResult.FAILURE; + } + } + return null; + } + + public Integer getOperationTimeout() { + // + // Sanity check + // + if (this.policy == null) { + System.out.println("getOperationTimeout returning 0"); + return 0; + } + System.out.println("getOperationTimeout returning " + this.policy.timeout); + return this.policy.timeout; + } + + public String getOperationTimeoutString(int defaultTimeout) { + Integer to = this.getOperationTimeout(); + if (to == null || to == 0) { + return Integer.toString(defaultTimeout) + "s"; + } + return to.toString() + "s"; + } + + public PolicyResult getOperationResult() { + return this.policyResult; + } + + public String getOperationMessage() { + if (this.currentOperation != null && this.currentOperation.operation != null) { + return this.currentOperation.operation.toMessage(); + } + if (this.operationHistory != null && this.operationHistory.size() > 0) { + return this.operationHistory.getLast().operation.toMessage(); + } + return null; + } + + public String getOperationMessage(String guardResult) { + if (this.currentOperation != null && this.currentOperation.operation != null) { + return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult; + } + if (this.operationHistory != null && this.operationHistory.size() > 0) { + return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult; + } + return null; + } + + public String getOperationHistory() { + if (this.currentOperation != null && this.currentOperation.operation != null) { + return this.currentOperation.operation.toHistory(); + } + if (this.operationHistory != null && this.operationHistory.size() > 0) { + return this.operationHistory.getLast().operation.toHistory(); + } + return null; + } + + public LinkedList<ControlLoopOperation> getHistory() { + LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>(); + for (Operation op : this.operationHistory) { + history.add(new ControlLoopOperation(op.operation)); + + } + return history; + } + + public void setOperationHasTimedOut() { + // + // + // + this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT); + } + + public void setOperationHasGuardDeny() { + // + // + // + this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD); + } + + public boolean isOperationComplete() { + // + // Is there currently a result? + // + if (this.policyResult == null) { + // + // either we are in process or we + // haven't started + // + return false; + } + // + // We have some result, check if the operation failed + // + if (this.policyResult.equals(PolicyResult.FAILURE)) { + // + // Check if there were no retries specified + // + if (policy.retry == null || policy.retry == 0) { + // + // The result is the failure + // + return true; + } + // + // Check retries + // + if (this.isRetriesMaxedOut()) { + // + // No more attempts allowed, reset + // that our actual result is failure due to retries + // + this.policyResult = PolicyResult.FAILURE_RETRIES; + return true; + } else { + // + // There are more attempts available to try the + // policy recipe. + // + return false; + } + } + // + // Other results mean we are done + // + return true; + } + + public boolean isOperationRunning() { + return (this.currentOperation != null); + } + + private boolean isRetriesMaxedOut() { + if (policy.retry == null || policy.retry == 0) { + // + // There were NO retries specified, so declare + // this as completed. + // + return (this.attempts > 0); + } + return (this.attempts > policy.retry); + } + + private void storeOperationInDataBase(){ + + EntityManager em; + try{ + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + }catch(Exception e){ + System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB."); + return; + } + + OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry(); + + newEntry.closedLoopName = this.onset.closedLoopControlName; + newEntry.requestId = this.onset.requestID.toString(); + newEntry.actor = this.currentOperation.operation.actor; + newEntry.operation = this.currentOperation.operation.operation; + newEntry.target = this.eventManager.getTargetInstance(this.policy); + newEntry.starttime = Timestamp.from(this.currentOperation.operation.start); + newEntry.subrequestId = this.currentOperation.operation.subRequestId; + newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli()); + newEntry.message = this.currentOperation.operation.message; + newEntry.outcome = this.currentOperation.operation.outcome; + + em.getTransaction().begin(); + em.persist(newEntry); + em.getTransaction().commit(); + + em.close(); + + } + + + + private void completeOperation(Integer attempt, String message, PolicyResult result) { + if (attempt == null) { + System.out.println("attempt cannot be null (i.e. subRequestID)"); + return; + } + if (this.currentOperation != null) { + if (this.currentOperation.attempt == attempt.intValue()) { + this.currentOperation.operation.end = Instant.now(); + this.currentOperation.operation.message = message; + this.currentOperation.operation.outcome = result.toString(); + this.currentOperation.policyResult = result; + // + // Save it in history + // + this.operationHistory.add(this.currentOperation); + this.storeOperationInDataBase(); + // + // Set our last result + // + this.policyResult = result; + // + // Clear the current operation field + // + this.currentOperation = null; + return; + } + System.out.println("not current"); + } + for (Operation op : this.operationHistory) { + if (op.attempt == attempt.intValue()) { + op.operation.end = Instant.now(); + op.operation.message = message; + op.operation.outcome = result.toString(); + op.policyResult = result; + return; + } + } + System.out.println("Could not find associated operation"); + + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java new file mode 100644 index 000000000..82775053e --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/OperationsHistoryDbEntry.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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.eventmanager; + +import java.io.Serializable; +import java.sql.Timestamp; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity +@Table(name="operationshistory10") +public class OperationsHistoryDbEntry implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id@GeneratedValue + @Column(name="ROWID") + public long rowid; + + @Column(name="CLNAME") + public String closedLoopName; + + public String requestId; + + public String actor; + + public String operation; + + public String target; + + public Timestamp starttime; + + public Timestamp endtime; + + public String subrequestId; + + public String outcome; + + public String message; + +} + + diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java new file mode 100644 index 000000000..acf7f1d22 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopLoggerStdOutImpl.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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.impl; + +import org.onap.policy.controlloop.ControlLoopLogger; + +public class ControlLoopLoggerStdOutImpl implements ControlLoopLogger { + + public ControlLoopLoggerStdOutImpl() { + } + + @Override + public void info(String... parameters) { + StringBuilder builder = new StringBuilder(); + for (String param : parameters) { + builder.append(param); + builder.append(" " ); + } + System.out.println(builder.toString().trim()); + } + + @Override + public void metrics(String... msgs) { + this.info(msgs); + } + + @Override + public void metrics(Object obj) { + this.info(obj.toString()); + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java new file mode 100644 index 000000000..37721a9a1 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/impl/ControlLoopPublisherJUnitImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop + * ================================================================================ + * 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.impl; + +import org.onap.policy.controlloop.ControlLoopPublisher; + +public class ControlLoopPublisherJUnitImpl implements ControlLoopPublisher { + + public ControlLoopPublisherJUnitImpl() { + + } + + @Override + public void publish(Object object) { + + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java new file mode 100644 index 000000000..bc94068ab --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/processor/ControlLoopProcessor.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * controlloop processor + * ================================================================================ + * 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 org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; + +public class ControlLoopProcessor { + + private final String yaml; + private final ControlLoopPolicy policy; + private String currentPolicy = null; + + public ControlLoopProcessor(String yaml) throws ControlLoopException { + this.yaml = yaml; + try { + Yaml y = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = y.load(this.yaml); + if (obj instanceof ControlLoopPolicy) { + this.policy = (ControlLoopPolicy) obj; + this.currentPolicy = this.policy.controlLoop.trigger_policy; + } else { + this.policy = null; + throw new ControlLoopException("Unable to parse yaml into ControlLoopPolicy object"); + } + } catch (Exception e) { + // + // Most likely this is a YAML Exception + // + throw new ControlLoopException(e); + } + } + + public ControlLoop getControlLoop() { + return this.policy.controlLoop; + } + + public FinalResult checkIsCurrentPolicyFinal() { + return FinalResult.toResult(this.currentPolicy); + } + + public Policy getCurrentPolicy() { + for (Policy policy : this.policy.policies) { + if (policy.id.equals(this.currentPolicy)) { + return policy; + } + } + return null; + } + + public void nextPolicyForResult(PolicyResult result) throws ControlLoopException { + Policy policy = this.getCurrentPolicy(); + try { + if (this.policy == null) { + throw new ControlLoopException("There is no current policy to determine where to go to."); + } + switch (result) { + case SUCCESS: + this.currentPolicy = policy.success; + break; + case FAILURE: + this.currentPolicy = policy.failure; + break; + case FAILURE_TIMEOUT: + this.currentPolicy = policy.failure_timeout; + break; + case FAILURE_RETRIES: + this.currentPolicy = policy.failure_retries; + break; + case FAILURE_EXCEPTION: + this.currentPolicy = policy.failure_exception; + break; + case FAILURE_GUARD: + this.currentPolicy = policy.failure_guard; + break; + default: + throw new ControlLoopException("Bad policy result given: " + result); + } + } catch (ControlLoopException e) { + this.currentPolicy = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + throw e; + } + } + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java new file mode 100644 index 000000000..07a273cc7 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * policy engine + * ================================================================================ + * 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.drools; + +public interface PolicyEngine { + + public boolean deliver(String busType, String topic, Object obj); + +} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java new file mode 100644 index 000000000..5c019c487 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * policy engine + * ================================================================================ + * 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.drools.impl; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; + +import org.onap.policy.appc.Request; +import org.onap.policy.controlloop.ControlLoopNotification; +import org.onap.policy.controlloop.util.Serialization; + +import org.onap.policy.drools.PolicyEngine; + +public class PolicyEngineJUnitImpl implements PolicyEngine { + + private Map<String, Map<String, Queue<Object>>> busMap = new HashMap<String, Map<String, Queue<Object>>>(); + + @Override + public boolean deliver(String busType, String topic, Object obj) { + if (obj instanceof ControlLoopNotification) { + ControlLoopNotification notification = (ControlLoopNotification) obj; + //System.out.println("Notification: " + notification.notification + " " + (notification.message == null ? "" : notification.message) + " " + notification.history); + System.out.println(Serialization.gsonPretty.toJson(notification)); + } + if (obj instanceof Request) { + Request request = (Request) obj; + System.out.println("Request: " + request.Action + " subrequest " + request.CommonHeader.SubRequestID); + } + // + // Does the bus exist? + // + if (busMap.containsKey(busType) == false) { + System.out.println("creating new bus type " + busType); + // + // Create the bus + // + busMap.put(busType, new HashMap<String, Queue<Object>>()); + } + // + // Get the bus + // + Map<String, Queue<Object>> topicMap = busMap.get(busType); + // + // Does the topic exist? + // + if (topicMap.containsKey(topic) == false) { + System.out.println("creating new topic " + topic); + // + // Create the topic + // + topicMap.put(topic, new LinkedList<Object>()); + } + // + // Get the topic queue + // + System.out.println("queueing"); + return topicMap.get(topic).add(obj); + } + + public Object subscribe(String busType, String topic) { + // + // Does the bus exist? + // + if (busMap.containsKey(busType)) { + // + // Get the bus + // + Map<String, Queue<Object>> topicMap = busMap.get(busType); + // + // Does the topic exist? + // + if (topicMap.containsKey(topic)) { + System.out.println("The queue has " + topicMap.get(topic).size()); + return topicMap.get(topic).poll(); + } else { + System.err.println("No topic exists " + topic); + } + } else { + System.err.println("No bus exists " + busType); + } + return null; + } + +} diff --git a/controlloop/common/eventmanager/src/main/resources/META-INF/persistence.xml b/controlloop/common/eventmanager/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..e3c4ef946 --- /dev/null +++ b/controlloop/common/eventmanager/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<persistence xmlns="http://java.sun.com/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence + http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> + + <persistence-unit name="OperationsHistoryPU" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <!-- <jar-file>packedEntity.jar</jar-file>--> + <class>org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry</class> + <properties> + <property name="eclipselink.ddl-generation" value="create-tables"/> + <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> + <!-- <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:7779/policy"/>--> + <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://135.207.129.112:3306/policy"/> + <property name="javax.persistence.jdbc.user" value="root"/> + <property name="javax.persistence.jdbc.password" value="lmpg"/> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> + +</persistence>
\ No newline at end of file diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java new file mode 100644 index 000000000..bf44a8026 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/Util.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * util + * ================================================================================ + * 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; + +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; + +public final class Util { + + public static class Pair<A, B> { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java new file mode 100644 index 000000000..fa52e8557 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.eventmanager; + + +import org.junit.Test; + +public class ControlLoopEventManagerTest { + + @Test + public void test() { + //fail("MICHAEL - Not yet implemented"); + } + +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java new file mode 100644 index 000000000..1cb8b5a5d --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.eventmanager; + +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.time.Instant; +import java.util.HashMap; +import java.util.UUID; + +import org.junit.Test; +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.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.Util; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.processor.ControlLoopProcessor; + +public class ControlLoopOperationManagerTest { + + private static VirtualControlLoopEvent onset; + static { + onset = new VirtualControlLoopEvent(); + onset.requestID = UUID.randomUUID(); + onset.target = "vserver.selflink"; + onset.closedLoopAlarmStart = Instant.now(); + onset.AAI = new HashMap<String, String>(); + onset.AAI.put("cloud-region.identity-url", "foo"); + onset.AAI.put("vserver.selflink", "bar"); + onset.AAI.put("vserver.is-closed-loop-disabled", "false"); + onset.AAI.put("generic-vnf.vnf-name", "testTriggerSource"); + onset.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + } + + @Test + public void testRetriesFail() { + // + // Load up the policy + // + final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.closedLoopControlName = pair.a.controlLoop.controlLoopName; + try { + // + // Create a processor + // + ControlLoopProcessor processor = new ControlLoopProcessor(pair.b); + // + // create the manager + // + ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.closedLoopControlName, onset.requestID); + + ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + System.out.println(manager); + // + // + // + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + System.out.println(manager); + assertNotNull(request); + assertTrue(request instanceof Request); + assertTrue(((Request)request).CommonHeader.SubRequestID.contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + Response response = new Response((Request) request); + response.Status.Code = ResponseCode.ACCEPT.getValue(); + response.Status.Value = ResponseValue.ACCEPT.toString(); + // + // + // + PolicyResult result = manager.onResponse(response); + System.out.println(manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + response = new Response((Request) request); + response.Status.Code = ResponseCode.FAILURE.getValue(); + response.Status.Value = ResponseValue.FAILURE.toString(); + response.Status.Description = "AppC failed for some reason"; + result = manager.onResponse(response); + System.out.println(manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Retry it + // + request = manager.startOperation(onset); + System.out.println(manager); + assertNotNull(request); + assertTrue(request instanceof Request); + assertTrue(((Request)request).CommonHeader.SubRequestID.contentEquals("2")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // + // + response = new Response((Request) request); + System.out.println(manager); + response.Status.Code = ResponseCode.ACCEPT.getValue(); + response.Status.Value = ResponseValue.ACCEPT.toString(); + // + // + // + result = manager.onResponse(response); + System.out.println(manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + response = new Response((Request) request); + response.Status.Code = ResponseCode.FAILURE.getValue(); + response.Status.Value = ResponseValue.FAILURE.toString(); + response.Status.Description = "AppC failed for some reason"; + result = manager.onResponse(response); + System.out.println(manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + // + // Should be complete now + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertNotNull(manager.getOperationResult()); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES)); + assertTrue(manager.getHistory().size() == 2); + } catch (ControlLoopException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTimeout() { + // + // Load up the policy + // + final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml("src/test/resources/test.yaml"); + onset.closedLoopControlName = pair.a.controlLoop.controlLoopName; + try { + // + // Create a processor + // + ControlLoopProcessor processor = new ControlLoopProcessor(pair.b); + // + // create the manager + // + ControlLoopEventManager eventManager = new ControlLoopEventManager(onset.closedLoopControlName, onset.requestID); + + ControlLoopOperationManager manager = new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + // + // + // + System.out.println(manager); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + System.out.println(manager); + assertNotNull(request); + assertTrue(request instanceof Request); + assertTrue(((Request)request).CommonHeader.SubRequestID.contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + Response response = new Response((Request) request); + response.Status.Code = ResponseCode.ACCEPT.getValue(); + response.Status.Value = ResponseValue.ACCEPT.toString(); + // + // + // + PolicyResult result = manager.onResponse(response); + System.out.println(manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to simulate Timeout + // + manager.setOperationHasTimedOut(); + System.out.println(manager); + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); + // + // Now we are going to Fail the previous request + // + response = new Response((Request) request); + response.Status.Code = ResponseCode.FAILURE.getValue(); + response.Status.Value = ResponseValue.FAILURE.toString(); + response.Status.Description = "AppC failed for some reason"; + result = manager.onResponse(response); + System.out.println(manager); + // + // + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); + } catch (ControlLoopException e) { + fail(e.getMessage()); + } + } + +} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java new file mode 100644 index 000000000..2ed216658 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.processor; + +import static org.junit.Assert.*; + +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.junit.Test; + +import org.onap.policy.controlloop.ControlLoopException; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; + +public class ControlLoopProcessorTest { + + @Test + public void test() { + try (InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"))) { + String result = IOUtils.toString(is, StandardCharsets.UTF_8); + this.testSuccess(result); + this.testFailure(result); + } catch (FileNotFoundException e) { + e.printStackTrace(); + fail(e.getMessage()); + } catch (IOException e) { + e.printStackTrace(); + fail(e.getMessage()); + } catch (ControlLoopException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + public void testSuccess(String yaml) throws ControlLoopException { + ControlLoopProcessor processor = new ControlLoopProcessor(yaml); + System.out.println("testSuccess: " + processor.getControlLoop().toString()); + while (true) { + FinalResult result = processor.checkIsCurrentPolicyFinal(); + if (result != null) { + System.out.println(result); + break; + } + Policy policy = processor.getCurrentPolicy(); + assertNotNull(policy); + System.out.println("current policy is: " + policy.id + " " + policy.name); + processor.nextPolicyForResult(PolicyResult.SUCCESS); + } + } + + public void testFailure(String yaml) throws ControlLoopException { + ControlLoopProcessor processor = new ControlLoopProcessor(yaml); + System.out.println("testFailure: " + processor.getControlLoop().toString()); + while (true) { + FinalResult result = processor.checkIsCurrentPolicyFinal(); + if (result != null) { + System.out.println(result); + break; + } + Policy policy = processor.getCurrentPolicy(); + assertNotNull(policy); + System.out.println("current policy is: " + policy.id + " " + policy.name); + processor.nextPolicyForResult(PolicyResult.FAILURE); + } + } + +} diff --git a/controlloop/common/eventmanager/src/test/resources/test.yaml b/controlloop/common/eventmanager/src/test/resources/test.yaml new file mode 100644 index 000000000..1295a9924 --- /dev/null +++ b/controlloop/common/eventmanager/src/test/resources/test.yaml @@ -0,0 +1,61 @@ +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 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 1 + 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_exception: final_failure_exception + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: 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_exception: final_failure_exception + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 30 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/guard/README.md b/controlloop/common/guard/README.md new file mode 100644 index 000000000..ba8593462 --- /dev/null +++ b/controlloop/common/guard/README.md @@ -0,0 +1,2 @@ +ECOMP Policy Guard Implementation + diff --git a/controlloop/common/guard/pom.xml b/controlloop/common/guard/pom.xml new file mode 100644 index 000000000..388a233ea --- /dev/null +++ b/controlloop/common/guard/pom.xml @@ -0,0 +1,67 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>guard</artifactId> + <dependencies> + +<!-- + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> +--> + + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>policy-yaml</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.att.research.xacml</groupId> + <artifactId>xacml</artifactId> + <version>1.0.0</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.att.research.xacml</groupId> + <artifactId>xacml-pdp</artifactId> + <version>1.0.0</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.4</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.2</version> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-core</artifactId> + <version>6.3.0.Final</version> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>org.eclipse.persistence.jpa</artifactId> + <version>2.6.4</version> + </dependency> + + + </dependencies> +</project> diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java new file mode 100644 index 000000000..af81a3610 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.policy.guard; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.annotations.RequestParser; +import java.util.UUID; + +import org.drools.core.WorkingMemory; + + +public class CallGuardTask implements Runnable { + + WorkingMemory workingMemory; + PDPEngine embeddedPdpEngine; + String restfulPdpUrl; + String actor; + String recipe; + String target; + String requestId; + + public CallGuardTask(PDPEngine engine, String url, WorkingMemory wm, String act, String rec, String tar, String reqId) { + + embeddedPdpEngine = engine; + restfulPdpUrl = url; + workingMemory = wm; + actor = act; + recipe = rec; + requestId = reqId; + target = tar; + } + public void run() { + long startTime = System.nanoTime(); + com.att.research.xacml.api.Request request = null; + + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes(actor, recipe, target, requestId); + + try { + request = RequestParser.parseRequest(xacmlReq); + } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /* + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + */ + + System.out.println("\n********** XACML REQUEST START ********"); + System.out.println(request); + System.out.println("********** XACML REQUEST END ********\n"); + + com.att.research.xacml.api.Response xacmlResponse = PolicyGuardXacmlHelper.callPDP(embeddedPdpEngine, "", request, false); + + System.out.println("\n********** XACML RESPONSE START ********"); + System.out.println(xacmlResponse); + System.out.println("********** XACML RESPONSE END ********\n"); + + PolicyGuardResponse guardResponse = PolicyGuardXacmlHelper.ParseXacmlPdpResponse(xacmlResponse); + + // + //Create an artificial Guard response in case we didn't get a clear Permit or Deny + // + if(guardResponse.result.equals("Indeterminate")){ + guardResponse.operation = recipe; + guardResponse.requestID = UUID.fromString(requestId); + } + + long estimatedTime = System.nanoTime() - startTime; + System.out.println("\n\n============ Guard inserted with decision "+ guardResponse.result + " !!! =========== time took: " +(double)estimatedTime/1000/1000 +" mili sec \n\n"); + workingMemory.insert(guardResponse); + + } + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java new file mode 100644 index 000000000..4afd16dab --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +public enum GuardResult { + LOCK_ACQUIRED, + LOCK_DENIED, + LOCK_EXCEPTION + ; + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java new file mode 100644 index 000000000..0a1255d33 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/LockCallback.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +public interface LockCallback { + + public boolean isActive(); + + public boolean releaseLock(); + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java new file mode 100644 index 000000000..99775dc3d --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java @@ -0,0 +1,352 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.math.BigInteger; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.datatypes.DataTypes; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + + +public class PIPEngineGetHistory extends StdConfigurableEngine{ + + private Log logger = LogFactory.getLog(this.getClass()); + + //private static EntityManager em; + + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + + // + // Base issuer string. The issuer in the policy will also contain time window information + // E.g., "com:att:research:xacml:guard:historydb:tw:10:min" + // + public static final String DEFAULT_ISSUER = "com:att:research:xacml:guard:historydb"; + + + private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:actor:actor-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:action"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:operation:operation-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), + new IdentifierImpl("urn:oasis:names:tc:xacml:1.0:target:target-id"), + new IdentifierImpl("http://www.w3.org/2001/XMLSchema#string")); + + + private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { + AttributeValue<BigInteger> attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); + } + } + + + + public PIPEngineGetHistory() { + super(); + + System.out.println("HAHAHAHAHAHAHAHAHAHAHAHAHAHAHA"); + + // TODO Auto-generated constructor stub + } + + + + @Override + public Collection<PIPRequest> attributesRequired() { + // TODO Auto-generated method stub + System.out.println("DADADADADADADADADADADADADA"); + return null; + } + + @Override + public Collection<PIPRequest> attributesProvided() { + // TODO Auto-generated method stub + System.out.println("GAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAG"); + return null; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + // TODO Auto-generated method stub + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Entering FeqLimiter PIP!!!"); + + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + this.logger.debug("No issuer in the request..."); + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - No issuer in the request!!!"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + else{ + //Notice, we are checking here for the base issuer prefix. + if (!string.contains(this.getIssuer())) { + this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer()); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + } + + String[] s1 = string.split("tw:"); + String[] s2 = s1[1].split(":"); + String timeWindowVal = s2[0];// number [of minutes, hours, days...] + String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year + + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - Issuer " + string + " is OK - proceeding with the request!!!"); + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - FeqLimiter PIP - TimeWindow: " + timeWindowVal + " " + timeWindowScale); + + String actor = getActor(pipFinder).iterator().next(); + String operation = getRecipe(pipFinder).iterator().next(); + String target = getTarget(pipFinder).iterator().next(); + + String timeWindow = timeWindowVal + " " + timeWindowScale; + + System.out.println("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow); + int countFromDB = getCountFromDB(actor, operation, target, timeWindow); + + + StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); + + this.addIntegerAttribute(stdPIPResponse, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"), + new IdentifierImpl("com:att:research:xacml:test:sql:resource:operations:count"), + countFromDB, + pipRequest); + + return new StdPIPResponse(stdPIPResponse); + } + + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + //System.out.println("MAMAMAMAMAMAMAMAMAMAMAMAMA - Configuring FeqLimiter PIP!!!"); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + /* + try{ + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + }catch(Exception e){ + System.err.println("Freq limiter PIP got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB."); + return; + } + */ + + } + + + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + System.out.println("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse.getAttributes().size() == 0) { + System.out.println("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + System.out.println("PIPException getting subject-id attribute: " + ex.getMessage()); + } + return pipResponse; + } + + + private Set<String> getActor(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); + if (pipResponseATTUID == null) { + return null; + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); + Set<String> setATTUIDs = new HashSet<String>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + + return setATTUIDs; + } + + private Set<String> getRecipe(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); + if (pipResponseATTUID == null) { + return null; + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); + Set<String> setATTUIDs = new HashSet<String>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + + return setATTUIDs; + } + + + private Set<String> getTarget(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); + if (pipResponseATTUID == null) { + return null; + } + + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection<Attribute> listATTUIDs = pipResponseATTUID.getAttributes(); + Set<String> setATTUIDs = new HashSet<String>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator<AttributeValue<String>> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + + return setATTUIDs; + } + + private static int getCountFromDB(String actor, String operation, String target, String timeWindow){ + + long startTime = System.nanoTime(); + + + + EntityManager em; + try{ + em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager(); + }catch(Exception e){ + System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB."); + return -1; + } + + + //em.getTransaction().begin(); + String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor='" + + actor + + "' and operation='" + + operation + + "' and target='" + + target + + "' " + + "and endtime between date_sub(now(),interval " + + timeWindow + + ") and now()"; + + Query nq = em.createNativeQuery(sql); + + int ret = ((Number)nq.getSingleResult()).intValue(); + + System.out.println("###########************** History count: " + ret); + + //em.getTransaction().commit(); + long estimatedTime = System.nanoTime() - startTime; + System.out.println("time took: " + (double)estimatedTime/1000/1000 + " mili sec."); + + em.close(); + + return ret; + + + + } + + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java new file mode 100644 index 000000000..b4aee2fda --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuard.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.guard; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.impl.PNFTargetLock; +import org.onap.policy.guard.impl.VMTargetLock; + +public class PolicyGuard { + + private static Map<String, TargetLock> activeLocks = new HashMap<String, TargetLock>(); + + public static class LockResult<A, B> { + private A a; + private B b; + + public static <A, B> LockResult<A, B> createLockResult(A a, B b) { + return new LockResult<A, B>(a, b); + } + + public LockResult(A a, B b) { + this.a = a; + this.b = b; + } + + public A getA() { + return a; + } + + public B getB() { + return b; + } + } + + public static LockResult<GuardResult, TargetLock> lockTarget(TargetType targetType, String targetInstance, UUID requestID, LockCallback callback) { + + synchronized(activeLocks) { + // + // Is there a lock on this instance already? + // + if (activeLocks.containsKey(targetInstance)) { + return LockResult.createLockResult(GuardResult.LOCK_DENIED, null); + } + TargetLock lock = null; + switch (targetType) { + case PNF: + // + // Create the Lock object + // + lock = new PNFTargetLock(targetType, targetInstance, requestID, callback); + break; + case VM: + // + // Create the Lock object + // + lock = new VMTargetLock(targetType, targetInstance, requestID, callback); + break; + default: + return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null); + } + // + // Keep track of it + // + activeLocks.put(targetInstance, lock); + // + // Return result + // + System.out.println("Locking " + lock); + return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock); + } + } + + public static boolean unlockTarget(TargetLock lock) { + synchronized(activeLocks) { + if (activeLocks.containsKey(lock.getTargetInstance())) { + System.out.println("Unlocking " + lock); + return (activeLocks.remove(lock.getTargetInstance()) != null); + } + return false; + } + } + + public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) { + synchronized(activeLocks) { + if (activeLocks.containsKey(targetInstance)) { + TargetLock lock = activeLocks.get(targetInstance); + return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID)); + } + return false; + } + } + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java new file mode 100644 index 000000000..04732dc36 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardRequest{ + + public PolicyGuardRequest(String actor, String target, UUID requestID, String operation) { + super(); + this.actor = actor; + this.target = target; + this.requestID = requestID; + this.operation = operation; + } + public String actor; + public String target; + public UUID requestID; + public String operation; + + + @Override + public String toString() { + return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestID=" + requestID + ", operation=" + + operation + "]"; + } + +}
\ No newline at end of file diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java new file mode 100644 index 000000000..20bbc2eb6 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardResponse{ + public PolicyGuardResponse(String string, UUID req, String op) { + this.result = string; + this.requestID = req; + this.operation = op; + } + public UUID requestID; + public String operation; + public String result; + + + + + + @Override + public String toString() { + return "PolicyGuardResponse [requestID=" + requestID + ", operation=" + operation + ", result=" + result + "]"; + } + public UUID getRequestID() { + return requestID; + } + public void setRequestID(UUID requestID) { + this.requestID = requestID; + } + public String getResult() { + return result; + } + public void setResult(String result) { + this.result = result; + } + +}
\ No newline at end of file diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java new file mode 100644 index 000000000..66d2f288e --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Iterator; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +//import org.openecomp.policy.appc.Response; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeCategory; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; + + +public class PolicyGuardXacmlHelper { + + + + public static com.att.research.xacml.api.Response callPDP(PDPEngine xacmlEmbeddedPdpEngine, String restfulPdpUrl, com.att.research.xacml.api.Request request, boolean isREST) { + // + // Send it to the PDP + // + com.att.research.xacml.api.Response response = null; + if (isREST) { + try { + String jsonString = JSONRequest.toString((com.att.research.xacml.api.Request) request, false); + // + // Call RESTful PDP + // + response = (com.att.research.xacml.api.Response) callRESTfulPDP(new ByteArrayInputStream(jsonString.getBytes()), new URL(restfulPdpUrl/*"https://localhost:8443/pdp/"*/)); + } catch (Exception e) { + System.err.println("Error in sending RESTful request: " + e); + } + } else if(xacmlEmbeddedPdpEngine != null){ + // + // Embedded call to PDP + // + long lTimeStart = System.currentTimeMillis(); + try { + response = (com.att.research.xacml.api.Response) xacmlEmbeddedPdpEngine.decide((com.att.research.xacml.api.Request) request); + } catch (PDPException e) { + System.err.println(e); + } + long lTimeEnd = System.currentTimeMillis(); + System.out.println("Elapsed Time: " + (lTimeEnd - lTimeStart) + "ms"); + } + return response; + } + + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param file + * @return + */ + private static com.att.research.xacml.api.Response callRESTfulPDP(InputStream is, URL restURL) { + com.att.research.xacml.api.Response response = null; + HttpURLConnection connection = null; + try { + + // + // Open up the connection + // + connection = (HttpURLConnection) restURL.openConnection(); + connection.setRequestProperty("Content-Type", "application/json"); + // + // Setup our method and headers + // + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // + // Send the request + // + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(is, os); + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 200) { + // + // Read the response + // + ContentType contentType = null; + try { + contentType = ContentType.parse(connection.getContentType()); + + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + response = (com.att.research.xacml.api.Response) JSONResponse.load(connection.getInputStream()); + } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { + response = (com.att.research.xacml.api.Response) DOMResponse.load(connection.getInputStream()); + } else { + System.err.println("unknown content-type: " + contentType); + } + + } catch (Exception e) { + String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); + System.err.println(message); + } + + } else { + System.err.println(connection.getResponseCode() + " " + connection.getResponseMessage()); + } + } catch (Exception e) { + System.err.println(e); + } + + return response; + } + + + public static PolicyGuardResponse ParseXacmlPdpResponse(com.att.research.xacml.api.Response xacmlResponse){ + + if(xacmlResponse == null){ + + // + //In case the actual XACML response was null, create an empty response object with decision "Indeterminate" + // + return new PolicyGuardResponse("Indeterminate", null, ""); + } + + Iterator<Result> it_res = xacmlResponse.getResults().iterator(); + + Result res = it_res.next(); + String decision_from_xacml_response = res.getDecision().toString(); + Iterator<AttributeCategory> it_attr_cat = res.getAttributes().iterator(); + UUID req_id_from_xacml_response = null; + String operation_from_xacml_response = ""; + + while(it_attr_cat.hasNext()){ + Iterator<Attribute> it_attr = it_attr_cat.next().getAttributes().iterator(); + while(it_attr.hasNext()){ + Attribute current_attr = it_attr.next(); + String s = current_attr.getAttributeId().stringValue(); + //System.out.println("ATTR ID = " + s); + if(s.equals("urn:oasis:names:tc:xacml:1.0:request:request-id")){ + Iterator<AttributeValue<?>> it_values = current_attr.getValues().iterator(); + req_id_from_xacml_response = UUID.fromString(it_values.next().getValue().toString()); + //System.out.println("UUID = " + req_id_from_xacml_response); + } + if(s.equals("urn:oasis:names:tc:xacml:1.0:operation:operation-id")){ + Iterator<AttributeValue<?>> it_values = current_attr.getValues().iterator(); + operation_from_xacml_response = it_values.next().getValue().toString(); + //System.out.println("OPERATION = " + operation_from_xacml_response); + } + + } + } + + + + + + return new PolicyGuardResponse(decision_from_xacml_response, req_id_from_xacml_response, operation_from_xacml_response); + + } + + + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java new file mode 100644 index 000000000..4abb70f84 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + + +import com.att.research.xacml.std.annotations.XACMLAction; +import com.att.research.xacml.std.annotations.XACMLRequest; +import com.att.research.xacml.std.annotations.XACMLResource; +import com.att.research.xacml.std.annotations.XACMLSubject; + + + +@XACMLRequest(ReturnPolicyIdList=true,CombinedDecision=true) +public class PolicyGuardXacmlRequestAttributes { + + + + + public PolicyGuardXacmlRequestAttributes(String actor_id, String operation_id, String target_id, + String request_id) { + super(); + this.actor_id = actor_id; + this.operation_id = operation_id; + this.target_id = target_id; + this.request_id = request_id; + } + + + + @Override + public String toString() { + return "PolicyGuardXacmlRequestAttributes [actor_id=" + actor_id + ", operation_id=" + operation_id + + ", target_id=" + target_id + ", request_id=" + request_id + "]"; + } + + + + //@XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id") + //String userID; + + //@XACMLAction() + //String action; + + @XACMLSubject(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id") + String actor_id; + + @XACMLAction(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id") + String operation_id; + + //@XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id123") + //String resource; + + @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:target:target-id") + String target_id; + + @XACMLResource(includeInResults=true, attributeId="urn:oasis:names:tc:xacml:1.0:request:request-id") + String request_id; + + public String getActor_id() { + return actor_id; + } + + + + public void setActor_id(String actor_id) { + this.actor_id = actor_id; + } + + + + public String getOperation_id() { + return operation_id; + } + + + + public void setOperation_id(String operation_id) { + this.operation_id = operation_id; + } + + + + public String getTarget_id() { + return target_id; + } + + + + public void setTarget_id(String target_id) { + this.target_id = target_id; + } + + + + public String getRequest_id() { + return request_id; + } + + + + public void setRequest_id(String request_id) { + this.request_id = request_id; + } + + + + + }; + diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java new file mode 100644 index 000000000..b9a7881b6 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; + + +public class PolicyGuardYamlToXacml { + + + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ + + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().recipe); + System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num); + System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration); + System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuard(xacmlTemplateContent, + yamlGuardObject.guards.getFirst().actor, + yamlGuardObject.guards.getFirst().recipe, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg2"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg3") + ); + + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + + + public static String generateXacmlGuard(String xacmlFileContent, + String actor, + String recipe, + Integer limit, + Map<String,String> timeWindow, + String guardActiveStart, + String guardActiveEnd) { + + Pattern p = Pattern.compile("\\$\\{actor\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(actor); + + p = Pattern.compile("\\$\\{recipe\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(recipe); + + p = Pattern.compile("\\$\\{limit\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(limit.toString()); + + + //p = Pattern.compile("\\$\\{timeWindow\\}"); + //m = p.matcher(xacmlFileContent); + //xacmlFileContent = m.replaceAll("tw"+timeWindow); + + p = Pattern.compile("\\$\\{twValue\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(timeWindow.get("value")); + + p = Pattern.compile("\\$\\{twUnits\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(timeWindow.get("units")); + + + p = Pattern.compile("\\$\\{guardActiveStart\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveStart); + + p = Pattern.compile("\\$\\{guardActiveEnd\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveEnd); + System.out.println(xacmlFileContent); + + return xacmlFileContent; + } + + + + public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){ + + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + System.out.println("actor: " + yamlGuardObject.guards.getFirst().actor); + System.out.println("recipe: " + yamlGuardObject.guards.getFirst().recipe); + System.out.println("num: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().num); + System.out.println("duration: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().duration); + System.out.println("time_in_range: " + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generateXacmlGuardBlacklist(xacmlTemplateContent, + yamlGuardObject.guards.getFirst().actor, + yamlGuardObject.guards.getFirst().recipe, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().blacklist, + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg2"), + yamlGuardObject.guards.getFirst().limit_constraints.getFirst().time_in_range.get("arg3") + ); + + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + public static String generateXacmlGuardBlacklist(String xacmlFileContent, + String actor, + String recipe, + List<String> blacklist, + String guardActiveStart, + String guardActiveEnd) { + + Pattern p = Pattern.compile("\\$\\{actor\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(actor); + + p = Pattern.compile("\\$\\{recipe\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(recipe); + + p = Pattern.compile("\\$\\{guardActiveStart\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveStart); + + p = Pattern.compile("\\$\\{guardActiveEnd\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(guardActiveEnd); + System.out.println(xacmlFileContent); + + for(String target : blacklist){ + p = Pattern.compile("\\$\\{blackListElement\\}"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + + target + + "</AttributeValue>" + + "\n\t\t\t\t\t\t\\$\\{blackListElement\\}"); + } + + p = Pattern.compile("\t\t\t\t\t\t\\$\\{blackListElement\\}\n"); + m = p.matcher(xacmlFileContent); + xacmlFileContent = m.replaceAll(""); + + + return xacmlFileContent; + } + + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java new file mode 100644 index 000000000..f2e4f0ae2 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/TargetLock.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; + +public interface TargetLock { + + public UUID getLockID(); + + public TargetType getTargetType(); + + public String getTargetInstance(); + + public UUID getRequestID(); + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java new file mode 100644 index 000000000..702f27ccb --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; + + +public final class Util { + + public static class Pair<A, B> { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas"); + System.out.println(contents); + //for(Policy policy : ((ControlLoopPolicy)obj).policies){ + + return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java new file mode 100644 index 000000000..ea966ea55 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PNFTargetLock.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard.impl; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.LockCallback; +import org.onap.policy.guard.TargetLock; + +public class PNFTargetLock implements TargetLock, Serializable { + + /** + * + */ + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockID; + private final TargetType targetType; + private final String target; + private final UUID requestID; + private final LockCallback callback; + + public PNFTargetLock (TargetType type, String target, UUID requestID, LockCallback callback) { + this.lockID = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestID = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockID; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestID; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "PNFTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestID + "]"; + } + + + +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java new file mode 100644 index 000000000..1de105ce4 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VMTargetLock.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard.impl; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.LockCallback; +import org.onap.policy.guard.TargetLock; + +public class VMTargetLock implements TargetLock, Serializable { + + /** + * + */ + private static final long serialVersionUID = -8795145054334409724L; + private final UUID lockID; + private final TargetType targetType; + private final String target; + private final UUID requestID; + private final LockCallback callback; + + public VMTargetLock(TargetType targetType, String target, UUID requestID, LockCallback callback) { + this.lockID = UUID.randomUUID(); + this.targetType = targetType; + this.target = target; + this.requestID = requestID; + this.callback = callback; + } + + @Override + public UUID getLockID() { + return this.lockID; + } + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestID() { + return this.requestID; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "VMTargetLock [lockID=" + lockID + ", targetType=" + targetType + ", target=" + target + ", requestID=" + + requestID + "]"; + } + +} diff --git a/controlloop/common/guard/src/main/resources/META-INF/persistence.xml b/controlloop/common/guard/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..babf94b01 --- /dev/null +++ b/controlloop/common/guard/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<persistence xmlns="http://java.sun.com/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence + http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> + + <persistence-unit name="OperationsHistoryPU11" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <!-- <jar-file>packedEntity.jar</jar-file>--> + <!-- <class>com.att.ecomp.policy.controlloop.eventmanager.OperationsHistoryDbEntry</class> --> + <properties> + <property name="eclipselink.ddl-generation" value="create-tables"/> + <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> + <!-- <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:7779/policy"/>--> + <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://135.207.129.112:3306/policy"/> + <property name="javax.persistence.jdbc.user" value="root"/> + <property name="javax.persistence.jdbc.password" value="lmpg"/> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> + +</persistence>
\ No newline at end of file diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java new file mode 100644 index 000000000..7068fed3d --- /dev/null +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import org.junit.Test; + +public class PolicyGuardTest { + + @Test + public void test() { + + } + +} diff --git a/controlloop/common/model-impl/aai/pom.xml b/controlloop/common/model-impl/aai/pom.xml new file mode 100644 index 000000000..da412a138 --- /dev/null +++ b/controlloop/common/model-impl/aai/pom.xml @@ -0,0 +1,26 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>aai</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>rest</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAIGETResponse.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAIGETResponse.java new file mode 100644 index 000000000..d2e2d710f --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAIGETResponse.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAIGETResponse implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 7311418432051756161L; + + @SerializedName("relationship-list") + public RelationshipList relationshipList; + + public AAIGETResponse() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199CloudRegion.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199CloudRegion.java new file mode 100644 index 000000000..4c80c4a41 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199CloudRegion.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199CloudRegion implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -897231529157222683L; + + @SerializedName("cloud-owner") + public String cloudOwner; + + @SerializedName("cloud-region-id") + public String cloudRegionId; + + @SerializedName("cloud-region-version") + public String cloudRegionVersion; + + @SerializedName("complex-name") + public String complexName; + + @SerializedName("resource-version") + public String resourceVersion; + + public AAINQF199CloudRegion() { + } +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperties.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperties.java new file mode 100644 index 000000000..ca5863a46 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperties.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199ExtraProperties implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 4109625574744702319L; + + @SerializedName("extra-property") + public List<AAINQF199ExtraProperty> extraProperty = new LinkedList<AAINQF199ExtraProperty>(); + + public AAINQF199ExtraProperties() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperty.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperty.java new file mode 100644 index 000000000..7280ff9bc --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ExtraProperty.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199ExtraProperty implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3861240617222397736L; + + @SerializedName("property-name") + public String propertyName; + + @SerializedName("property-value") + public String propertyValue; + + public AAINQF199ExtraProperty() { + } + + public AAINQF199ExtraProperty(String propertyName, String propertyValue) { + this.propertyName = propertyName; + this.propertyValue = propertyValue; + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199GenericVNF.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199GenericVNF.java new file mode 100644 index 000000000..8d667bb75 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199GenericVNF.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199GenericVNF implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 834322706248060559L; + + @SerializedName("vnf-id") + public String vnfID; + + @SerializedName("vnf-name") + public String vnfName; + + @SerializedName("vnf-name2") + public String vnfName2; + + @SerializedName("vnf-type") + public String vnfType; + + @SerializedName("service-id") + public String serviceId; + + @SerializedName("prov-status") + public String provStatus; + + @SerializedName("operational-state") + public String operationalState; + + @SerializedName("ipv4-oam-address") + public String ipv4OamAddress; + + @SerializedName("ipv4-loopback0-address") + public String ipv4Loopback0Address; + + @SerializedName("in-maint") + public Boolean inMaint; + + @SerializedName("is-closed-loop-disabled") + public Boolean isClosedLoopDisabled; + + @SerializedName("resource-version") + public String resourceVersion; + + @SerializedName("encrypted-access-flag") + public Boolean encrypedAccessFlag; + + @SerializedName("persona-model-id") + public String personaModelId; + + @SerializedName("persona-model-version") + public String personaModelVersion; + + public AAINQF199GenericVNF() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InstanceFilters.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InstanceFilters.java new file mode 100644 index 000000000..80ab73d74 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InstanceFilters.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199InstanceFilters implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8993824591338121185L; + + @SerializedName("instance-filter") + public List<Map<String, Map<String, String>>> instanceFilter = new LinkedList<Map<String, Map<String, String>>>(); + + public AAINQF199InstanceFilters() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItem.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItem.java new file mode 100644 index 000000000..d896c931b --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItem.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199InventoryResponseItem implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 7142072567154675183L; + + @SerializedName("model-name") + public String modelName; + + @SerializedName("vf-module") + public AAINQF199VfModule vfModule; + + @SerializedName("service-instance") + public AAINQF199ServiceInstance serviceInstance; + + @SerializedName("vserver") + public AAINQF199VServer vserver; + + @SerializedName("tenant") + public AAINQF199Tenant tenant; + + @SerializedName("cloud-region") + public AAINQF199CloudRegion cloudRegion; + + @SerializedName("generic-vnf") + public AAINQF199GenericVNF genericVNF; + + @SerializedName("extra-properties") + public AAINQF199ExtraProperties extraProperties; + + @SerializedName("inventory-response-items") + public AAINQF199InventoryResponseItems items; + + public AAINQF199InventoryResponseItem() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItems.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItems.java new file mode 100644 index 000000000..d3d17093f --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199InventoryResponseItems.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199InventoryResponseItems implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 7602807659381179004L; + + @SerializedName("inventory-response-item") + public List<AAINQF199InventoryResponseItem> inventoryResponseItems = new LinkedList<AAINQF199InventoryResponseItem>(); + + public AAINQF199InventoryResponseItems() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Manager.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Manager.java new file mode 100644 index 000000000..e02021a43 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Manager.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.aai.AAIGETResponse; +import org.onap.policy.aai.util.Serialization; +import org.onap.policy.rest.RESTManager; +import org.onap.policy.rest.RESTManager.Pair; + +import com.google.gson.JsonSyntaxException; + +public final class AAINQF199Manager { + + public static AAINQF199Response postQuery(String url, String username, String password, AAINQF199Request request, UUID requestID) { + + Map<String, String> headers = new HashMap<String, String>(); + headers.put("X-FromAppId", "POLICY"); + headers.put("X-TransactionId", requestID.toString()); + headers.put("Accept", "application/json"); + + url = url + "/aai/search/named-query"; + + Pair<Integer, String> httpDetails = RESTManager.post(url, username, password, headers, "application/json", Serialization.gsonPretty.toJson(request)); + + if (httpDetails == null) { + System.out.println("AAI POST Null Response to " + url); + return null; + } + + System.out.println(url); + System.out.println(httpDetails.a); + System.out.println(httpDetails.b); + if (httpDetails.a == 200) { + try { + AAINQF199Response response = Serialization.gsonPretty.fromJson(httpDetails.b, AAINQF199Response.class); + return response; + } catch (JsonSyntaxException e) { + System.err.println("Failed to deserialize into AAIResponse" + e.getLocalizedMessage()); + } + } + + return null; + } + + public static AAIGETResponse getQuery(String urlGet, String username, String password, UUID requestID, String vnfId) { + + Map<String, String> headers = new HashMap<String, String>(); + headers.put("X-FromAppId", "POLICY"); + headers.put("X-TransactionId", requestID.toString()); + headers.put("Accept", "application/json"); + + urlGet = urlGet + "/aai/v8/network/generic-vnfs/generic-vnf/" + vnfId; + + int attemptsLeft = 3; + AAIGETResponse responseGet = null; + + while(attemptsLeft-- > 0){ + + Pair<Integer, String> httpDetailsGet = RESTManager.get(urlGet, username, password, headers); + if (httpDetailsGet == null) { + System.out.println("AAI GET Null Response to " + urlGet); + return null; + } + + System.out.println(urlGet); + System.out.println(httpDetailsGet.a); + System.out.println(httpDetailsGet.b); + + if (httpDetailsGet.a == 200) { + try { + responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.b, AAIGETResponse.class); + return responseGet; + } catch (JsonSyntaxException e) { + System.err.println("Failed to deserialize into AAIResponse" + e.getLocalizedMessage()); + } + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) {} + + } + + return null; + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199NamedQuery.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199NamedQuery.java new file mode 100644 index 000000000..922d67f39 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199NamedQuery.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; +import java.util.UUID; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199NamedQuery implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3277980060302645333L; + + @SerializedName("named-query-uuid") + public UUID namedQueryUUID; + + public AAINQF199NamedQuery() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199QueryParameters.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199QueryParameters.java new file mode 100644 index 000000000..8812a2483 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199QueryParameters.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199QueryParameters implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -4291227193197126982L; + + @SerializedName("named-query") + public AAINQF199NamedQuery namedQuery; + + public AAINQF199QueryParameters() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Request.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Request.java new file mode 100644 index 000000000..0feb6d73b --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Request.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + + +/* + * + * { + "query-parameters": { + "named-query": { + "named-query-uuid": "f199cb88-5e69-4b1f-93e0-6f257877d066" + } + }, + "instance-filters": { + "instance-filter": [ + { + "vserver": { + "vserver-name": "dfw1lb01lb01" + } + } + ] + } +} + + * + */ + +public class AAINQF199Request implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("query-parameters") + public AAINQF199QueryParameters queryParameters; + @SerializedName("instance-filters") + public AAINQF199InstanceFilters instanceFilters; + + public AAINQF199Request() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199RequestWrapper.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199RequestWrapper.java new file mode 100644 index 000000000..fdd630ba8 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199RequestWrapper.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.util.UUID; + +public class AAINQF199RequestWrapper { + + public UUID requestID; + public AAINQF199Request aainqf199request; + + public AAINQF199RequestWrapper() { + + } + + public AAINQF199RequestWrapper(UUID requestID, AAINQF199Request aainqf199request){ + this.requestID = requestID; + this.aainqf199request = aainqf199request; + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Response.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Response.java new file mode 100644 index 000000000..68a011b98 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Response.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199Response implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8411407444051746101L; + + @SerializedName("inventory-response-item") + public List<AAINQF199InventoryResponseItem> inventoryResponseItems = new LinkedList<AAINQF199InventoryResponseItem>(); + + public AAINQF199Response() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ResponseWrapper.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ResponseWrapper.java new file mode 100644 index 000000000..d4fe8f86d --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ResponseWrapper.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.util.UUID; + +import org.onap.policy.aai.AAINQF199.AAINQF199Response; + +public class AAINQF199ResponseWrapper { + + public UUID requestID; + public AAINQF199Response aainqf199response; + + public AAINQF199ResponseWrapper() { + + } + + public AAINQF199ResponseWrapper(UUID requestID, AAINQF199Response aainqf199response){ + this.requestID = requestID; + this.aainqf199response = aainqf199response; + } +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ServiceInstance.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ServiceInstance.java new file mode 100644 index 000000000..8aa4a1b2a --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199ServiceInstance.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199ServiceInstance implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -8000944396593889586L; + + @SerializedName("service-instance-id") + public String serviceInstanceID; + + @SerializedName("service-instance-name") + public String serviceInstanceName; + + @SerializedName("persona-model-id") + public String personaModelId; + + @SerializedName("persona-model-version") + public String personaModelVersion; + + @SerializedName("service-instance-location-id") + public String serviceInstanceLocationId; + + @SerializedName("resource-version") + public String resourceVersion; + + public AAINQF199ServiceInstance() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Tenant.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Tenant.java new file mode 100644 index 000000000..763c052ca --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Tenant.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199Tenant implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 4702784101671984364L; + + @SerializedName("tenant-id") + public String tenantId; + + @SerializedName("tenant-name") + public String tenantName; + + @SerializedName("resource-version") + public String resourceVersion; + + public AAINQF199Tenant() { + } +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VServer.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VServer.java new file mode 100644 index 000000000..8667544eb --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VServer.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199VServer { + + @SerializedName("vserver-id") + public String vserverId; + + @SerializedName("vserver-name") + public String vserverName; + + @SerializedName("vserver-name2") + public String vserverName2; + + @SerializedName("prov-status") + public String provStatus; + + @SerializedName("vserver-selflink") + public String vserverSelflink; + + @SerializedName("in-maint") + public Boolean inMaint; + + @SerializedName("is-closed-loop-disabled") + public Boolean isClosedLoopDisabled; + + @SerializedName("resource-version") + public String resourceVersion; + + public AAINQF199VServer() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VfModule.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VfModule.java new file mode 100644 index 000000000..50161fb8a --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199VfModule.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.AAINQF199; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class AAINQF199VfModule implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8019133081429638231L; + + @SerializedName("vf-module-id") + public String vfModuleId; + + @SerializedName("vf-module-name") + public String vfModuleName; + + @SerializedName("heat-stack-id") + public String heatStackId; + + @SerializedName("orchestration-status") + public String orchestrationStatus; + + @SerializedName("is-base-vf-module") + public Boolean isBaseVfModule; + + @SerializedName("resource-version") + public String resourceVersion; + + @SerializedName("persona-model-id") + public String personaModelId; + + @SerializedName("persona-model-version") + public String personaModelVersion; + + @SerializedName("widget-model-id") + public String widgetModelId; + + @SerializedName("widget-model-version") + public String widgetModelVersion; + + @SerializedName("contrail-service-instance-fqdn") + public String contrailServiceInstanceFqdn; + + public AAINQF199VfModule() { + } +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNF.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNF.java new file mode 100644 index 000000000..d8074e0a8 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNF.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import java.io.Serializable; + +public class PNF implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3535108358668248501L; + + public String PNFName; + public PNFType PNFType; + + public PNF() { + + } + + public PNF(PNF pnf) { + this.PNFName = pnf.PNFName; + this.PNFType = pnf.PNFType; + } + + @Override + public String toString() { + return "PNF [PNFName=" + PNFName + ", PNFType=" + PNFType + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((PNFName == null) ? 0 : PNFName.hashCode()); + result = prime * result + ((PNFType == null) ? 0 : PNFType.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; + PNF other = (PNF) obj; + if (PNFName == null) { + if (other.PNFName != null) + return false; + } else if (!PNFName.equals(other.PNFName)) + return false; + if (PNFType != other.PNFType) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFInstance.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFInstance.java new file mode 100644 index 000000000..21d1d50ac --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFInstance.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import java.io.Serializable; + +public class PNFInstance implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3694152433472165034L; + + public String PNFName; + public String PNFInstanceName; + public PNFType PNFType; + public String PNFSerial; + + public PNFInstance() { + + } + + public PNFInstance(PNFInstance instance) { + if (instance == null) { + return; + } + this.PNFName = instance.PNFName; + this.PNFInstanceName = instance.PNFInstanceName; + this.PNFType = instance.PNFType; + this.PNFSerial = instance.PNFSerial; + } + + @Override + public String toString() { + return "PNFInstance [PNFName=" + PNFName + ", PNFInstanceName=" + PNFInstanceName + ", PNFType=" + PNFType + + ", PNFSerial=" + PNFSerial + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((PNFInstanceName == null) ? 0 : PNFInstanceName.hashCode()); + result = prime * result + ((PNFName == null) ? 0 : PNFName.hashCode()); + result = prime * result + ((PNFSerial == null) ? 0 : PNFSerial.hashCode()); + result = prime * result + ((PNFType == null) ? 0 : PNFType.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; + PNFInstance other = (PNFInstance) obj; + if (PNFInstanceName == null) { + if (other.PNFInstanceName != null) + return false; + } else if (!PNFInstanceName.equals(other.PNFInstanceName)) + return false; + if (PNFName == null) { + if (other.PNFName != null) + return false; + } else if (!PNFName.equals(other.PNFName)) + return false; + if (PNFSerial == null) { + if (other.PNFSerial != null) + return false; + } else if (!PNFSerial.equals(other.PNFSerial)) + return false; + if (PNFType != other.PNFType) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFType.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFType.java new file mode 100644 index 000000000..e3d068877 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/PNFType.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +public enum PNFType { + ENODEB("eNodeB"), + PSERVER("pserver") + ; + + private String type; + + private PNFType(String type) { + this.type = type; + } + + public String toString() { + return this.type; + + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelatedToPropertyItem.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelatedToPropertyItem.java new file mode 100644 index 000000000..7b5bcafa7 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelatedToPropertyItem.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import com.google.gson.annotations.SerializedName; + +public class RelatedToPropertyItem { + + @SerializedName("property-key") + public String propertyKey; + @SerializedName("property-value") + public String propertyValue; + + public RelatedToPropertyItem() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipItem.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipItem.java new file mode 100644 index 000000000..0cfc82ec9 --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipItem.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import java.util.List; +import java.util.LinkedList; + +import com.google.gson.annotations.SerializedName; + +public class RelationshipItem { + + @SerializedName("related-to-property") + public List<RelatedToPropertyItem> relatedToProperty = new LinkedList<RelatedToPropertyItem>(); + + public RelationshipItem() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipList.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipList.java new file mode 100644 index 000000000..36d34f75b --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/RelationshipList.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai; + +import java.util.List; +import java.util.LinkedList; + +import com.google.gson.annotations.SerializedName; + +public class RelationshipList { + + @SerializedName("relationship") + public List<RelationshipItem> relationship = new LinkedList<RelationshipItem>(); + + public RelationshipList() { + } + +} diff --git a/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/util/Serialization.java b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/util/Serialization.java new file mode 100644 index 000000000..785c173eb --- /dev/null +++ b/controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/util/Serialization.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * aai + * ================================================================================ + * 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.aai.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public final class Serialization { + + final static public Gson gsonPretty = new GsonBuilder().disableHtmlEscaping() + .setPrettyPrinting() +// .registerTypeAdapter(AAIQueryParameters.class, new notificationTypeAdapter()) + .create(); +} diff --git a/controlloop/common/model-impl/appc/pom.xml b/controlloop/common/model-impl/appc/pom.xml new file mode 100644 index 000000000..ae6ff0f5f --- /dev/null +++ b/controlloop/common/model-impl/appc/pom.xml @@ -0,0 +1,45 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>appc</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/CommonHeader.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/CommonHeader.java new file mode 100644 index 000000000..4df25ecc5 --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/CommonHeader.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +import java.io.Serializable; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +public class CommonHeader implements Serializable { + + private static final long serialVersionUID = -3581658269910980336L; + + public Instant TimeStamp = Instant.now(); + public String APIver = "1.01"; + public String OriginatorID; + public UUID RequestID; + public String SubRequestID; + public Collection<String> RequestTrack = new ArrayList<String>(); + public Collection<Map<String, String>> Flags = new ArrayList<Map<String, String>>(); + + public CommonHeader() { + + } + + public CommonHeader(CommonHeader commonHeader) { + this.OriginatorID = commonHeader.OriginatorID; + this.RequestID = commonHeader.RequestID; + this.SubRequestID = commonHeader.SubRequestID; + if (commonHeader.RequestTrack != null) { + this.RequestTrack.addAll(commonHeader.RequestTrack); + } + if (commonHeader.Flags != null) { + this.Flags.addAll(commonHeader.Flags); + } + } + + @Override + public String toString() { + return "CommonHeader [TimeStamp=" + TimeStamp + ", APIver=" + APIver + ", OriginatorID=" + OriginatorID + + ", RequestID=" + RequestID + ", SubrequestID=" + SubRequestID + ", RequestTrack=" + RequestTrack + + ", Flags=" + Flags + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((APIver == null) ? 0 : APIver.hashCode()); + result = prime * result + ((Flags == null) ? 0 : Flags.hashCode()); + result = prime * result + ((OriginatorID == null) ? 0 : OriginatorID.hashCode()); + result = prime * result + ((RequestID == null) ? 0 : RequestID.hashCode()); + result = prime * result + ((RequestTrack == null) ? 0 : RequestTrack.hashCode()); + result = prime * result + ((SubRequestID == null) ? 0 : SubRequestID.hashCode()); + result = prime * result + ((TimeStamp == null) ? 0 : TimeStamp.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; + CommonHeader other = (CommonHeader) obj; + if (APIver == null) { + if (other.APIver != null) + return false; + } else if (!APIver.equals(other.APIver)) + return false; + if (Flags == null) { + if (other.Flags != null) + return false; + } else if (!Flags.equals(other.Flags)) + return false; + if (OriginatorID == null) { + if (other.OriginatorID != null) + return false; + } else if (!OriginatorID.equals(other.OriginatorID)) + return false; + if (RequestID == null) { + if (other.RequestID != null) + return false; + } else if (!RequestID.equals(other.RequestID)) + return false; + if (RequestTrack == null) { + if (other.RequestTrack != null) + return false; + } else if (!RequestTrack.equals(other.RequestTrack)) + return false; + if (SubRequestID == null) { + if (other.SubRequestID != null) + return false; + } else if (!SubRequestID.equals(other.SubRequestID)) + return false; + if (TimeStamp == null) { + if (other.TimeStamp != null) + return false; + } else if (!TimeStamp.equals(other.TimeStamp)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Request.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Request.java new file mode 100644 index 000000000..fbf0d8ee5 --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Request.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class Request implements Serializable{ + + private static final long serialVersionUID = -3912323643990646431L; + + public CommonHeader CommonHeader; + public String Action; + public String TargetID; + public String ObjectID; + public Map<String, Object> Payload = new HashMap<String, Object>(); + + public Request() { + + } + + public CommonHeader getCommonHeader() { + return CommonHeader; + } + + public Map<String, Object> getPayload() { + return Payload; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((Action == null) ? 0 : Action.hashCode()); + result = prime * result + ((CommonHeader == null) ? 0 : CommonHeader.hashCode()); + result = prime * result + ((ObjectID == null) ? 0 : ObjectID.hashCode()); + result = prime * result + ((Payload == null) ? 0 : Payload.hashCode()); + result = prime * result + ((TargetID == null) ? 0 : TargetID.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; + Request other = (Request) obj; + if (Action == null) { + if (other.Action != null) + return false; + } else if (!Action.equals(other.Action)) + return false; + if (CommonHeader == null) { + if (other.CommonHeader != null) + return false; + } else if (!CommonHeader.equals(other.CommonHeader)) + return false; + if (ObjectID == null) { + if (other.ObjectID != null) + return false; + } else if (!ObjectID.equals(other.ObjectID)) + return false; + if (Payload == null) { + if (other.Payload != null) + return false; + } else if (!Payload.equals(other.Payload)) + return false; + if (TargetID == null) { + if (other.TargetID != null) + return false; + } else if (!TargetID.equals(other.TargetID)) + return false; + return true; + } + + @Override + public String toString() { + return "Request [CommonHeader=" + CommonHeader + ", Action=" + Action + ", TargetID=" + TargetID + ", ObjectID=" + + ObjectID + ", Payload=" + Payload + "]"; + } + +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Response.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Response.java new file mode 100644 index 000000000..f9f494625 --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/Response.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class Response implements Serializable { + + private static final long serialVersionUID = 434953706339865151L; + + public CommonHeader CommonHeader; + public ResponseStatus Status = new ResponseStatus(); + public Map<String, Object> Payload = new HashMap<String, Object>(); + + public Response() { + + } + + public Response(Request request) { + this.CommonHeader = new CommonHeader(request.CommonHeader); + if (request.Payload != null) { + this.Payload.putAll(request.Payload); + } + } + + public CommonHeader getCommonHeader() { + return CommonHeader; + } + + public void setCommonHeader(CommonHeader commonHeader) { + CommonHeader = commonHeader; + } + + public ResponseStatus getStatus() { + return Status; + } + + public void setStatus(ResponseStatus status) { + Status = status; + } + + public Map<String, Object> getPayload() { + return Payload; + } + + public void setPayload(Map<String, Object> payload) { + Payload = payload; + } + + @Override + public String toString() { + return "Response [CommonHeader=" + CommonHeader + ", Status=" + Status + ", Payload=" + Payload + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((CommonHeader == null) ? 0 : CommonHeader.hashCode()); + result = prime * result + ((Payload == null) ? 0 : Payload.hashCode()); + result = prime * result + ((Status == null) ? 0 : Status.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; + Response other = (Response) obj; + if (CommonHeader == null) { + if (other.CommonHeader != null) + return false; + } else if (!CommonHeader.equals(other.CommonHeader)) + return false; + if (Payload == null) { + if (other.Payload != null) + return false; + } else if (!Payload.equals(other.Payload)) + return false; + if (Status == null) { + if (other.Status != null) + return false; + } else if (!Status.equals(other.Status)) + return false; + return true; + } + + + +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseCode.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseCode.java new file mode 100644 index 000000000..9bc9bb13e --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseCode.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +public enum ResponseCode { + ACCEPT(100), + ERROR(200), + REJECT(300), + SUCCESS(400), + FAILURE(500) + ; + + private Integer code; + + private ResponseCode(int code) { + this.code = code; + } + + public int getValue() { + return this.code; + } + + public String toString() { + return Integer.toString(this.code); + } + + public static ResponseCode toResponseCode(int code) { + if (code == ACCEPT.code) { + return ACCEPT; + } + if (code == ERROR.code) { + return ERROR; + } + if (code == REJECT.code) { + return REJECT; + } + if (code == SUCCESS.code) { + return SUCCESS; + } + if (code == FAILURE.code) { + return FAILURE; + } + return null; + } +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseStatus.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseStatus.java new file mode 100644 index 000000000..6319dd8ad --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseStatus.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +import java.io.Serializable; + +public class ResponseStatus implements Serializable { + + private static final long serialVersionUID = 2421770469587860452L; + + public int Code; + public String Value; + public String Description; + + @Override + public String toString() { + return "ResponseStatus [Code=" + Code + ", Value=" + Value + ", Description=" + Description + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Code; + result = prime * result + ((Description == null) ? 0 : Description.hashCode()); + result = prime * result + ((Value == null) ? 0 : Value.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; + ResponseStatus other = (ResponseStatus) obj; + if (Code != other.Code) + return false; + if (Description == null) { + if (other.Description != null) + return false; + } else if (!Description.equals(other.Description)) + return false; + if (Value == null) { + if (other.Value != null) + return false; + } else if (!Value.equals(other.Value)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseValue.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseValue.java new file mode 100644 index 000000000..4de0f81f9 --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/ResponseValue.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc; + +public enum ResponseValue { + ACCEPT("ACCEPT"), + ERROR("ERROR"), + REJECT("REJECT"), + SUCCESS("SUCCESS"), + FAILURE("FAILURE") + ; + + private String value; + + private ResponseValue(String value) { + this.value = value; + } + + public String toString() { + return this.value; + } + + public static ResponseValue toResponseValue(String value) { + if (value.toString().equals(ACCEPT.toString())) { + return ACCEPT; + } + if (value.toString().equals(ERROR.toString())) { + return ERROR; + } + if (value.toString().equals(REJECT.toString())) { + return REJECT; + } + if (value.toString().equals(SUCCESS.toString())) { + return SUCCESS; + } + if (value.toString().equals(FAILURE.toString())) { + return FAILURE; + } + + return null; + } + +} diff --git a/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/util/Serialization.java b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/util/Serialization.java new file mode 100644 index 000000000..8a801c32b --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/util/Serialization.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * appc + * ================================================================================ + * 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.appc.util; + +import java.lang.reflect.Type; +import java.time.Instant; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +public final class Serialization { + + public static DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx"); + + public static class gsonUTCAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> { + + public ZonedDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context) + throws JsonParseException { + try { + return ZonedDateTime.parse(element.getAsString(), format); + } catch (Exception e) { + System.err.println(e); + } + return null; + } + + public JsonElement serialize(ZonedDateTime datetime, Type type, JsonSerializationContext context) { + return new JsonPrimitive(datetime.format(format)); + } + } + public static class gsonInstantAdapter implements JsonSerializer<Instant>, JsonDeserializer<Instant> { + + @Override + public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return Instant.ofEpochMilli(json.getAsLong()); + } + + @Override + public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.toEpochMilli()); + } + + } + + public static final Gson gsonPretty = new GsonBuilder() + .disableHtmlEscaping() + .setPrettyPrinting() + .registerTypeAdapter(ZonedDateTime.class, new gsonUTCAdapter()) + .registerTypeAdapter(Instant.class, new gsonInstantAdapter()) +// .registerTypeAdapter(CommonHeader1607.class, new gsonCommonHeaderInstance()) +// .registerTypeAdapter(ResponseStatus1607.class, new gsonResponseStatus()) + .create(); + +} diff --git a/controlloop/common/model-impl/appc/src/main/resources/definitions.yaml b/controlloop/common/model-impl/appc/src/main/resources/definitions.yaml new file mode 100644 index 000000000..680a9929c --- /dev/null +++ b/controlloop/common/model-impl/appc/src/main/resources/definitions.yaml @@ -0,0 +1,118 @@ +### +# ============LICENSE_START======================================================= +# appc +# ================================================================================ +# 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========================================================= +### + +Request: + type: object + properties: + CommonHeader: + type: object + properties: + TimeStamp: + type: string + APIver: + type: string + value: '1.01' + OriginatorID: + type: string + RequestID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + SubRequestID: + type: string + Flags: + type: object + required: + - TimeStamp + - APIver + - OriginatorID + - RequestID + Action: + type: string + enum: + - Audit + - ActionStatus + - BlockAudits + - Configure + - HealthCheck + - Install + - LiveUpgrade + - Migrate + - ModifyConfig + - Query + - Rebuild + - Reconfigure + - Restart + - Rollback + - Scale + - Start + - Stop + - Sync + - Terminate + - Test + - Upgrade + TargetID: + type: string + ObjectID: + type: string + Payload: + type: object + required: + - CommonHeader + - Action + - TargetID +Response: + type: object + properties: + CommonHeader: + type: object + properties: + TimeStamp: + type: string + APIver: + type: string + OriginatorID: + type: string + RequestID: + type: string + SubRequestID: + type: string + Flags: + type: object + required: + - TimeStamp + - APIver + - OriginatorID + - RequestID + Status: + type: object + properties: + Code: + type: integer + Value: + type: string + required: + - Code + - Value + Payload: + type: object + required: + - CommonHeader + - Status + diff --git a/controlloop/common/model-impl/events/README.md b/controlloop/common/model-impl/events/README.md new file mode 100644 index 000000000..1347d78a6 --- /dev/null +++ b/controlloop/common/model-impl/events/README.md @@ -0,0 +1,7 @@ +Policy Control Loop + +This is the implementation of the Policy's Control Loop messages. This includes the Events consumed and Notifications produced by the ECOMP Policy Platform. + + + + diff --git a/controlloop/common/model-impl/events/pom.xml b/controlloop/common/model-impl/events/pom.xml new file mode 100644 index 000000000..e7f4f9482 --- /dev/null +++ b/controlloop/common/model-impl/events/pom.xml @@ -0,0 +1,16 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>events</artifactId> + <dependencies> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopEvent.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopEvent.java index d7fa04884..df099ed5e 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopEvent.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopEvent.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.io.Serializable; import java.util.UUID; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopEventStatus.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopEventStatus.java index 063a611b9..f74b626cb 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopEventStatus.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopEventStatus.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; public enum ControlLoopEventStatus { ONSET("ONSET"), diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopNotification.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopNotification.java index 15c61a80a..8e29b1de3 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopNotification.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopNotification.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.io.Serializable; import java.time.ZoneOffset; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopNotificationType.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopNotificationType.java index a5618df02..5417baed9 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopNotificationType.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopNotificationType.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; public enum ControlLoopNotificationType { ACTIVE("ACTIVE"), diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopOperation.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopOperation.java index 8925ee287..ce721b43d 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopOperation.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopOperation.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.io.Serializable; import java.time.Instant; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopOperationWrapper.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopOperationWrapper.java index 417a59d8e..fb3942b63 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopOperationWrapper.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopOperationWrapper.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.util.UUID; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopTargetType.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopTargetType.java index c1ed0e1d8..c8bd1a80c 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/ControlLoopTargetType.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/ControlLoopTargetType.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; public enum ControlLoopTargetType { VM("VM"), diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/PhysicalControlLoopEvent.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/PhysicalControlLoopEvent.java index 615ee48bc..aca072eaa 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/PhysicalControlLoopEvent.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/PhysicalControlLoopEvent.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; public class PhysicalControlLoopEvent extends ControlLoopEvent { diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/PhysicalControlLoopNotification.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/PhysicalControlLoopNotification.java index ee093cb67..c904d6740 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/PhysicalControlLoopNotification.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/PhysicalControlLoopNotification.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; public class PhysicalControlLoopNotification extends ControlLoopNotification { diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/VirtualControlLoopEvent.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/VirtualControlLoopEvent.java index 6ca280e4a..bc3d2beb7 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/VirtualControlLoopEvent.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/VirtualControlLoopEvent.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.time.Instant; import java.util.HashMap; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/VirtualControlLoopNotification.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/VirtualControlLoopNotification.java index 239a3ef21..f97c609c7 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/VirtualControlLoopNotification.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/VirtualControlLoopNotification.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop; +package org.onap.policy.controlloop; import java.time.Instant; import java.util.HashMap; diff --git a/controlloop/src/main/java/org/openecomp/policy/controlloop/util/Serialization.java b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/util/Serialization.java index 2625da712..a45947733 100644 --- a/controlloop/src/main/java/org/openecomp/policy/controlloop/util/Serialization.java +++ b/controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/util/Serialization.java @@ -18,15 +18,15 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.policy.controlloop.util; +package org.onap.policy.controlloop.util; import java.lang.reflect.Type; import java.time.Instant; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import org.openecomp.policy.controlloop.ControlLoopNotificationType; -import org.openecomp.policy.controlloop.ControlLoopTargetType; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopTargetType; import com.google.gson.Gson; import com.google.gson.GsonBuilder; diff --git a/controlloop/src/main/resources/definitions.yaml b/controlloop/common/model-impl/events/src/main/resources/definitions.yaml index 13016ef5a..cbe422b82 100644 --- a/controlloop/src/main/resources/definitions.yaml +++ b/controlloop/common/model-impl/events/src/main/resources/definitions.yaml @@ -1,23 +1,34 @@ -### -# ============LICENSE_START======================================================= -# controlloop -# ================================================================================ -# 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========================================================= -### - +AAI: + type: object + properties: + AICVServerSelfLink: + type: string + VNF_NAME: + type: string + AICVMID: + type: string + AICTenantID: + type: string + LOC_ID: + type: string + in_maint: + type: boolean + AICIdentity: + type: string + Prov_status: + type: string + OAM_IPV4: + type: string + is_closed_loop_disabled: + type: boolean + VM_NAME: + type: string + OAM_IPV6: + type: string + required: + - AICVServerSelfLink + - AICIdentity + - is_closed_loop_disabled ControlLoop: type: object description: Common fields for control loop events and notifications @@ -25,10 +36,20 @@ ControlLoop: closedLoopControlName: type: string description: A UNIQUE string identifying the Closed Loop ID this event is for. There are no semantics behind this string. + serviceInstance: + $ref: '../../../com.att.ecomp.policy.asdc/src/main/resources/definitions.yaml#/serviceInstance' + resourceInstance: + $ref: '../../../com.att.ecomp.policy.asdc/src/main/resources/definitions.yaml#/resourceInstance' requestID: type: string description: This is required via ECOMP Platform Logging Requirements. pattern: /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/ + triggerID: + type: string + description: ID that maps back to Highland Park. Concatenation between eventID and firstEPOCH. + triggerSourceName: + type: string + description: pulled from eventSourceName of trigger H.P. alarm. The contents of this field should also be contained in the AAI Json sub-tag (see below). closedLoopAlarmStart: type: string description: firstEpoch. UTC Timestamp when this event was detected by DCAE. Conform to ECOMP Logging requirements. @@ -42,23 +63,20 @@ ControlLoop: type: string description: The target entity that is being administered. This could be VM_NAME, VNF_NAME, etc. This should map to a field name in the AAI sub-tag shown below. AAI: - type: object - description: Fields of node.attribute and their values that map to AAI topology. + $ref: '#/AAI' from: type: string - description: The ECOMP component generating this message. policyScope: type: string - description: The policy scope driving the generation of this message. policyName: type: string - description: The policy name driving the generation of this message. policyVersion: type: string - description: The policy version driving the generation of this message. required: - closedLoopControlName - requestID + - triggerID + - triggerSourceName - closedLoopAlarmStart - closedLoopEventClient - target @@ -73,7 +91,7 @@ Event: - properties: closedLoopEventStatus: type: string - description: The status for the event within Open DCAE. A value of “ONSET� indicates the event has been encountered. “ABATED� indicates the event has been abated. + description: The status for the event within Open DCAE. A value of “ONSET†indicates the event has been encountered. “ABATED†indicates the event has been abated. valid_values: - ONSET - ABATEMENT diff --git a/controlloop/common/model-impl/mso/pom.xml b/controlloop/common/model-impl/mso/pom.xml new file mode 100644 index 000000000..8e584a8ea --- /dev/null +++ b/controlloop/common/model-impl/mso/pom.xml @@ -0,0 +1,51 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>mso</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>rest</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOAsyncRequestStatus.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOAsyncRequestStatus.java new file mode 100644 index 000000000..7e7451a60 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOAsyncRequestStatus.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; +import java.time.LocalDateTime; + +import com.google.gson.annotations.SerializedName; + +public class MSOAsyncRequestStatus implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("correlator") + public String correlator; + + @SerializedName("requestId") + public String requestId; + + @SerializedName("instanceReferences") + public MSOInstanceReferences instanceReferences; + + @SerializedName("startTime") + public LocalDateTime startTime; + + @SerializedName("finishTime") + public LocalDateTime finishTime; + + @SerializedName("requestScope") + public String requestScope; + + @SerializedName("requestType") + public String requestType; + + @SerializedName("requestStatus") + public MSORequestStatus requestStatus; + + + public MSOAsyncRequestStatus() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOCloudConfiguration.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOCloudConfiguration.java new file mode 100644 index 000000000..965ada24d --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOCloudConfiguration.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSOCloudConfiguration implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("lcpCloudRegionId") + public String lcpCloudRegionId; + + @SerializedName("tenantId") + public String tenantId; + + public MSOCloudConfiguration() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOInstanceReferences.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOInstanceReferences.java new file mode 100644 index 000000000..f751c3a43 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOInstanceReferences.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSOInstanceReferences implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("requestId") + public String requestId; + + @SerializedName("instanceId") + public String instanceId; + + public MSOInstanceReferences() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOManager.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOManager.java new file mode 100644 index 000000000..79725901a --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOManager.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.mso.util.Serialization; +import org.onap.policy.rest.RESTManager; +import org.onap.policy.rest.RESTManager.Pair; + +import com.google.gson.JsonSyntaxException; + +public final class MSOManager { + + public static MSOResponse createModuleInstance(String url, String urlBase, String username, String password, MSORequest request) { + + // + // Call REST + // + Map<String, String> headers = new HashMap<String, String>(); + //headers.put("X-FromAppId", "POLICY"); + //headers.put("X-TransactionId", requestID.toString()); + headers.put("Accept", "application/json"); + + // + // 201 - CREATED - you are done just return + // + + Pair<Integer, String> httpDetails = RESTManager.post(url, username, password, headers, "application/json", Serialization.gsonPretty.toJson(request)); + + if (httpDetails == null) { + return null; + } + + if (httpDetails.a == 202) { + try { + MSOResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, MSOResponse.class); + + String body = Serialization.gsonPretty.toJson(response); + System.out.println("***** Response to post:"); + System.out.println(body); + + String requestId = response.requestReferences.requestId; + int attemptsLeft = 20; + + //String getUrl = "/orchestrationRequests/v2/"+requestId; + String urlGet = urlBase + "/orchestrationRequests/v2/"+requestId; + MSOResponse responseGet = null; + + while(attemptsLeft-- > 0){ + + Pair<Integer, String> httpDetailsGet = RESTManager.get(urlGet, username, password, headers); + responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.b, MSOResponse.class); + body = Serialization.gsonPretty.toJson(responseGet); + System.out.println("***** Response to get:"); + System.out.println(body); + + if(httpDetailsGet.a == 200){ + if(responseGet.request.requestStatus.requestState.equalsIgnoreCase("COMPLETE") || + responseGet.request.requestStatus.requestState.equalsIgnoreCase("FAILED")){ + System.out.println("***** ######## VF Module Creation "+responseGet.request.requestStatus.requestState); + return responseGet; + } + } + Thread.sleep(20000); + } + + System.out.println("***** ######## VF Module Creation timeout. Status: ("+responseGet.request.requestStatus.requestState+")"); + return responseGet; + } catch (JsonSyntaxException e) { + System.err.println("Failed to deserialize into MSOResponse" + e.getLocalizedMessage()); + } catch (InterruptedException e) { + System.err.println("Interrupted exception: " + e.getLocalizedMessage()); + } + } + + + + + return null; + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOModelInfo.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOModelInfo.java new file mode 100644 index 000000000..9efea94b1 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOModelInfo.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSOModelInfo implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("modelType") + public String modelType; + + @SerializedName("modelInvariantId") + public String modelInvariantId; + + @SerializedName("modelNameVersionId") + public String modelNameVersionId; + + @SerializedName("modelName") + public String modelName; + + @SerializedName("modelVersion") + public String modelVersion; + + @SerializedName("modelCustomizationName") + public String modelCustomizationName; + + public MSOModelInfo() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOPolicyException.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOPolicyException.java new file mode 100644 index 000000000..97e85132a --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOPolicyException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class MSOPolicyException implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("messageId") + public String messageId; + + @SerializedName("text") + public String text; + + public MSOPolicyException() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstance.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstance.java new file mode 100644 index 000000000..0eec72f70 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstance.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + + +import com.google.gson.annotations.SerializedName; + +public class MSORelatedInstance implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("instanceId") + public String instanceId; + + @SerializedName("instanceName") + public String instanceName; + + @SerializedName("modelInfo") + public MSOModelInfo modelInfo; + + + public MSORelatedInstance() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstanceListElement.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstanceListElement.java new file mode 100644 index 000000000..dfeed32f2 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORelatedInstanceListElement.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSORelatedInstanceListElement implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("relatedInstance") + public MSORelatedInstance relatedInstance; + + + public MSORelatedInstanceListElement() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequest.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequest.java new file mode 100644 index 000000000..fa4e7892b --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; +import java.time.LocalDateTime; + +import com.google.gson.annotations.SerializedName; + +public class MSORequest implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("requestId") + public String requestId; + + @SerializedName("startTime") + //public LocalDateTime startTime; + public String startTime; + + @SerializedName("finishTime") + public LocalDateTime finishTime; + + @SerializedName("requestScope") + public String requestScope; + + @SerializedName("requestType") + public String requestType; + + @SerializedName("requestDetails") + public MSORequestDetails requestDetails; + + @SerializedName("requestStatus") + public MSORequestStatus requestStatus; + + public MSORequest() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestDetails.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestDetails.java new file mode 100644 index 000000000..180285765 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestDetails.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class MSORequestDetails implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("modelInfo") + public MSOModelInfo modelInfo; + + @SerializedName("cloudConfiguration") + public MSOCloudConfiguration cloudConfiguration; + + @SerializedName("requestInfo") + public MSORequestInfo requestInfo; + + @SerializedName("subscriberInfo") + public MSOSubscriberInfo subscriberInfo; + + @SerializedName("relatedInstanceList") + public List<MSORelatedInstanceListElement> relatedInstanceList= new LinkedList<MSORelatedInstanceListElement>(); + + @SerializedName("requestParameters") + public MSORequestParameters requestParameters; + + public MSORequestDetails() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestError.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestError.java new file mode 100644 index 000000000..849103e6d --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestError.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class MSORequestError implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + + @SerializedName("policyException") + public MSOPolicyException policyException; + + + @SerializedName("serviceException") + public MSOServiceException serviceException; + + /* + @SerializedName("messageId") + public String messageId; + + @SerializedName("text") + public String text; + + @SerializedName("url") + public String url; + + @SerializedName("variables") + public String variables; + */ + + public MSORequestError() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestInfo.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestInfo.java new file mode 100644 index 000000000..5c771b6e3 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestInfo.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSORequestInfo implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("instanceName") + public String instanceName; + + @SerializedName("source") + public String source; + + @SerializedName("productFamilyId") + public String productFamilyId; + + @SerializedName("suppressRollback") + public boolean suppressRollback; + + @SerializedName("billingAccountNumber") + public String billingAccountNumber; + + @SerializedName("callbackUrl") + public String callbackUrl; + + @SerializedName("correlator") + public String correlator; + + @SerializedName("orderNumber") + public String orderNumber; + + @SerializedName("orderVersion") + public Integer orderVersion; + + + public MSORequestInfo() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestParameters.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestParameters.java new file mode 100644 index 000000000..043a8e848 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestParameters.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + + +import com.google.gson.annotations.SerializedName; + +public class MSORequestParameters implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("subscriptionServiceType") + public String subscriptionServiceType; + + @SerializedName("userParams") + public List<Map<String, String>> userParams = new LinkedList<Map<String, String>>(); + + public MSORequestParameters() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestReferences.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestReferences.java new file mode 100644 index 000000000..c641db4bb --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestReferences.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSORequestReferences implements Serializable { + + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("instanceId") + public String instanceId; + + @SerializedName("requestId") + public String requestId; + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestStatus.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestStatus.java new file mode 100644 index 000000000..598e9cbdc --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSORequestStatus.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class MSORequestStatus implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("percentProgress") + public int percentProgress; + + @SerializedName("requestState") + public String requestState; + + @SerializedName("timestamp") + //public LocalDateTime timestamp; + public String timestamp; + + @SerializedName("wasRolledBack") + public boolean wasRolledBack; + + + public MSORequestStatus() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOResponse.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOResponse.java new file mode 100644 index 000000000..2106959fb --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOResponse.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class MSOResponse implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("requestReferences") + public MSORequestReferences requestReferences; + + @SerializedName("requestError") + public MSORequestError requestError; + + @SerializedName("request") + public MSORequest request; + + + + public MSOResponse() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOServiceException.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOServiceException.java new file mode 100644 index 000000000..3322bf8f3 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOServiceException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class MSOServiceException implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("messageId") + public String messageId; + + @SerializedName("text") + public String text; + + @SerializedName("variables") + public List<String> variables = new LinkedList<String>(); + + public MSOServiceException() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOSubscriberInfo.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOSubscriberInfo.java new file mode 100644 index 000000000..957c4c70c --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOSubscriberInfo.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class MSOSubscriberInfo implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("globalSubscriberId") + public String globalSubscriberId; + + @SerializedName("subscriberCommonSiteId") + public String subscriberCommonSiteId; + + @SerializedName("subscriberName") + public String subscriberName; + + public MSOSubscriberInfo() { + } + +} diff --git a/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/util/Serialization.java b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/util/Serialization.java new file mode 100644 index 000000000..24eb2951a --- /dev/null +++ b/controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/util/Serialization.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.mso.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public final class Serialization { + + final static public Gson gsonPretty = new GsonBuilder().disableHtmlEscaping() + .setPrettyPrinting() + .create(); + +} diff --git a/controlloop/common/model-impl/mso/src/test/java/org/openecomp/policy/mso/TestDemo.java b/controlloop/common/model-impl/mso/src/test/java/org/openecomp/policy/mso/TestDemo.java new file mode 100644 index 000000000..c6c750568 --- /dev/null +++ b/controlloop/common/model-impl/mso/src/test/java/org/openecomp/policy/mso/TestDemo.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * mso + * ================================================================================ + * 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.openecomp.policy.mso; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.util.Serialization; + +public class TestDemo { + + @Test + public void test() { + + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = "ff5256d2-5a33-55df-13ab-12abad84e7ff"; + request.requestDetails.modelInfo.modelNameVersionId = "fe6478e5-ea33-3346-ac12-ab121484a3fe"; + request.requestDetails.modelInfo.modelName = "vSAMP12..base..module-0"; + request.requestDetails.modelInfo.modelVersion = "1"; + + request.requestDetails.cloudConfiguration.lcpCloudRegionId = "mdt1"; + request.requestDetails.cloudConfiguration.tenantId = "88a6ca3ee0394ade9403f075db23167e"; + + request.requestDetails.requestInfo.instanceName = "MSOTEST103a-vSAMP12_base_module-0"; + request.requestDetails.requestInfo.source = "VID"; + request.requestDetails.requestInfo.suppressRollback = true; + + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement3 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement3.relatedInstance = new MSORelatedInstance(); + + relatedInstanceListElement1.relatedInstance.instanceId = "17ef4658-bd1f-4ef0-9ca0-ea76e2bf122c"; + relatedInstanceListElement1.relatedInstance.instanceName = "MSOTESTVOL103a-vSAMP12_base_module-0_vol"; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "volumeGroup"; + + relatedInstanceListElement2.relatedInstance.instanceId = "serviceInstanceId"; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = "ff3514e3-5a33-55df-13ab-12abad84e7ff"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = "fe6985cd-ea33-3346-ac12-ab121484a3fe"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = "parent service model name"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = "1.0"; + + relatedInstanceListElement3.relatedInstance.instanceId = "vnfInstanceId"; + relatedInstanceListElement3.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement3.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement3.relatedInstance.modelInfo.modelInvariantId = "ff5256d1-5a33-55df-13ab-12abad84e7ff"; + relatedInstanceListElement3.relatedInstance.modelInfo.modelNameVersionId = "fe6478e4-ea33-3346-ac12-ab121484a3fe"; + relatedInstanceListElement3.relatedInstance.modelInfo.modelName = "vSAMP12"; + relatedInstanceListElement3.relatedInstance.modelInfo.modelVersion = "1.0"; + relatedInstanceListElement3.relatedInstance.modelInfo.modelCustomizationName = "vSAMP12 1"; + + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement3); + + Map<String, String> userParam1 = new HashMap<String, String>(); + userParam1.put("name1", "value1"); + + Map<String, String> userParam2 = new HashMap<String, String>(); + userParam2.put("name2", "value2"); + + request.requestDetails.requestParameters.userParams.add(userParam1); + request.requestDetails.requestParameters.userParams.add(userParam2); + + String body = Serialization.gsonPretty.toJson(request); + System.out.println(body); + + //MSOResponse response = MSOManager.createModuleInstance("http://localhost:7780/", "my_username", "my_passwd", request); + + //body = Serialization.gsonPretty.toJson(response); + //System.out.println(body); + + } + + @Test + public void testHack() { + + System.out.println("** HACK **"); + + MSORequest request = new MSORequest(); + // + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = "a9c4a35a-de48-451a-9e4e-343f2ac52928"; + request.requestDetails.modelInfo.modelNameVersionId = "e0d98ad1-238d-4555-b439-023d3f9079f6"; + request.requestDetails.modelInfo.modelName = "0d9e0d9d352749f4B3cb..dnsscaling..module-0"; + request.requestDetails.modelInfo.modelVersion = "2.0"; + + request.requestDetails.cloudConfiguration.lcpCloudRegionId = "DFW"; + request.requestDetails.cloudConfiguration.tenantId = "1015548"; + + request.requestDetails.requestInfo.instanceName = "Vfmodule_Ete_Name1eScaling63928f-ccdc-4b34-bdef-9bf64109026e"; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + + String serviceInstanceId = "98af39ce-6408-466b-921f-c2c7a8f59ed6"; + relatedInstanceListElement1.relatedInstance.instanceId = serviceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = "24329a0c-1d57-4210-b1af-a65df64e9d59"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = "ac642881-8e7e-4217-bd64-16ad41c42e30"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = "5116d67e-0b4f-46bf-a46f"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = "2.0"; + + String vnfInstanceId = "8eb411b8-a936-412f-b01f-9a9a435c0e93"; + relatedInstanceListElement2.relatedInstance.instanceId = vnfInstanceId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = "09fd971e-db5f-475d-997c-cf6704b6b8fe"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = "152ed917-6dcc-46ee-bf8a-a775c5aa5a74"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = "9e4c31d2-4b25-4d9e-9fb4"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = "2.0"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = "0d9e0d9d-3527-49f4-b3cb 2"; + + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + + String body = Serialization.gsonPretty.toJson(request); + System.out.println(body); + } + +} diff --git a/controlloop/common/model-impl/pom.xml b/controlloop/common/model-impl/pom.xml new file mode 100644 index 000000000..94c3f345a --- /dev/null +++ b/controlloop/common/model-impl/pom.xml @@ -0,0 +1,46 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Common Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <artifactId>model-impl</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>aai</module> + <module>appc</module> + <module>events</module> + <module>mso</module> + <module>rest</module> + <module>sdc</module> + <module>trafficgenerator</module> + </modules> + + +</project> diff --git a/controlloop/common/model-impl/rest/pom.xml b/controlloop/common/model-impl/rest/pom.xml new file mode 100644 index 000000000..96c5bb98a --- /dev/null +++ b/controlloop/common/model-impl/rest/pom.xml @@ -0,0 +1,52 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>rest</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.2</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java b/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java new file mode 100644 index 000000000..e42ab1693 --- /dev/null +++ b/controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * rest + * ================================================================================ + * 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.rest; + +import java.io.IOException; +import java.util.Map; + +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; + +public final class RESTManager { + + public static class Pair<A, B> { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + public static Pair<Integer, String> post(String url, String username, String password, Map<String, String> headers, String contentType, String body) { + CredentialsProvider credentials = new BasicCredentialsProvider(); + credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); + + System.out.println("HTTP REQUEST: " + url + " -> " + username + ((password!=null)?password.length():"-") + " -> " + contentType); + if (headers != null) { + System.out.println("Headers: "); + headers.forEach((name, value) -> { + System.out.println(name + " -> " + value); + }); + } + System.out.println(body); + + try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) { + + HttpPost post = new HttpPost(url); + for (String key : headers.keySet()) { + post.addHeader(key, headers.get(key)); + } + post.addHeader("Content-Type", contentType); + + StringEntity input = new StringEntity(body); + input.setContentType(contentType); + post.setEntity(input); + + HttpResponse response = client.execute(post); + + String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + System.out.println("HTTP POST Response Status Code: " + response.getStatusLine().getStatusCode()); + System.out.println("HTTP POST Response Body:"); + System.out.println(returnBody); + + return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody); + } catch (IOException e) { + System.err.println("Failed to POST to " + url + e.getLocalizedMessage()); + return null; + } + + } + + public static Pair<Integer, String> get(String url, String username, String password, Map<String, String> headers) { + + CredentialsProvider credentials = new BasicCredentialsProvider(); + credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); + + try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) { + + HttpGet get = new HttpGet(url); + for (String key : headers.keySet()) { + get.addHeader(key, headers.get(key)); + } + + HttpResponse response = client.execute(get); + + String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + System.out.println("HTTP GET Response Status Code: " + response.getStatusLine().getStatusCode()); + System.out.println("HTTP GET Response Body:"); + System.out.println(returnBody); + + return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody); + } catch (IOException e) { + System.err.println("Failed to GET to " + url + e.getLocalizedMessage()); + return null; + } + } +} diff --git a/controlloop/common/model-impl/sdc/README.md b/controlloop/common/model-impl/sdc/README.md new file mode 100644 index 000000000..2a17461e5 --- /dev/null +++ b/controlloop/common/model-impl/sdc/README.md @@ -0,0 +1,3 @@ +ECOMP ASDC + + diff --git a/controlloop/common/model-impl/sdc/pom.xml b/controlloop/common/model-impl/sdc/pom.xml new file mode 100644 index 000000000..9a80bc6a4 --- /dev/null +++ b/controlloop/common/model-impl/sdc/pom.xml @@ -0,0 +1,11 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>sdc</artifactId> + +</project> diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java new file mode 100644 index 000000000..99b770475 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Resource.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * sdc + * ================================================================================ + * 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.sdc; + +import java.io.Serializable; +import java.util.UUID; + +public class Resource implements Serializable { + + private static final long serialVersionUID = -913729158733348027L; + + public UUID resourceUUID; + public UUID resourceInvariantUUID; + public String resourceName; + public String resourceVersion; + public ResourceType resourceType; + + public Resource() { + + } + + public Resource(Resource resource) { + this.resourceUUID = resource.resourceUUID; + this.resourceInvariantUUID = resource.resourceInvariantUUID; + this.resourceName = resource.resourceName; + this.resourceVersion = resource.resourceVersion; + this.resourceType = resource.resourceType; + } + + public Resource(UUID uuid) { + this.resourceUUID = uuid; + } + + public Resource(String name, ResourceType type) { + this.resourceName = name; + this.resourceType = type; + } + + public Resource(UUID uuid, UUID invariantUUID, String name, String version, ResourceType type) { + this.resourceUUID = uuid; + this.resourceInvariantUUID = invariantUUID; + this.resourceName = name; + this.resourceVersion = version; + this.resourceType = type; + } + + @Override + public String toString() { + return "Resource [resourceUUID=" + resourceUUID + ", resourceInvariantUUID=" + resourceInvariantUUID + + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceType=" + + resourceType + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); + result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); + result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.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; + Resource other = (Resource) obj; + if (resourceInvariantUUID == null) { + if (other.resourceInvariantUUID != null) + return false; + } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + return false; + if (resourceName == null) { + if (other.resourceName != null) + return false; + } else if (!resourceName.equals(other.resourceName)) + return false; + if (resourceType == null) { + if (other.resourceType != null) + return false; + } else if (!resourceType.equals(other.resourceType)) + return false; + if (resourceUUID == null) { + if (other.resourceUUID != null) + return false; + } else if (!resourceUUID.equals(other.resourceUUID)) + return false; + if (resourceVersion == null) { + if (other.resourceVersion != null) + return false; + } else if (!resourceVersion.equals(other.resourceVersion)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java new file mode 100644 index 000000000..108163a34 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceInstance.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * sdc + * ================================================================================ + * 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.sdc; + +import java.io.Serializable; +import java.util.UUID; + +public class ResourceInstance implements Serializable { + private static final long serialVersionUID = -5506162340393802424L; + + public String resourceInstanceName; + public String resourceName; + public UUID resourceInvariantUUID; + public String resourceVersion; + public ResourceType resourceType; + public UUID resourceUUID; + + public ResourceInstance() { + + } + + public ResourceInstance(ResourceInstance instance) { + if (instance == null) { + return; + } + this.resourceInstanceName = instance.resourceInstanceName; + this.resourceName = instance.resourceName; + this.resourceInvariantUUID = instance.resourceInvariantUUID; + this.resourceVersion = instance.resourceVersion; + this.resourceType = instance.resourceType; + this.resourceUUID = instance.resourceUUID; + } + + @Override + public String toString() { + return "ResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + resourceVersion + + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUUID + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((resourceInstanceName == null) ? 0 : resourceInstanceName.hashCode()); + result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); + result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); + result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.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; + ResourceInstance other = (ResourceInstance) obj; + if (resourceInstanceName == null) { + if (other.resourceInstanceName != null) + return false; + } else if (!resourceInstanceName.equals(other.resourceInstanceName)) + return false; + if (resourceInvariantUUID == null) { + if (other.resourceInvariantUUID != null) + return false; + } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + return false; + if (resourceName == null) { + if (other.resourceName != null) + return false; + } else if (!resourceName.equals(other.resourceName)) + return false; + if (resourceType != other.resourceType) + return false; + if (resourceUUID == null) { + if (other.resourceUUID != null) + return false; + } else if (!resourceUUID.equals(other.resourceUUID)) + return false; + if (resourceVersion == null) { + if (other.resourceVersion != null) + return false; + } else if (!resourceVersion.equals(other.resourceVersion)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java new file mode 100644 index 000000000..ee2fc89fd --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ResourceType.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * sdc + * ================================================================================ + * 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.sdc; + +public enum ResourceType { + VF("VF"), + VFC("VFC"), + VL("VL"), + CP("CP") + ; + + private String type; + + private ResourceType(String type) { + this.type = type; + } + + public String toString() { + return this.type; + } + +} diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java new file mode 100644 index 000000000..4b97168b8 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/Service.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * sdc + * ================================================================================ + * 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.sdc; + +import java.io.Serializable; +import java.util.UUID; + +public class Service implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -1249276698549996806L; + + public UUID serviceUUID; + public UUID serviceInvariantUUID; + public String serviceName; + public String serviceVersion; + + public Service() { + + } + + public Service(UUID uuid) { + this.serviceUUID = uuid; + } + + public Service(String name) { + this.serviceName = name; + } + + public Service(UUID uuid, UUID invariantUUID, String name, String version) { + this.serviceUUID = uuid; + this.serviceInvariantUUID = invariantUUID; + this.serviceName = name; + this.serviceVersion = version; + } + + public Service(Service service) { + this.serviceUUID = service.serviceUUID; + this.serviceInvariantUUID = service.serviceInvariantUUID; + this.serviceName = service.serviceName; + this.serviceVersion = service.serviceVersion; + } + + @Override + public String toString() { + return "Service [serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID + + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((serviceInvariantUUID == null) ? 0 : serviceInvariantUUID.hashCode()); + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); + result = prime * result + ((serviceVersion == null) ? 0 : serviceVersion.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; + Service other = (Service) obj; + if (serviceInvariantUUID == null) { + if (other.serviceInvariantUUID != null) + return false; + } else if (!serviceInvariantUUID.equals(other.serviceInvariantUUID)) + return false; + if (serviceName == null) { + if (other.serviceName != null) + return false; + } else if (!serviceName.equals(other.serviceName)) + return false; + if (serviceUUID == null) { + if (other.serviceUUID != null) + return false; + } else if (!serviceUUID.equals(other.serviceUUID)) + return false; + if (serviceVersion == null) { + if (other.serviceVersion != null) + return false; + } else if (!serviceVersion.equals(other.serviceVersion)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java new file mode 100644 index 000000000..519f88712 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/java/org/onap/policy/sdc/ServiceInstance.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * sdc + * ================================================================================ + * 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.sdc; + +import java.io.Serializable; +import java.util.UUID; + +public class ServiceInstance implements Serializable { + private static final long serialVersionUID = 6285260780966679625L; + + public UUID personaModelUUID; + public UUID serviceUUID; + public UUID serviceInstanceUUID; + public UUID widgetModelUUID; + public String widgetModelVersion; + public String serviceName; + public String serviceInstanceName; + + public ServiceInstance() { + + } + + public ServiceInstance(ServiceInstance instance) { + if (instance == null) { + return; + } + this.personaModelUUID = instance.personaModelUUID; + this.serviceUUID = instance.serviceUUID; + this.serviceInstanceUUID = instance.serviceInstanceUUID; + this.widgetModelUUID = instance.widgetModelUUID; + this.widgetModelVersion = instance.widgetModelVersion; + this.serviceName = instance.serviceName; + this.serviceInstanceName = instance.serviceInstanceName; + } + + @Override + public String toString() { + return "ServiceInstance [personaModelUUID=" + personaModelUUID + ", serviceUUID=" + serviceUUID + + ", serviceInstanceUUID=" + serviceInstanceUUID + ", widgetModelUUID=" + widgetModelUUID + + ", widgetModelVersion=" + widgetModelVersion + ", serviceName=" + serviceName + + ", serviceInstanceName=" + serviceInstanceName + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((personaModelUUID == null) ? 0 : personaModelUUID.hashCode()); + result = prime * result + ((serviceInstanceName == null) ? 0 : serviceInstanceName.hashCode()); + result = prime * result + ((serviceInstanceUUID == null) ? 0 : serviceInstanceUUID.hashCode()); + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); + result = prime * result + ((widgetModelUUID == null) ? 0 : widgetModelUUID.hashCode()); + result = prime * result + ((widgetModelVersion == null) ? 0 : widgetModelVersion.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; + ServiceInstance other = (ServiceInstance) obj; + if (personaModelUUID == null) { + if (other.personaModelUUID != null) + return false; + } else if (!personaModelUUID.equals(other.personaModelUUID)) + return false; + if (serviceInstanceName == null) { + if (other.serviceInstanceName != null) + return false; + } else if (!serviceInstanceName.equals(other.serviceInstanceName)) + return false; + if (serviceInstanceUUID == null) { + if (other.serviceInstanceUUID != null) + return false; + } else if (!serviceInstanceUUID.equals(other.serviceInstanceUUID)) + return false; + if (serviceName == null) { + if (other.serviceName != null) + return false; + } else if (!serviceName.equals(other.serviceName)) + return false; + if (serviceUUID == null) { + if (other.serviceUUID != null) + return false; + } else if (!serviceUUID.equals(other.serviceUUID)) + return false; + if (widgetModelUUID == null) { + if (other.widgetModelUUID != null) + return false; + } else if (!widgetModelUUID.equals(other.widgetModelUUID)) + return false; + if (widgetModelVersion == null) { + if (other.widgetModelVersion != null) + return false; + } else if (!widgetModelVersion.equals(other.widgetModelVersion)) + return false; + return true; + } + +} diff --git a/controlloop/common/model-impl/sdc/src/main/resources/definitions.yaml b/controlloop/common/model-impl/sdc/src/main/resources/definitions.yaml new file mode 100644 index 000000000..6fb1f7cfa --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/main/resources/definitions.yaml @@ -0,0 +1,76 @@ +Service: + type: Object + properties: + serviceUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + serviceInvariantUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + serviceName: + type: string + serviceVersion: + type: string +Resource: + type: Object + properties: + resourceUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + resourceInvariantUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + resourceName: + type: string + resourceVersion: + type: string + resourceType: + type: string + valid_values: + - VF + - VFC + - CP + - VL +ServiceInstance: + type: Object + properties: + personaModelUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + serviceUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + serviceInstanceUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + widgetModelUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + widgetModelVersion: + type: string + serviceName: + type: string + serviceInstanceName: + type: string +ResourceInstance: + type: object + properties: + resourceInstanceName: + type: string + resourceName: + type: string + resourceInvariantUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" + resourceVersion: + type: string + resourceType: + type: string + valid_values: + - VF + - VFC + - CP + - VL + resourceUUID: + type: string + pattern: "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" diff --git a/controlloop/common/model-impl/sdc/src/test/resources/service_trinity.yaml b/controlloop/common/model-impl/sdc/src/test/resources/service_trinity.yaml new file mode 100644 index 000000000..2dda7d705 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/test/resources/service_trinity.yaml @@ -0,0 +1,3 @@ +Service: + serviceName: trinity +
\ No newline at end of file diff --git a/controlloop/common/model-impl/sdc/src/test/resources/service_vSCP.yaml b/controlloop/common/model-impl/sdc/src/test/resources/service_vSCP.yaml new file mode 100644 index 000000000..c56961ec9 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/test/resources/service_vSCP.yaml @@ -0,0 +1,2 @@ +Service: + serviceName: vSCP
\ No newline at end of file diff --git a/controlloop/common/model-impl/sdc/src/test/resources/service_vUSP.yaml b/controlloop/common/model-impl/sdc/src/test/resources/service_vUSP.yaml new file mode 100644 index 000000000..e63636d39 --- /dev/null +++ b/controlloop/common/model-impl/sdc/src/test/resources/service_vUSP.yaml @@ -0,0 +1,2 @@ +Service: + serviceName: vUSP diff --git a/controlloop/common/model-impl/trafficgenerator/pom.xml b/controlloop/common/model-impl/trafficgenerator/pom.xml new file mode 100644 index 000000000..e822f1d9e --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/pom.xml @@ -0,0 +1,46 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>trafficgenerator</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>model-impl</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java new file mode 100644 index 000000000..d08d9422e --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGRequest.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * trafficgenerator + * ================================================================================ + * 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.vnf.trafficgenerator; + +import java.io.Serializable; + + +import com.google.gson.annotations.SerializedName; + +public class PGRequest implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3283942659786236032L; + + @SerializedName("pg-streams") + public PGStreams pgStreams; + + public PGRequest() { + } + +} diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java new file mode 100644 index 000000000..de5a2c37d --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStream.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * trafficgenerator + * ================================================================================ + * 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.vnf.trafficgenerator; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class PGStream implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5567635677419358210L; + + @SerializedName("id") + public String streamId; + @SerializedName("is-enabled") + public String isEnabled; + + public PGStream() { + } + +} diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java new file mode 100644 index 000000000..dc0d4084f --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/PGStreams.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * trafficgenerator + * ================================================================================ + * 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.vnf.trafficgenerator; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class PGStreams implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5567635677419358210L; + + @SerializedName("pg-stream") + public List<PGStream> pgStream= new LinkedList<PGStream>(); + + public PGStreams() { + } + +} diff --git a/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/util/Serialization.java b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/util/Serialization.java new file mode 100644 index 000000000..e64991d94 --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/src/main/java/org/onap/policy/vnf/trafficgenerator/util/Serialization.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * trafficgenerator + * ================================================================================ + * 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.vnf.trafficgenerator.util; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public final class Serialization { + + final static public Gson gsonPretty = new GsonBuilder().disableHtmlEscaping() + .setPrettyPrinting() +// .registerTypeAdapter(AAIQueryParameters.class, new notificationTypeAdapter()) + .create(); +} diff --git a/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java b/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java new file mode 100644 index 000000000..656234ca2 --- /dev/null +++ b/controlloop/common/model-impl/trafficgenerator/src/test/java/org/onap/policy/vnf/trafficgenerator/TestDemo.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * trafficgenerator + * ================================================================================ + * 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.vnf.trafficgenerator; + + +import org.junit.Test; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; +import org.onap.policy.vnf.trafficgenerator.util.Serialization; + +public class TestDemo { + + @Test + public void test() { + PGRequest request = new PGRequest(); + request.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + request.pgStreams.pgStream.add(pgStream); + } + + String body = Serialization.gsonPretty.toJson(request); + System.out.println(body); + + // fail("Not yet implemented"); + } + +} diff --git a/controlloop/common/packages/apps/pom.xml b/controlloop/common/packages/apps/pom.xml new file mode 100644 index 000000000..f591bdc38 --- /dev/null +++ b/controlloop/common/packages/apps/pom.xml @@ -0,0 +1,77 @@ +<!-- + ============LICENSE_START======================================================= + PDP-D Application Installation Packages + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>packages</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>apps</artifactId> + <packaging>pom</packaging> + + <name>PDP-D APPS Installation Package</name> + <description>PDP-D APPS Installation Package</description> + + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>single</goal> + </goals> + <phase>package</phase> + <configuration> + <descriptors> + <descriptor>src/assembly/zip.xml</descriptor> + </descriptors> + <appendAssemblyId>false</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + + <!-- List any dependencies here that should be included in the installer zip --> + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>basex</artifactId> + <version>${project.version}</version> + <type>tar.gz</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>artifacts</artifactId> + <version>${project.version}</version> + <type>zip</type> + </dependency> + </dependencies> + +</project> + diff --git a/controlloop/common/packages/apps/src/assembly/zip.xml b/controlloop/common/packages/apps/src/assembly/zip.xml new file mode 100644 index 000000000..f3392e130 --- /dev/null +++ b/controlloop/common/packages/apps/src/assembly/zip.xml @@ -0,0 +1,40 @@ +<!-- + ============LICENSE_START======================================================= + PDP-D APPS Installation Package + ================================================================================ + 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========================================================= + --> + +<assembly> + <id>zipfile</id> + <formats> + <format>zip</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>src/files</directory> + <outputDirectory>.</outputDirectory> + <fileMode>755</fileMode> + </fileSet> + </fileSets> + <dependencySets> + <dependencySet> + <useTransitiveDependencies>false</useTransitiveDependencies> + </dependencySet> + </dependencySets> +</assembly> + diff --git a/controlloop/common/packages/apps/src/files/README.apps.txt b/controlloop/common/packages/apps/src/files/README.apps.txt new file mode 100644 index 000000000..aab021885 --- /dev/null +++ b/controlloop/common/packages/apps/src/files/README.apps.txt @@ -0,0 +1,8 @@ + +The PDP-D apps installation package contains: + +1. artifacts-<version>.zip contains models and other jars to support PDP-D applications. +2. basex-<version>.tar.gz contains scripts and additional files to support the PDP-D models. + +The apps-<version>.zip must be placed in the same directory as the installation package +before installation before installation is attempted. diff --git a/controlloop/common/packages/artifacts/pom.xml b/controlloop/common/packages/artifacts/pom.xml new file mode 100644 index 000000000..ba996b819 --- /dev/null +++ b/controlloop/common/packages/artifacts/pom.xml @@ -0,0 +1,118 @@ +<!-- + ============LICENSE_START======================================================= + PDP-D Application Installation Packages + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>packages</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>artifacts</artifactId> + <packaging>pom</packaging> + + <name>Artifacts for PDP-D Applications</name> + <description>PDP-D models, rules and tooling</description> + + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>single</goal> + </goals> + <phase>package</phase> + <configuration> + <descriptors> + <descriptor>src/assembly/zip.xml</descriptor> + </descriptors> + <appendAssemblyId>false</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + + <!-- The following are placed in the local repository at installation --> + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>drools-pdp-apps</artifactId> + <version>${project.version}</version> + <type>pom</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>demo</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>rest</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>mso</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>trafficgenerator</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>archetype-closedloop-demo-rules</artifactId> + <version>${project.version}</version> + <type>jar</type> + </dependency> + </dependencies> + +</project> diff --git a/controlloop/common/packages/artifacts/src/assembly/zip.xml b/controlloop/common/packages/artifacts/src/assembly/zip.xml new file mode 100644 index 000000000..e3f018d26 --- /dev/null +++ b/controlloop/common/packages/artifacts/src/assembly/zip.xml @@ -0,0 +1,33 @@ +<!-- + ============LICENSE_START======================================================= + Artifacts for PDP-D Applications + ================================================================================ + 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========================================================= + --> + +<assembly> + <id>zipfile</id> + <formats> + <format>zip</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <dependencySets> + <dependencySet> + <outputDirectory>artifacts</outputDirectory> + <useTransitiveDependencies>false</useTransitiveDependencies> + </dependencySet> + </dependencySets> +</assembly> diff --git a/controlloop/common/packages/basex/pom.xml b/controlloop/common/packages/basex/pom.xml new file mode 100644 index 000000000..7e2014b86 --- /dev/null +++ b/controlloop/common/packages/basex/pom.xml @@ -0,0 +1,61 @@ +<!-- + ============LICENSE_START======================================================= + PDP-D Application Installation Packages + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>packages</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>basex</artifactId> + <packaging>pom</packaging> + + <name>PDP-D APPS Base Package</name> + <description>PDP-D APPS Packaging</description> + + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>single</goal> + </goals> + <phase>package</phase> + <configuration> + <descriptors> + <descriptor>src/assembly/zip.xml</descriptor> + </descriptors> + <appendAssemblyId>false</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> + diff --git a/controlloop/common/packages/basex/src/assembly/zip.xml b/controlloop/common/packages/basex/src/assembly/zip.xml new file mode 100644 index 000000000..a33f1b7e5 --- /dev/null +++ b/controlloop/common/packages/basex/src/assembly/zip.xml @@ -0,0 +1,36 @@ +<!-- + ============LICENSE_START======================================================= + PDP-D APPS Base Package + ================================================================================ + 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========================================================= + --> + +<assembly> + <id>basex</id> + <formats> + <format>tar.gz</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <fileSets> + <fileSet> + <directory>src/files</directory> + <outputDirectory>.</outputDirectory> + <fileMode>700</fileMode> + <directoryMode>700</directoryMode> + </fileSet> + </fileSets> +</assembly> + diff --git a/controlloop/common/packages/basex/src/files/bin/create-closed-loop-demo.sh b/controlloop/common/packages/basex/src/files/bin/create-closed-loop-demo.sh new file mode 100644 index 000000000..3cd191f03 --- /dev/null +++ b/controlloop/common/packages/basex/src/files/bin/create-closed-loop-demo.sh @@ -0,0 +1,315 @@ +#! /bin/bash + +### +# ============LICENSE_START======================================================= +# PDP-D APPS Base Package +# ================================================================================ +# 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========================================================= +### + +# Interactive script to generate a closed loop demo rules artifact +# for testing purposes of standalone PDP-D + +echo "Closed Loop Demo Creator for standalone PDP-D" +echo "----------------------------------------------" +echo + +GROUPID="org.openecomp.policy.demo.rules" +ARTIFACTID="closed-loop-demo-rules" +VERSION="1.1.0-SNAPSHOT" +PACKAGE="org.openecomp.policy.demo.rules" +CLOSEDLOOPCONTROLNAME="CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8" +POLICYSCOPE="service=test;resource=FRWL;type=configuration" +POLICYNAME="FirewallDemo" +POLICYVERSION="v0.0.1" +ACTOR="APPC" +APPCTOPIC="APPC-CL" +APPCSERVERS="vm1.mr.simpledemo.openecomp.org" +APPCAPIKEY= +APPCAPISECRET= +NOTIFICATIONTOPIC="POLICY-CL-MGT" +NOTIFICATIONSERVERS="vm1.mr.simpledemo.openecomp.org" +NOTIFICATIONAPIKEY= +NOTIFICATIONAPISECRET= +DCAETOPIC="DCAE-CL-EVENT" +DCAESERVERS="vm1.mr.simpledemo.openecomp.org" +DCAEAPIKEY= +DCAEAPISECRET= +AAIURL="http://localhost:7676/aai/test" +AAIUSERNAME="policy" +AAIPASSWORD="policy" +AAINAMEDQUERYUUID=d925ed73-8231-4d02-9545-db4e101fffff +AAIPATTERNMATCH=1 +MSOURL="http://localhost:7677/mso/test" +MSOUSERNAME="policy" +MSOPASSWORD="policy" + +read -e -i "${GROUPID}" -p "Closed Loop Rules Maven Group Id> " GROUP_ID +read -e -i "${ARTIFACTID}" -p "Closed Loop Rules Maven Coordinates Artifact Id> " ARTIFACTID +read -e -i "${VERSION}" -p "Closed Loop Rules Maven Coordinates Version> " VERSION +read -e -i "${PACKAGE}" -p "Closed Loop Rules Package> " PACKAGE +read -e -i "${CLOSEDLOOPCONTROLNAME}" -p "Closed Loop Template Control Name> " CLOSEDLOOPCONTROLNAME +read -e -i "${POLICYSCOPE}" -p "Closed Loop Policy Scope> " POLICYSCOPE +read -e -i "${POLICYNAME}" -p "Closed Loop Policy Name> " POLICYNAME +read -e -i "${POLICYVERSION}" -p "Closed Loop Policy Version> " POLICYVERSION +read -e -i "${ACTOR}" -p "Closed Loop Actor ('APPC' or 'MSO')> " ACTOR +read -e -i "${APPCTOPIC}" -p "Closed Loop APP-C Recipe Topic> " APPCTOPIC +read -e -i "${APPCSERVERS}" -p "Closed Loop APP-C UEB Servers for ${APPCTOPIC} topic> " APPCSERVERS +read -e -i "${APPCAPIKEY}" -p "Closed Loop APP-C UEB API Key for ${APPCTOPIC} topic> " APPCAPIKEY +read -e -i "${APPCAPISECRET}" -p "Closed Loop APP-C UEB API Secret for ${APPCTOPIC} topic> " APPCAPISECRET +read -e -i "${NOTIFICATIONTOPIC}" -p "Closed Loop Ruby Notification Topic> " NOTIFICATIONTOPIC +read -e -i "${NOTIFICATIONSERVERS}" -p "Closed Loop Ruby UEB Servers for ${NOTIFICATIONTOPIC} topic> " NOTIFICATIONSERVERS +read -e -i "${NOTIFICATIONAPIKEY}" -p "Closed Loop Ruby UEB API Key ${NOTIFICATIONTOPIC} topic> " NOTIFICATIONAPIKEY +read -e -i "${NOTIFICATIONAPISECRET}" -p "Closed Loop Ruby UEB API Secret ${NOTIFICATIONTOPIC} topic> " NOTIFICATIONAPISECRET +read -e -i "${DCAETOPIC}" -p "Closed Loop DCAE Topic> " DCAETOPIC +read -e -i "${DCAESERVERS}" -p "Closed Loop DCAE UEB Servers> " DCAESERVERS +read -e -i "${DCAEAPIKEY}" -p "Closed Loop DCAE UEB API Key for ${DCAETOPIC} topic> " DCAEAPIKEY +read -e -i "${DCAEAPISECRET}" -p "Closed Loop DCAE UEB API Secret for ${DCAETOPIC} topic> " DCAEAPISECRET +read -e -i "${AAIURL}" -p "Closed Loop AAI URL> " AAIURL +read -e -i "${AAIUSERNAME}" -p "Closed Loop AAI Username> " AAIUSERNAME +read -e -i "${AAIPASSWORD}" -p "Closed Loop AAI Password> " AAIPASSWORD +read -e -i "${AAINAMEDQUERYUUID}" -p "Closed Loop AAI Named Query UUID> " AAINAMEDQUERYUUID +read -e -i "${AAIPATTERNMATCH}" -p "Closed Loop AAI Pattern Match (1 for vFW, otherwise vDNS)> " AAIPATTERNMATCH +read -e -i "${MSOURL}" -p "Closed Loop MSO URL> " MSOURL +read -e -i "${MSOUSERNAME}" -p "Closed Loop MSO Username> " MSOUSERNAME +read -e -i "${MSOPASSWORD}" -p "Closed Loop MSO Password> " MSOPASSWORD + +echo +echo + +if [ -z "${GROUPID}" ]; then echo "Aborting: Closed Loop Rules Maven Group Id not provided"; exit 1; fi +if [ -z "${ARTIFACTID}" ]; then echo "Aborting: Closed Loop Rules Maven Coordinates Artifact Id not provided"; exit 1; fi +if [ -z "${VERSION}" ]; then echo "Aborting: Closed Loop Rules Maven Coordinates Version not provided"; exit 1; fi +if [ -z "${PACKAGE}" ]; then echo "Aborting: Closed Loop Rules Package not provided"; exit 1; fi +if [ -z "${CLOSEDLOOPCONTROLNAME}" ]; then echo "Aborting: Closed Loop Template Control Name not provided"; exit 1; fi +if [ -z "${POLICYSCOPE}" ]; then echo "Aborting: Closed Loop Template Policy Scope not provided"; exit 1; fi +if [ -z "${POLICYNAME}" ]; then echo "Aborting: Closed Loop Template Policy Name not provided"; exit 1; fi +if [ -z "${POLICYVERSION}" ]; then echo "Aborting: Closed Loop Template Policy Version not provided"; exit 1; fi +if [ -z "${ACTOR}" ]; then echo "Aborting: Closed Loop Template Actor not provided"; exit 1; fi +if [ -z "${APPCTOPIC}" ]; then echo "Aborting: Closed Loop Template APP-C Recipe Topic not provided"; exit 1; fi +if [ -z "${APPCSERVERS}" ]; then echo "Aborting: Closed Loop Template APP-C UEB Servers not provided"; exit 1; fi +if [ -z "${NOTIFICATIONTOPIC}" ]; then echo "Aborting: Closed Loop Template Ruby Notification Topic not provided"; exit 1; fi +if [ -z "${NOTIFICATIONSERVERS}" ]; then echo "Aborting: Closed Loop Template Ruby UEB Servers not provided"; exit 1; fi +if [ -z "${DCAETOPIC}" ]; then echo "Aborting: Closed Loop Template DCAE DMAAP Topic not provided"; exit 1; fi +if [ -z "${DCAESERVERS}" ]; then echo "Aborting: Closed Loop Template DCAE DMAAP Servers not provided"; exit 1; fi +if [ -z "${AAIURL}" ]; then echo "Aborting: Closed Loop Template AAI URL not provided"; exit 1; fi +if [ -z "${AAIUSERNAME}" ]; then echo "Aborting: Closed Loop Template AAI Username not provided"; exit 1; fi +if [ -z "${AAIPASSWORD}" ]; then echo "Aborting: Closed Loop Template AAI Password not provided"; exit 1; fi +if [ -z "${AAINAMEDQUERYUUID}" ]; then echo "Aborting: Closed Loop Template AAI Named Query UUID not provided"; exit 1; fi +if [ -z "${AAIPATTERNMATCH}" ]; then echo "Aborting: Closed Loop Template AAPI Pattern Match not provided"; exit 1; fi +if [ -z "${MSOURL}" ]; then echo "Aborting: Closed Loop Template MSO URL not provided"; exit 1; fi +if [ -z "${MSOUSERNAME}" ]; then echo "Aborting: Closed Loop Template MSO Username not provided"; exit 1; fi +if [ -z "${MSOPASSWORD}" ]; then echo "Aborting: Closed Loop Template MSO Password not provided"; exit 1; fi + +if [ -z "${DCAEAPIKEY}" ]; then DCAEAPIKEY="NULL"; fi +if [ -z "${DCAEAPISECRET}" ]; then DCAEAPISECRET="NULL"; fi +if [ -z "${APPCAPIKEY}" ]; then APPCAPIKEY="NULL"; fi +if [ -z "${APPCAPISECRET}" ]; then APPCAPISECRET="NULL"; fi +if [ -z "${NOTIFICATIONAPIKEY}" ]; then NOTIFICATIONAPIKEY="NULL"; fi +if [ -z "${NOTIFICATIONAPISECRET}" ]; then NOTIFICATIONAPISECRET="NULL"; fi + +if [[ "$VERSION" == *-SNAPSHOT ]]; then + DEPENDENCIES_VERSION="1.1.0-SNAPSHOT" +else + DEPENDENCIES_VERSION="${VERSION}" +fi + +read -e -i "${DEPENDENCIES_VERSION}" -p "Closed Loop Model/PDP-D dependent version(s) (ie: 1.0.0-SNAPSHOT, 1607.31.1-1, or [1607.31.1,)) > " DEPENDENCIES_VERSION +if [ -z "${DEPENDENCIES_VERSION}" ]; then echo "Aborting: Closed Loop Model/PDP-D dependencies not provided"; exit 1; fi + +echo "---------------------------------------------------------------------------------------" +echo "Please review the entered Closed Loop Maven Coordinates and Policy Template Parameters:" +echo +echo "Installation in Local Maven Repository" +echo +echo "Closed Loop Rules Maven Artifact Generation: Group Id: ${GROUP_ID}" +echo "Closed Loop Rules Maven Artifact Generation: Artifact Id: ${ARTIFACTID}" +echo "Closed Loop Rules Maven Artifact Generation: Version: ${VERSION}" +echo "Closed Loop Rules Maven Artifact Generation: Package: ${PACKAGE}" +echo +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Control Name: ${CLOSEDLOOPCONTROLNAME}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Policy Scope: ${POLICYSCOPE}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Policy Name: ${POLICYNAME}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Policy Version: ${POLICYVERSION}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Actor: ${ACTOR}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Recipe: ${APPC}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Recipe Topic: ${APPCTOPIC}" +echo "Closed Loop Template Drools DRL Expansion: Closed Loop Notification Topic: ${NOTIFICATIONTOPIC}" +echo +echo "Closed Loop Controller Configuration: Rules: Group Id: ${GROUP_ID}" +echo "Closed Loop Controller Configuration: Rules: Artifact Id: ${ARTIFACTID}" +echo "Closed Loop Controller Configuration: Rules: Version: ${VERSION}" +echo +echo "Closed Loop Controller Configuration: DCAE UEB Topic: ${DCAETOPIC}" +echo "Closed Loop Controller Configuration: DCAE UEB Servers: ${DCAESERVERS}" +echo "Closed Loop Controller Configuration: DCAE UEB API Key: ${DCAEAPIKEY}" +echo "Closed Loop Controller Configuration: DCAE UEB API Secret: ${DCAEAPISECRET}" +echo +echo "Closed Loop Controller Configuration: APP-C UEB Topic: ${APPCTOPIC}" +echo "Closed Loop Controller Configuration: APP-C UEB Servers: ${APPCSERVERS}" +echo "Closed Loop Controller Configuration: APP-C UEB API Key: ${APPCAPIKEY}" +echo "Closed Loop Controller Configuration: APP-C UEB API Secret: ${APPCAPISECRET}" +echo +echo "Closed Loop Controller Configuration: NOTIFICATION Topic: ${NOTIFICATIONTOPIC}" +echo "Closed Loop Controller Configuration: NOTIFICATION UEB Servers: ${NOTIFICATIONSERVERS}" +echo "Closed Loop Controller Configuration: NOTIFICATION UEB API Key: ${NOTIFICATIONAPIKEY}" +echo "Closed Loop Controller Configuration: NOTIFICATION UEB API Secret: ${NOTIFICATIONAPISECRET}" +echo +echo "Closed Loop Controller Configuration: AAI URL: ${AAIURL}" +echo "Closed Loop Controller Configuration: AAI Username: ${AAIUSERNAME}" +echo "Closed Loop Controller Configuration: AAI Password: ${AAIPASSWORD}" +echo "Closed Loop Controller Configuration: AAI Named Query UUID: ${AAINAMEDQUERYUUID}" +echo "Closed Loop Controller Configuration: AAI Pattern Match: ${AAIPATTERNMATCH}" +echo +echo "Closed Loop Controller Configuration: MSO URL: ${MSOURL}" +echo "Closed Loop Controller Configuration: MSO Username: ${MSOUSERNAME}" +echo "Closed Loop Controller Configuration: MSO Password: ${MSOPASSWORD}" +echo +echo "Closed Loop Model/PDP-D dependent version(s): ${DEPENDENCIES_VERSION}" +echo "---------------------------------------------------------------------------------------" +echo + +HAPPY="Y" +read -e -i "${HAPPY}" -p "Are the previous parameters correct (Y/N)? " HAPPY +if [[ ${HAPPY} != "Y" ]]; then + exit 1 +fi + +echo +DIR_TMP="/tmp" +echo "The Closed Loop Source Rules will be installed at ${DIR_TMP}" +read -e -i "${DIR_TMP}" -p "Do you want to change the Source Rules install directory? " DIR_TMP + +if [ ! -w "${DIR_TMP}" ]; then + echo "Aborting. ${DIR_TMP} is not writable" + exit 1 +fi + +ARCHETYPE_GROUP_ID="org.openecomp.policy.drools-applications" +ARCHETYPE_ARTIFACT_ID="archetype-closedloop-demo-rules" + +if [ -d "${DIR_TMP}/${ARTIFACTID}/" ]; then + if [ "$(ls -A "${DIR_TMP}/${ARTIFACTID}"/)" ]; then + echo "${DIR_TMP} already contains a ${ARTIFACTID}/ directory, saving it to ${DIR_TMP}/${ARTIFACTID}.arch.bak/" + if [ -d "${DIR_TMP}/${ARTIFACTID}.arch.bak"/ ]; then + ( + echo "${DIR_TMP}/${ARTIFACTID}.arch.bak/ also exists, deleting it .." + cd "${DIR_TMP}"/ + rm -fr "${ARTIFACTID}.arch.bak" + ) + fi + /bin/mv --force "${DIR_TMP}/${ARTIFACTID}/" "${DIR_TMP}/${ARTIFACTID}.arch.bak" + if [ "${?}" -ne 0 ]; then + echo + echo + echo "Aborting: ${DIR_TMP}/${ARTIFACTID}/ cannot be moved" + exit 1 + fi + else + ( cd "${DIR_TMP}/" ; rmdir "${DIR_TMP}/${ARTIFACTID}/" ) + fi +fi + +CREATEARTIFACT="Y" +read -e -i "${CREATEARTIFACT}" -p "Create Maven Artifact (Y/N)? " CREATEARTIFACT +if [[ ${CREATEARTIFACT} != "Y" ]]; then + exit 1 +fi + +( +cd "${DIR_TMP}" + +"$M2_HOME"/bin/mvn archetype:generate \ + -B \ + -DarchetypeCatalog=local \ + -DarchetypeGroupId="${ARCHETYPE_GROUP_ID}" \ + -DarchetypeArtifactId="${ARCHETYPE_ARTIFACT_ID}" \ + -DarchetypeVersion="${VERSION}" \ + -DgroupId="${GROUP_ID}" \ + -DartifactId="${ARTIFACTID}" \ + -Dversion="${VERSION}" \ + -Dpackage="${PACKAGE}" \ + -DclosedLoopControlName="${CLOSEDLOOPCONTROLNAME}" \ + -DpolicyScope="${POLICYSCOPE}" \ + -DpolicyName="${POLICYNAME}" \ + -DpolicyVersion="${POLICYVERSION}" \ + -Dactor="${ACTOR}" \ + -DappcTopic="${APPCTOPIC}" \ + -DappcServers="${APPCSERVERS}" \ + -DappcApiKey="${APPCAPIKEY}" \ + -DappcApiSecret="${APPCAPISECRET}" \ + -DnotificationTopic="${NOTIFICATIONTOPIC}" \ + -DnotificationServers="${NOTIFICATIONSERVERS}" \ + -DnotificationApiKey="${NOTIFICATIONAPIKEY}" \ + -DnotificationApiSecret="${NOTIFICATIONAPISECRET}" \ + -DdcaeTopic="${DCAETOPIC}" \ + -DdcaeServers="${DCAESERVERS}" \ + -DdcaeApiKey="${DCAEAPIKEY}" \ + -DdcaeApiSecret="${DCAEAPISECRET}" \ + -DaaiURL="${AAIURL}" \ + -DaaiUsername="${AAIUSERNAME}" \ + -DaaiPassword="${AAIPASSWORD}" \ + -DaaiNamedQueryUUID="${AAINAMEDQUERYUUID}" \ + -DaaiPatternMatch="${AAIPATTERNMATCH}" \ + -DmsoURL="${MSOURL}" \ + -DmsoUsername="${MSOUSERNAME}" \ + -DmsoPassword="${MSOPASSWORD}" \ + -DdependenciesVersion="${DEPENDENCIES_VERSION}" + +if [ "${?}" -ne 0 ]; then + echo + echo + echo "Aborting: ${ARTIFACTID} has not been successfully generated" + exit 1 +fi + +echo + +cd "${DIR_TMP}/${ARTIFACTID}"/ + +/bin/mv src/main/config/* . + +/bin/sed -i -e "/apiKey=NULL$/d" *-controller.properties +/bin/sed -i -e "/apiSecret=NULL$/d" *-controller.properties + +/bin/sed -i -e "/apiKey.*:.*\"NULL\",/d" *-controller.rest.json +/bin/sed -i -e "/apiSecret.*:.*\"NULL\",/d" *-controller.rest.json + +echo "Closed Loop Rules from templates have been successfully created under ${DIR_TMP}/${ARTIFACTID}/" + +INSTALLREPO="Y" +read -e -i "${INSTALLREPO}" -p "Do you want to deploy ${ARTIFACTID} rules into maven repository (Y/N)? " INSTALLREPO +if [[ ${INSTALLREPO} != "Y" ]]; then + exit 1 +fi + +echo +echo "generating deployable ${ARTIFACTID} maven artifact .." + +"$M2_HOME"/bin/mvn install + +if [ "${?}" -ne 0 ]; then + echo + echo + echo "Aborting: ${ARTIFACTID} deployable jar cannot be generated" + exit 1 +fi + + +echo +echo "${ARTIFACTID} has been successfully installed in user's (${USER}) local repository" +echo "Find configuration files at ${DIR_TMP}/${ARTIFACTID}/" +) diff --git a/controlloop/common/packages/basex/src/files/config/vDNS-controller.properties b/controlloop/common/packages/basex/src/files/config/vDNS-controller.properties new file mode 100644 index 000000000..951a0f9c4 --- /dev/null +++ b/controlloop/common/packages/basex/src/files/config/vDNS-controller.properties @@ -0,0 +1,55 @@ +### +# ============LICENSE_START======================================================= +# PDP-D APPS Base Package +# ================================================================================ +# 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========================================================= +### + +controller.name=vDNS + +ueb.source.topics=DCAE-CL-EVENT,APPC-CL + +ueb.source.topics.DCAE-CL-EVENT.servers=vm1.mr.simpledemo.openecomp.org +ueb.source.topics.DCAE-CL-EVENT.apiKey= +ueb.source.topics.DCAE-CL-EVENT.apiSecret= +ueb.source.topics.DCAE-CL-EVENT.events=org.openecomp.policy.controlloop.VirtualControlLoopEvent +ueb.source.topics.DCAE-CL-EVENT.events.org.openecomp.policy.controlloop.VirtualControlLoopEvent.filter=closedLoopEventStatus\=.*,closedLoopControlName\=.*DNS.* +ueb.source.topics.DCAE-CL-EVENT.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +ueb.source.topics.APPC-CL.servers=vm1.mr.simpledemo.openecomp.org +ueb.source.topics.APPC-CL.apiKey= +ueb.source.topics.APPC-CL.apiSecret= +ueb.source.topics.APPC-CL.events=org.openecomp.policy.appc.Response +ueb.source.topics.APPC-CL.events.org.openecomp.policy.appc.Response.filter=CommonHeader=.*,Status=.* +ueb.source.topics.APPC-CL.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics=APPC-CL,POLICY-CL-MGT + +ueb.sink.topics.APPC-CL.servers=vm1.mr.simpledemo.openecomp.org +ueb.sink.topics.APPC-CL.apiKey= +ueb.sink.topics.APPC-CL.apiSecret= +ueb.sink.topics.APPC-CL.events=org.openecomp.policy.appc.Request +ueb.sink.topics.APPC-CL.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics.POLICY-CL-MGT.servers=vm1.mr.simpledemo.openecomp.org +ueb.sink.topics.POLICY-CL-MGT.apiKey= +ueb.sink.topics.POLICY-CL-MGT.apiSecret= +ueb.sink.topics.POLICY-CL-MGT.events=org.openecomp.policy.controlloop.VirtualControlLoopNotification +ueb.sink.topics.POLICY-CL-MGT.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +rules.groupId= +rules.artifactId= +rules.version= diff --git a/controlloop/common/packages/basex/src/files/config/vFW-controller.properties b/controlloop/common/packages/basex/src/files/config/vFW-controller.properties new file mode 100644 index 000000000..558ba42e8 --- /dev/null +++ b/controlloop/common/packages/basex/src/files/config/vFW-controller.properties @@ -0,0 +1,55 @@ +### +# ============LICENSE_START======================================================= +# PDP-D APPS Base Package +# ================================================================================ +# 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========================================================= +### + +controller.name=vFW + +ueb.source.topics=DCAE-CL-EVENT,APPC-CL + +ueb.source.topics.DCAE-CL-EVENT.servers=vm1.mr.simpledemo.openecomp.org +ueb.source.topics.DCAE-CL-EVENT.apiKey= +ueb.source.topics.DCAE-CL-EVENT.apiSecret= +ueb.source.topics.DCAE-CL-EVENT.events=org.openecomp.policy.controlloop.VirtualControlLoopEvent +ueb.source.topics.DCAE-CL-EVENT.events.org.openecomp.policy.controlloop.VirtualControlLoopEvent.filter=closedLoopEventStatus\=.*,closedLoopControlName\=.*FRWL.* +ueb.source.topics.DCAE-CL-EVENT.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +ueb.source.topics.APPC-CL.servers=vm1.mr.simpledemo.openecomp.org +ueb.source.topics.APPC-CL.apiKey= +ueb.source.topics.APPC-CL.apiSecret= +ueb.source.topics.APPC-CL.events=org.openecomp.policy.appc.Response +ueb.source.topics.APPC-CL.events.org.openecomp.policy.appc.Response.filter=CommonHeader=.*,Status=.* +ueb.source.topics.APPC-CL.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics=APPC-CL,POLICY-CL-MGT + +ueb.sink.topics.APPC-CL.servers=vm1.mr.simpledemo.openecomp.org +ueb.sink.topics.APPC-CL.apiKey= +ueb.sink.topics.APPC-CL.apiSecret= +ueb.sink.topics.APPC-CL.events=org.openecomp.policy.appc.Request +ueb.sink.topics.APPC-CL.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics.POLICY-CL-MGT.servers=vm1.mr.simpledemo.openecomp.org +ueb.sink.topics.POLICY-CL-MGT.apiKey= +ueb.sink.topics.POLICY-CL-MGT.apiSecret= +ueb.sink.topics.POLICY-CL-MGT.events=org.openecomp.policy.controlloop.VirtualControlLoopNotification +ueb.sink.topics.POLICY-CL-MGT.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +rules.groupId= +rules.artifactId= +rules.version= diff --git a/controlloop/common/packages/pom.xml b/controlloop/common/packages/pom.xml new file mode 100644 index 000000000..ea54a3317 --- /dev/null +++ b/controlloop/common/packages/pom.xml @@ -0,0 +1,43 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>packages</artifactId> + <packaging>pom</packaging> + + <name>PDP-D Application Installation Packages</name> + <description>PDP-D Installation</description> + + <modules> + <module>basex</module> + <module>artifacts</module> + <module>apps</module> + </modules> +</project> diff --git a/controlloop/common/policy-yaml/README- v1.0.0.md b/controlloop/common/policy-yaml/README- v1.0.0.md new file mode 100644 index 000000000..3ef70dea9 --- /dev/null +++ b/controlloop/common/policy-yaml/README- v1.0.0.md @@ -0,0 +1,356 @@ +ECOMP Control Loop Policy + +A control loop policy is a YAML specification for creating and chaining policies for ControlLoop. + +1610 ECOMP Control Loop Policy Features: + +* A single DCAE Closed Loop Event is the trigger for the overall Control Loop Policy +* APPC is the only Actor that Policy will interact with. The operations available are: RESTART, REBUILD, MIGRATE. +* An overall timeout for the Control Loop Policy must be provided +* The Control Loop Policy can contain zero or more Operational Policies each chained together via outcomes of each policy. +* If there are zero Operational Policies, i.e. no automated action is to be taken, then the policy is an Open Loop policy. +* Operational Policies can have retries and timeout's given to control how they are processed. + +This SDK helps build the YAML specification for 1610 ECOMP Control Loop Polices. + +# Create Builder Object + +To begin with, the ControlLoopPolicyBuilder.Factory class has static methods that one should use to begin building a Control Loop Policy. It will return a [ControlLoopPolicyBuilder object](src/main/java/com/att/ecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java) that can then be used to continue to build and define the Control Loop Policy. + +```java + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( + UUID.randomUUID().toString(), + 2400, + new Resource("vCTS", ResourceType.VF), + new Service("vUSP") + ); +``` + +# Define the Trigger Policy + +After the name of the Control Loop and the resource and services have been defined, the next step would be to define the Operation Policy that is first to respond to an incoming DCAE Closed Loop Event. Use the setTriggerPolicy() method to do so. + +```java + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + Actor.APPC, + Target.VM, + "Restart", + 2, + 300); +``` + +# Chain Operational Policies Together Using Operational Results + +Operational Policies are chained together using the results of each Operational Policy. The results are defined in [PolicyResult.java](src/main/java/com/att/ecomp/policy/controlloop/policy/PolicyResult.java). To create an Operational Policy that is tied to the result of another, use the +setPolicyForPolicyResult() method. + +```java + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + Actor.APPC, + Target.VM, + "Rebuild", + 1, + 600, + triggerPolicy.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); +``` + +An Operational Policy MUST have place to go for every one of its results. By default, each result type goes to a Final Result. Optionally, using the setPolicyForPolicyResult() method is what allows the chaining of policies. Be aware of creating loops and set the overall Control Loop timeout to reasonable value. All paths MUST lead to a Final Result. + +# Build the YAML Specification + +When finished defining the Policies, build the specification and analyze the [Results.java](src/main/java/com/att/ecomp/policy/controlloop/policy/builder/Results.java) + +```java + Results results = builder.buildSpecification(); + if (results.isValid()) { + System.out.println(results.getSpecification()); + } else { + System.err.println("Builder failed"); + for (Message message : results.getMessages()) { + System.err.println(message.getMessage()); + } + } +``` + +# Sample Code + +Sample code is available in this project: https://codecloud.web.att.com/projects/ST_POLICY/repos/com.att.ecomp.policy.controlloop.sample/browse + + + +# Use the YAML Specification to call the Create Policy API + +Now that you have a valid YAML specification, call the createPolicy API via the ECOMP Policy Platform API. + +# YAML Specification + +The YAML specification has 2 sections to it: [controlLoop](#controlloop-object) and [policies](#policies-array). The [controlLoop section](#controlloop-object) section is simply a header defining the Control Loop Policy, what services its for, which resource its for, or if its for a pnf, the overall timeout, and which Operational Policy is triggered upon receiving the event. The [policies section](#policies-array) is simply an array of [Policy Objects](#policy-object). + +## controlLoop Object + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| controlLoopName | string | required | Unique ID for the control Loop | +| version | string | required | Value for this release if 1.0.0 | +| services | array of [service](#service-object) objects | optional | Zero or more services associated with this Control Loop | +| resources | array of [resource](#resource-object) object | required (If NOT a pnf control loop) | The resource's associated with this Control Loop. | +| pnf | [pnf](#pnf-object) object | required (If NOT a resource control loop) | The physical network function associated with this Control Loop. | +| trigger_policy | string | required | Either this is the ID of an Operation Policy (see policy object), or "Final_OpenLoop" indicating an Open Loop | +| timeout | int | required | This is the overall timeout for the Control Loop Policy. It can be 0 for an Open Loop, but otherwise should total more than the timeouts specified in any Operational Policies | + +### resource Object + +This object was derived via ASDC Catalog API and ASDC Data Dictionary (POC) in an attempt to use common naming conventions. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| resourceInvariantUUID | string - UUID | optional | via ASDC, the unique ID for the resource version | +| resourceName | string | required if NO resourceUUID available | Name of the resource, ideally from ASDC catalog. But if not available, use well-known name. | +| resourceType | string | optional | Use values defined by ASDC: VF, VFC, VL, CP. | +| resourceUUID | string - UUID | required IF available, else populate resourceName | Unique ID for the resource as assigned via ASDC. +| resourceVersion | string | optional | string version of the resource via ASDC catalog + +Given in 1610 the ASDC catalog is not fully available and resources have not been defined yet, use resourceName. Eg. F5FW + +### service Object + +This object was derived via ASDC Catalog API and ASDC Data Dictionary (POC) in an attempt to use common naming conventions. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| serviceInvariantUUID | string - UUID | optional | via ASDC catalog, the unique ID for the service version | +| serviceName | string | required if NO serviceUUID available | Name of the service, ideally from ASDC catalog. But if not available, use well-known name. | +| serviceUUID | string - UUID | required IF available, else populate serviceName | Unique ID fort he service as assigned via ASDC +| serviceVersion | string | optional | string version of the service via ASDC catalog + +Given in 1610 the ASDC catalog is not fully available and some services have not been defined yet, use resourceName. Eg. vUSP, vSCP, trinity. + +### pnf Object + +This object is used for a physical network function. In the case of 1610, eNodeB is the use case supported. Expect this object to change in the future when ECOMP Policy fully integrates with A&AI. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| PNFName | string | required | Name of the PNF. Should be supplied via A&AI. If not available use a well-known name. | +| PNFType | string | optional | Type of PNF if available. | + + +## policies array + +The policies section is an array of [Policy objects](#policy-object). + +### Policy Object + +This is an Operation Policy. It is used to instruct an actor (eg. APPC) to invoke a recipe (eg. "Restart") on a target entity (eg. a "VM"). For 1610, there are 2 actors: APPC and RAN. An operation is simply defined as performing a recipe (or operation) on an actor. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| id | string | required | Unique ID for the policy. +| name | string | required | Policy name | +| description | string | optional | Policy description | +| actor | string | required | Name of the actor for this operation: Example: APPC | +| recipe | string | required | Name of recipe to be performed. Example "Restart" | +| target | string | required | Entity being targeted. Example: VM | +| timeout | int | required | Timeout for the actor to perform the recipe. | +| retry | int | optional | Optional number of retries for ECOMP Policy to invoke the recipe on the actor. | +| success | string | required | By default, this value should be FINAL_SUCCESS. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon successfully completing the recipe on the actor. +| failure | string | required | By default, this value should be FINAL_FAILURE. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon failure to perform the operation. | +| failure_exception | string | required | By default, this value should be FINAL_FAILURE_EXCEPTION. Otherwise this can be the ID of an Operational Policy (included in this specification) to invoke upon an exception occurring while attempting to perform the operation. | +| failure_retries | string | required | By default, this value should be the FINAL_FAILURE_RETRIES. Otherwise this can be the ID of an Operational Policy (included in this specification) to invoke upon maxing out on retries while attempting to perform the operation. | +| failure_timeout | string | required | By default, this value should be FINAL_FAILURE_TIMEOUT. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon a timeout occuring while performing an operation. | + +Every Operational Policy MUST have a place to go for every possible result (success, failure, failure_retries, failure_timeout, failure_exception). By default, all the results are final results. + +## Examples of YAML Control Loops for 1610 + +[1607-F5](src/test/resources/v1.0.0/policy_vSCP_F5_1610.yaml) +[1610-vUSP](src/test/resources/v1.0.0/policy_vUSP_1610.yaml) +[1610-Open-Loop](src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml) +[1610-vProbes](src/test/resources/v1.0.0/policy_vProbes_1610.yaml) +[VNF-with-Multiple-Services](src/test/resources/v1.0.0/policy_Test_MultipleService.yaml) + +### 1607 F5 +``` +controlLoop: + version: 1.0.0 + controlLoopName: ClosedLoop-FRWL-SIG-d925ed73-8231-4d02-9545-db4e101f88f8 + services: + - serviceName: vSCP + - serviceName: trinity + resources: + - resourceName: F5FW + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + +``` + +### 1610 vUSP +``` +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: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: 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: VM + retry: 0 + timeout: 600 + success: final_success + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: 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: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + +``` + +### 1610 Open Loop +``` +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-Open-fac4ae3d-c3f5-4bab-8e54-0a8581ede132 + services: + - serviceName: Service + resources: + - resourceType: VF + resourceName: Example + trigger_policy: final_openloop + timeout: 0 + +policies: +``` + +### 1610 vProbes +``` +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-vProbes-41aba939-9a93-4535-b193-973c68fc8763 + services: + resources: + - resourceName: vProbes + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 600 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + +``` + +### VNF with Multiple Services +``` +controlLoop: + version: 1.0.0 + controlLoopName: ClosedLoop-FRWL-SIG-d925ed73-8231-4d02-9545-db4e101f88f8 + services: + - serviceName: vSCP + - serviceName: vSBG + resources: + - resourceName: F5FW + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + +``` + + +# Control Loop Final Results Explained + +A Control Loop Policy has the following set of final results, as defined in [FinalResult.java](src/main/java/com/att/ecomp/policy/controlloop/policy/FinalResult.java). A final result indicates when a Control Loop Policy has finished execution and is finished processing a Closed Loop Event. All paths must lead to a Final Result. + diff --git a/controlloop/common/policy-yaml/README-guard-v2.0.0.md b/controlloop/common/policy-yaml/README-guard-v2.0.0.md new file mode 100644 index 000000000..e0416f486 --- /dev/null +++ b/controlloop/common/policy-yaml/README-guard-v2.0.0.md @@ -0,0 +1,206 @@ +ECOMP Control Loop Guard + +A control loop guard is a YAML specification for creating policy guard for ControlLoop. + +1707 ECOMP Control Loop Guard Features: + +* The Control Loop Guard can specify the frequency limiter and the blacklist of target entities but not both in the same Guard. +* Two parts are incorporated. One is the common guard header including guard version while the other part is a set of guard policies. +* The Control Loop Guard should contain at least one guard policies. +* Each guard policy is bound to a specific Actor and Recipe. +* Each guard policy should have at least one limit constraints which define how the guard policy should be enforced. +* Supported Actors are APPC, MSO, SDNO, SDNR and AOTS. + +This SDK helps build the YAML specification for 1707 ECOMP Control Loop Guard. + +# Create Builder Object + +To begin with, the ControlLoopGuardBuilder.Factory class has static methods that one should use to begin building a Control Loop Guard. It will return a [ControlLoopGuardBuilder object](src/main/java/com/att/ecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java) that can then be used to continue to build and define the Control Loop Guard. + +```java + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); +``` + +# Add Guard Policy + +After a guard builder has been created, the next step would be to add a guard policy to the newly created Control Loop Guard via the builder. To add a guard policy, use the addGuardPolicy() method. + +```java + GuardPolicy policy = new GuardPolicy( + "unique_guard_vUSP_1", + "APPC 5 Restart", + "We only allow 5 restarts over 15 minute window during the day time hours (i.e. avoid midnight to 5am)", + "APPC", + "Restart"); + builder = builder.addGuardPolicy(policy); +``` + +# Add Limit Constraint to a Guard Policy + +The limit constraint defines the details of how to enforce the guard policy. Each limit constraint can contain two types of constraints - frequency limiter and black list. At least one type of constraints should be specified, otherwise the limit constraint will be counted as invalid. To add a limit constraint to an existing guard policy, use the addLimitConstraint() method. + +```java + Map<String, String> time_in_range = new HashMap<String, String>(); + time_in_range.put("arg2", "PT5H"); + time_in_range.put("arg3", "PT24H"); + List<String> blacklist = new LinkedList<String>(); + blacklist.add("vm_name_1"); + blacklist.add("vm_name_2"); + Constraint cons = new Constraint(5, "PT15M", time_in_range, blacklist); + builder = builder.addLimitConstraint(policy.id, cons); +``` + + +# Build the YAML Specification + +When finished defining the Guard Policies, build the specification and analyze the [Results.java](src/main/java/com/att/ecomp/policy/controlloop/policy/builder/Results.java) + +```java + Results results = builder.buildSpecification(); + if (results.isValid()) { + System.out.println(results.getSpecification()); + } else { + System.err.println("Builder failed"); + for (Message message : results.getMessages()) { + System.err.println(message.getMessage()); + } + } +``` + +# Sample Code + +Sample code is available in this project: https://codecloud.web.att.com/projects/ST_POLICY/repos/com.att.ecomp.policy.controlloop.sample/browse + + + +# Use the YAML Specification to Generate the XACML Guard Policies + +Now that you have a valid YAML specification, call the method in [PolicyGuardYamlToXacml.java](guard/src/main/java/com/att/ecomp/policy/guard/PolicyGuardYamlToXacml.java) to generate the XACML Guard Policies. + +# YAML Specification + +The YAML specification has 2 sections to it: [guard](#guard-object) and [guards](#guards-array). The [guard section](#guard-object) section is simply a header defining the version of this guard. The [guards section](#guards-array) is simply an array of [GuardPolicy objects](#guardpolicy-object). + +## guard Object + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| version | string | required | Value for this release if 2.0.0 | + + +## guards array + +The guards section is an array of [GuardPolicy objects](#guardpolicy-object). + +### GuardPolicy Object + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| id | string | required | Unique ID for the policy. | +| name | string | required | Policy name | +| description | string | optional | Policy description | +| actor | string | required | Name of the actor for this operation: Example: APPC | +| recipe | string | required | Name of recipe to be performed. Example "Restart" | +| limit_constraints | array of [constraint](#constraint-object) object | required | Constraints used to enforce the guard policy | + +The guard policy is bound to a specific recipe performed by the actor. When the Control Loop tries to perform the recipe operation by the actor, this guard policy should be evaluated against all the specified constraints. If any of the constraints will be violated, the operation should be abandoned. + +#### constraint Object + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| num | integer | required if blacklist is not specified | The limited number of the same operations | +| duration | string | required if blacklist is not specified | Time window for counting the same operations | +| time_in_range | map<string, string> | optional | Valid time spans for enforcing the guard policy | +| blacklist | array of string | required if num and duration are not specified | A list of the entity names that should not be touched by the Control Loop | + +The first three attributes define the frequency limiter which means that only a limited number of the same operations can be allowed within each valid time window. The last attribute defines a blacklist of the target entities on which the Control Loop should not perform the operation. + +The "duration" parameter should have one of the following values: [5min, 10min, 30min, 1h, 12h, 1d, 5d, 1w, 1mon]. + + +## Examples of YAML Control Loop Guards for 1707 + +[1707-vUSP-Guard](src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml) +[1707-eNodeB-Ericsson-Frequency-Limiter-Guard](template.enodeb/src/test/resources/policy_guard_eNodeB_1707_sdnr_reset.yaml) +[1707-eNodeB-Ericsson-Blacklist-Guard](template.enodeb/src/test/resources/policy_guard_vUSP_1707_sdnr_reset_blacklist.yaml) +[OpenECOMP-vDNS-Guard](src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml) + + +### 1707 vUSP Guard +``` +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 + duration: PT15M + time_in_range: + arg2: PT5H + arg3: PT24H +``` + +### 1707 eNodeB Ericsson Frequency Limiter Guard +``` +guard: + version: 2.0.0 + +guards: + - id: unique_guard_eNodeB_Ericsson + name: SDNR 1 Reset + description: | + We only allow 1 reset over 24 hour window + actor: SDNR + recipe: Reset + limit_constraints: + - num: 100 + duration: 1d + time_in_range: + arg2: 00:00:00-05:00 + arg3: 23:59:59-05:00 +``` + +### 1707 eNodeB Ericsson Blacklist Guard +``` +guard: + version: 2.0.0 + +guards: + - id: unique_guard_eNodeB_Ericsson_Blacklist + name: SDNR Reset Blacklist + description: | + We deny restart of the blacklisted targets (avoid midnight to 5am) + actor: APPC + recipe: Reset + limit_constraints: + - blacklist: + - HNVJAL22_DMH1_U_L + - MNYKAQ35_DMH1_U_L + time_in_range: + arg2: 00:00:00-05:00 + arg3: 23:59:59-05:00 +``` + +### OpenECOMP vDNS Guard +``` +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/README-v2.0.0.md b/controlloop/common/policy-yaml/README-v2.0.0.md new file mode 100644 index 000000000..eadaf658a --- /dev/null +++ b/controlloop/common/policy-yaml/README-v2.0.0.md @@ -0,0 +1,569 @@ +ECOMP Control Loop Policy v2.0.0 + +A control loop policy is a YAML specification for creating and chaining policies for ControlLoop. + +1707 ECOMP Control Loop Policy Features: + +* Backward compatible with 1610 ECOMP Control Loop Policy +* A single DCAE Closed Loop Event is the trigger for the overall Control Loop Policy. +* An overall timeout for the Control Loop Policy must be provided. +* An abatement flag indicating whether Policy will receive abatement event for the Control Loop could be provided. +* The Control Loop Policy can contain zero or more Operational Policies each chained together via outcomes of each policy. +* If there are zero Operational Policies, i.e. no automated action is to be taken, then the policy is an Open Loop policy. +* Operational policies can have target, retries and timeout's given to control how they are processed. +* Type and resourceID of the target could be provided to support the target in operational policies. +* Payload could be provided to support the recipe. +* Multiple actors along with their supported recipes can be specified in operational policies that Policy will interact with. The following table summarizes the supported actors and recipes. + +| Actor | Recipe | Target | Payload | +| -------------|:---------------------------:| ---------| ------------:| +| APPC | Restart | VM | AICVServerSelfLink, AICIdentity | +| APPC | Rebuild | VM | AICVServerSelfLink, AICIdentity | +| APPC | Migrate | VM | AICVServerSelfLink, AICIdentity | +| APPC | ModifyConfig | VFC | generic-vnf.vnf-id | +| MSO | VF Module Create | VFC | optional | +| SDNO | health-diagnostic-type | VM | health-diagnostic-code, health-diagnostic-code-parameters | +| SDNO | health-diagnostic | VM | optional | +| SDNO | health-diagnostic-history | VM | optional | +| SDNO | health-diagnostic-commands | VM | optional | +| SDNO | health-diagnostic-aes | VM | optional | +| SDNR | Reset | PNF | optional | +| AOTS | checkMaintenanceWindow | VM | optional | +| AOTS | checkENodeBTicketHours | VM | timeWindow | +| AOTS | checkEquipmentStatus | VM | optional | +| AOTS | checkEimStatus | VM | optional | + + + +This SDK helps build the YAML specification for 1707 ECOMP Control Loop Polices. + +# Create Builder Object + +To begin with, the ControlLoopPolicyBuilder.Factory class has static methods that one should use to begin building a Control Loop Policy. It will return a [ControlLoopPolicyBuilder object](src/main/java/com/att/ecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java) that can then be used to continue to build and define the Control Loop Policy. + +```java + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( + UUID.randomUUID().toString(), + 2400, + new Resource("vCTS", ResourceType.VF), + new Service("vUSP") + ); +``` + +# Define the Trigger Policy + +After the name of the Control Loop and the resource and services have been defined, the next step would be to define the Operation Policy that is first to respond to an incoming DCAE Closed Loop Event. Use the setTriggerPolicy() method to do so. + +```java + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); +``` + +# Set the Abatement Flag for the Control Loop + +After the trigger policy, the name, the resource(s) and services of the Control Loop have been defined, the next optional step would be to set the abatement flag that indicates whether DCAE will send Policy the abatement event for this Control Loop. If the abatement is not explicitly set, it is assumed that Policy will not receive the abatement event. Use the setAbatement() method to do so. + +```java + builder = builder.setAbatement(false); +``` + +# Chain Operational Policies Together Using Operational Results + +Operational Policies are chained together using the results of each Operational Policy. The results are defined in [PolicyResult.java](src/main/java/com/att/ecomp/policy/controlloop/policy/PolicyResult.java). To create an Operational Policy that is tied to the result of another, use the +setPolicyForPolicyResult() method. + +```java + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + triggerPolicy.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT, + PolicyResult.FAILURE_GUARD); +``` + +An Operational Policy MUST have place to go for every one of its results. By default, each result type goes to a Final Result. Optionally, using the setPolicyForPolicyResult() method is what allows the chaining of policies. Be aware of creating loops and set the overall Control Loop timeout to reasonable value. All paths MUST lead to a Final Result. + + + +# Build the YAML Specification + +When finished defining the Policies, build the specification and analyze the [Results.java](src/main/java/com/att/ecomp/policy/controlloop/policy/builder/Results.java) + +```java + Results results = builder.buildSpecification(); + if (results.isValid()) { + System.out.println(results.getSpecification()); + } else { + System.err.println("Builder failed"); + for (Message message : results.getMessages()) { + System.err.println(message.getMessage()); + } + } +``` + +# Sample Code + +Sample code is available in this project: https://codecloud.web.att.com/projects/ST_POLICY/repos/com.att.ecomp.policy.controlloop.sample/browse + + + +# Use the YAML Specification to call the Create Policy API + +Now that you have a valid YAML specification, call the createPolicy API via the ECOMP Policy Platform API. + + +# YAML Specification + +The YAML specification has 2 sections to it: [controlLoop](#controlloop-object) and [policies](#policies-array). The [controlLoop section](#controlloop-object) section is simply a header defining the Control Loop Policy, what services its for, which resource its for, or if its for a pnf, the overall timeout, the abatement flag, and which Operational Policy is triggered upon receiving the event. The [policies section](#policies-array) is simply an array of [Policy Objects](#policy-object). + +## controlLoop Object + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| controlLoopName | string | required | Unique ID for the control Loop | +| version | string | required | Value for this release if 1.0.0 | +| services | array of [service](#service-object) objects | optional | Zero or more services associated with this Control Loop | +| resources | array of [resource](#resource-object) object | required (If NOT a pnf control loop) | The resource's associated with this Control Loop. | +| pnf | [pnf](#pnf-object) object | required (If NOT a resource control loop) | The physical network function associated with this Control Loop. | +| trigger_policy | string | required | Either this is the ID of an Operation Policy (see policy object), or "Final_OpenLoop" indicating an Open Loop | +| timeout | int | required | This is the overall timeout for the Control Loop Policy. It can be 0 for an Open Loop, but otherwise should total more than the timeouts specified in any Operational Policies | +| abatement | boolean | optional | This is an abatement flag indicating if DCAE will send abatement event to Policy for this Control Loop | + +### resource Object + +This object was derived via ASDC Catalog API and ASDC Data Dictionary (POC) in an attempt to use common naming conventions. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| resourceInvariantUUID | string - UUID | optional | via ASDC, the unique ID for the resource version | +| resourceName | string | required if NO resourceUUID available | Name of the resource, ideally from ASDC catalog. But if not available, use well-known name. | +| resourceType | string | optional | Use values defined by ASDC: VF, VFC, VL, CP. | +| resourceUUID | string - UUID | required IF available, else populate resourceName | Unique ID for the resource as assigned via ASDC. +| resourceVersion | string | optional | string version of the resource via ASDC catalog + + +### service Object + +This object was derived via ASDC Catalog API and ASDC Data Dictionary (POC) in an attempt to use common naming conventions. + +| Field Name | Type | Required | Description | +| ---------------:| -------------:| ----------:| ------------:| +| serviceInvariantUUID | string - UUID | optional | via ASDC catalog, the unique ID for the service version | +| serviceName | string | required if NO serviceUUID available | Name of the service, ideally from ASDC catalog. But if not available, use well-known name. | +| serviceUUID | string - UUID | required IF available, else populate serviceName | Unique ID fort he service as assigned via ASDC +| serviceVersion | string | optional | string version of the service via ASDC catalog + + +### pnf Object + +This object is used for a physical network function. In the case of 1707, eNodeB is the use case supported. Expect this object to change in the future when ECOMP Policy fully integrates with A&AI. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| PNFName | string | required | Name of the PNF. Should be supplied via A&AI. If not available use a well-known name. | +| PNFType | string | optional | Type of PNF if available. | + + +## policies array + +The policies section is an array of [Policy objects](#policy-object). + +### Policy Object + +This is an Operation Policy. It is used to instruct an actor (eg. APPC) to invoke a recipe (eg. "Restart") on a target entity (eg. a "VM"). For 1707, there are 5 actors: APPC, MSO, SDNO, SDNR and AOTS. An operation is simply defined as performing a recipe (or operation) on an actor. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| id | string | required | Unique ID for the policy. +| name | string | required | Policy name | +| description | string | optional | Policy description | +| actor | string | required | Name of the actor for this operation: Example: APPC | +| recipe | string | required | Name of recipe to be performed. Example "Restart" | +| target | [target](#target-object) object | required | Entity being targeted. Example: VM | +| timeout | int | required | Timeout for the actor to perform the recipe. | +| retry | int | optional | Optional number of retries for ECOMP Policy to invoke the recipe on the actor. | +| success | string | required | By default, this value should be FINAL_SUCCESS. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon successfully completing the recipe on the actor. +| failure | string | required | By default, this value should be FINAL_FAILURE. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon failure to perform the operation. | +| failure_exception | string | required | By default, this value should be FINAL_FAILURE_EXCEPTION. Otherwise this can be the ID of an Operational Policy (included in this specification) to invoke upon an exception occurring while attempting to perform the operation. | +| failure_retries | string | required | By default, this value should be the FINAL_FAILURE_RETRIES. Otherwise this can be the ID of an Operational Policy (included in this specification) to invoke upon maxing out on retries while attempting to perform the operation. | +| failure_timeout | string | required | By default, this value should be FINAL_FAILURE_TIMEOUT. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon a timeout occuring while performing an operation. | +| failure_guard | string | required | By default, this value should be FINAL_FAILURE_GUARD. Otherwise this can be the ID of the operational Policy (included in this specification) to invoke upon Guard denies this operation. | + +Every Operational Policy MUST have a place to go for every possible result (success, failure, failure_retries, failure_timeout, failure_exception, failure_guard). By default, all the results are final results. + +#### target Object + +This object is used for defining a target entity of a recipe. + +| Field Name | Type | Required | Description | +| ------------- |:-------------:| -----------| ------------:| +| type | enums of VM, PNF and VNC | required | Type of the target. | +| resourceID | string | optional | Resource ID of the target. Should be supplied via ASDC Catalog. | + + +## Examples of YAML Control Loops for 1707 + +[1707-vUSP](src/test/resources/v2.0.0/policy_vUSP_1707.yaml) +[1707-eNodeB-Ericsson](src/test/resources/v2.0.0/policy_eNodeB_Ericsson_1707.yaml) +[1707-eNodeB-ALU](src/test/resources/v2.0.0/policy_eNodeB_ALU_1707.yaml) +[OpenECOMP-vFirewall](src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml) +[OpenECOMP-vDNS](src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml) + +### 1707 vUSP +``` +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vUSP-vCTS-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: vUSP + resources: + - resourceName: vCTS + resourceType: VFC + - resourceName: vCOM + resourceType: VFC + - resourceName: vRAR + resourceType: VFC + - resourceName: vLCS + resourceType: VFC + - resourceName: v3CB + resourceType: VFC + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + abatement: false + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: + type: VM + retry: 2 + timeout: 300 + success: unique-policy-id-1-healthdiagnostic + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + failure_guard: unique-policy-id-2-rebuild + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: + type: VM + retry: 0 + timeout: 600 + success: unique-policy-id-2-healthdiagnostic + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: unique-policy-id-3-migrate + failure_exception: final_failure_exception + failure_guard: unique-policy-id-3-migrate + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-1-healthdiagnostic + name: Do SDNO Health Diagnostic + description: + actor: SDNO + recipe: health-diagnostic + payload: + health-diagnostic-code: HC99 + health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + failure_guard: unique-policy-id-2-rebuild + + - id: unique-policy-id-2-healthdiagnostic + name: Do SDNO Health Diagnostic + description: + actor: SDNO + recipe: health-diagnostic + payload: + health-diagnostic-code: HC99 + health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard +``` + +### 1707 eNodeB Ericsson +``` +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-eNodeB-Ericsson-0732e76a-4228-42d1-8185-972510be388c + services: + resources: + pnf: + PNFName: eNodeB.Ericsson + trigger_policy: unique-policy-id-1-check-aots-ticket + timeout: 2400 + +policies: + - id: unique-policy-id-1-check-aots-ticket + name: Check AOTS CTS + description: Discard sleeping cell based on the new signature if it appears in recent CTS tickets + actor: AOTS + recipe: checkENodeBTicketHours + payload: + timeWindow: 5 + retry: 2 + timeout: 300 + success: unique-policy-id-2-check-aots-cts + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-2-check-aots-cts + name: Check AOTS CTS Equipment + description: Discard sleeping cell based on the new signature if it is not active in CTS equipment data + actor: AOTS + recipe: checkEquipmentStatus + payload: + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-eim + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-3-check-aots-eim + name: Check AOTS EIM_RT + description: Discard sleeping cell based on the new signature if it appears in EIM_RT data + actor: AOTS + recipe: checkEimStatus + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-maintenance + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-4-check-aots-maintenance + name: Check AOTS MAINTENANCE + description: Discard sleeping cell based on the new signature if it appears in Maintenance + actor: AOTS + recipe: checkMaintenanceWindow + retry: 2 + timeout: 300 + success: unique-policy-id-5-sdnr-reset + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-5-sdnr-reset + name: Have SDNR Reset + description: SDNR should now reset this sleeper + actor: SDNR + recipe: Reset + operationsAccumulateParams: + period: 15m + limit: 5 + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard +``` + +### 1707 eNodeB ALU +``` +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-eNodeB-ALU-3ee91181-6f05-4cd3-8437-cad5f58653ca + services: + resources: + pnf: + PNFName: eNodeB.ALU + trigger_policy: unique-policy-id-1-check-aots + timeout: 2400 + +policies: + - id: unique-policy-id-1-check-aots + name: Check AOTS CTS + description: Discard sleeping cell based on the new signature if it appears in recent CTS tickets + actor: AOTS + recipe: checkENodeBTicketHours + payload: + timeWindow: 5 + retry: 2 + timeout: 300 + success: unique-policy-id-2-check-aots-cts + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-2-check-aots-cts + name: Check AOTS CTS Equipment + description: Discard sleeping cell based on the new signature if it is not active in CTS equipment data + actor: AOTS + recipe: checkEquipmentStatus + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-eim + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-3-check-aots-eim + name: Check AOTS EIM_RT + description: Discard sleeping cell based on the new signature if it appears in EIM_RT data + actor: AOTS + recipe: checkEimStatus + retry: 2 + timeout: 300 + success: unique-policy-id-4-sdnr-reset + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-4-sdnr-reset + name: Have SDNR Reset + description: SDNR should now reset this sleeper + actor: SDNR + recipe: Reset + operationsAccumulateParams: + period: 15m + limit: 5 + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard +``` + +### OpenECOMP vFirewall +``` +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a + services: + - serviceInvariantUUID: 5cfe6f4a-41bc-4247-8674-ebd4b98e35cc + serviceUUID: 0f40bba5-986e-4b3c-803f-ddd1b7b25f24 + serviceName: 57e66ea7-0ed6-45c7-970f + trigger_policy: unique-policy-id-1-modifyConfig + timeout: 1200 + +policies: + - id: unique-policy-id-1-modifyConfig + name: Change the Load Balancer + description: + actor: APPC + recipe: ModifyConfig + target: + resourceID: Eace933104d443b496b8.nodes.heat.vpg + payload: + generic-vnf.vnf-id: {generic-vnf.vnf-id} + ref$: pgstreams.json + retry: 0 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard +``` + +### OpenECOMP vDNS +``` +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3 + services: + - serviceName: d4738992-6497-4dca-9db9 + serviceInvariantUUID: dc112d6e-7e73-4777-9c6f-1a7fb5fd1b6f + serviceUUID: 2eea06c6-e1d3-4c3a-b9c4-478c506eeedf + trigger_policy: unique-policy-id-1-scale-up + timeout: 1200 + +policies: + - id: unique-policy-id-1-scale-up + name: Create a new VF Module + description: + actor: MSO + recipe: VF Module Create + target: + resourceID: 59a2ee3fB58045feB5a1.nodes.heat.vdns + retry: 0 + timeout: 1200 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard +``` + + +# Control Loop Final Results Explained + +A Control Loop Policy has the following set of final results, as defined in [FinalResult.java](src/main/java/com/att/ecomp/policy/controlloop/policy/FinalResult.java). A final result indicates when a Control Loop Policy has finished execution and is finished processing a Closed Loop Event. All paths must lead to a Final Result. + diff --git a/controlloop/common/policy-yaml/pom.xml b/controlloop/common/policy-yaml/pom.xml new file mode 100644 index 000000000..6f87a978a --- /dev/null +++ b/controlloop/common/policy-yaml/pom.xml @@ -0,0 +1,46 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>common</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>policy-yaml</artifactId> + + <dependencies> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.17</version> + </dependency> + <dependency> + <groupId>org.jgrapht</groupId> + <artifactId>jgrapht-core</artifactId> + <version>0.9.2</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>sdc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>19.0</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java new file mode 100644 index 000000000..8a1fc3edd --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java @@ -0,0 +1,46 @@ +/*- + * ============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.compiler; + +public class CompilerException extends Exception { + + private static final long serialVersionUID = -7262217239867898601L; + + public CompilerException() { + } + + public CompilerException(String message) { + super(message); + } + + public CompilerException(Throwable cause) { + super(cause); + } + + public CompilerException(String message, Throwable cause) { + super(message, cause); + } + + public CompilerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java new file mode 100644 index 000000000..2710fcde2 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java @@ -0,0 +1,620 @@ +/*- + * ============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.compiler; + +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.graph.ClassBasedEdgeFactory; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedMultigraph; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.TargetType; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class ControlLoopCompiler { + + public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure the control loop is sane + // + validateControlLoop(policy.controlLoop, callback); + // + // Validate the policies + // + validatePolicies(policy, callback); + + return policy; + } + + public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopPolicy)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); + } + return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); + } + + private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { + if (controlLoop == null) { + if (callback != null) { + callback.onError("controlLoop cannot be null"); + } + } + if (controlLoop.controlLoopName == null | controlLoop.controlLoopName.length() < 1) { + if (callback != null) { + callback.onError("Missing controlLoopName"); + } + } + if (! controlLoop.version.contentEquals(ControlLoop.VERSION)) { + if (callback != null) { + callback.onError("Unsupported version for this compiler"); + } + } + if (controlLoop.trigger_policy == null || controlLoop.trigger_policy.length() < 1) { + throw new CompilerException("trigger_policy is not valid"); + } + // + } + + private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + if (policy == null) { + throw new CompilerException("policy cannot be null"); + } + // + // Chenfei: verify controlLoop overall timeout should be no less than the sum of operational policy timeouts + // + if (policy.policies == null) { + callback.onWarning("controlLoop is an open loop."); + } + else{ + int sum = 0; + for (Policy operPolicy : policy.policies) { + sum += operPolicy.timeout.intValue(); + } + if (policy.controlLoop.timeout.intValue() < sum) { + if (callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + } + // + // For this version we can use a directed multigraph, in the future we may not be able to + // + DirectedGraph<NodeWrapper, LabeledEdge> graph = new DirectedMultigraph<NodeWrapper, LabeledEdge>(new ClassBasedEdgeFactory<NodeWrapper, LabeledEdge>(LabeledEdge.class)); + // + // Check to see if the trigger Event is for OpenLoop, we do so by + // attempting to create a FinalResult object from it. If its a policy id, this should + // return null. + // + FinalResult triggerResult = FinalResult.toResult(policy.controlLoop.trigger_policy); + TriggerNodeWrapper triggerNode; + // + // Did this turn into a FinalResult object? + // + if (triggerResult != null) { + // + // Ensure they didn't use some other FinalResult code + // + if (triggerResult != FinalResult.FINAL_OPENLOOP) { + throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + // + // They really shouldn't have any policies attached. + // + if (policy.policies != null || policy.policies.size() > 0) { + if (callback != null) { + callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); + } + } + return; + // + } else { + // + // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. + // + triggerNode = new TriggerNodeWrapper(policy.controlLoop.controlLoopName); + } + // + // Add in the trigger node + // + graph.addVertex(triggerNode); + // + // Add in our Final Result nodes. All paths should end to these nodes. + // + FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); + FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); + FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); + FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); + FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); + FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); + graph.addVertex(finalSuccess); + graph.addVertex(finalFailure); + graph.addVertex(finalFailureTimeout); + graph.addVertex(finalFailureRetries); + graph.addVertex(finalFailureException); + graph.addVertex(finalFailureGuard); + // + // Work through the policies and add them in as nodes. + // + Map<Policy, PolicyNodeWrapper> mapNodes = new HashMap<Policy, PolicyNodeWrapper>(); + for (Policy operPolicy : policy.policies) { + // + // Check the policy id and make sure its sane + // + boolean okToAdd = true; + if (operPolicy.id == null || operPolicy.id.length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + okToAdd = false; + } + // + // Check if they decided to make the ID a result object + // + if (PolicyResult.toResult(operPolicy.id) != null) { + if (callback != null) { + callback.onError("Policy id is set to a PolicyResult " + operPolicy.id); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.id) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.id); + } + okToAdd = false; + } + // + // Check that the actor/recipe/target are valid + // + if (operPolicy.actor == null) { + if (callback != null) { + callback.onError("Policy actor is null"); + } + okToAdd = false; + } + // + // Construct a list for all valid actors + // + ImmutableList<String> actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); + // + if (operPolicy.actor != null && (!actors.contains(operPolicy.actor)) ) { + if (callback != null) { + callback.onError("Policy actor is invalid"); + } + okToAdd = false; + } + if (operPolicy.recipe == null) { + if (callback != null) { + callback.onError("Policy recipe is null"); + } + okToAdd = false; + } + // + // TODO: + // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) + // + ImmutableMap<String, List<String>> recipes = new ImmutableMap.Builder<String, List<String>>() + .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) + .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) + .put("MSO", ImmutableList.of("VF Module Create")) + .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) + .put("SDNR", ImmutableList.of("Restart", "Reboot")) + .build(); + // + if (operPolicy.recipe != null && (!recipes.getOrDefault(operPolicy.actor, Collections.emptyList()).contains(operPolicy.recipe))) { + if (callback != null) { + callback.onError("Policy recipe is invalid"); + } + okToAdd = false; + } + if (operPolicy.target == null) { + if (callback != null) { + callback.onError("Policy target is null"); + } + okToAdd = false; + } + if (operPolicy.target != null && operPolicy.target.type != TargetType.VM && operPolicy.target.type != TargetType.VFC && operPolicy.target.type != TargetType.PNF) { + if (callback != null) { + callback.onError("Policy target is invalid"); + } + okToAdd = false; + } + // + // Check that policy results are connected to either default final * or another policy + // + if (FinalResult.toResult(operPolicy.success) != null && operPolicy.success != FinalResult.FINAL_SUCCESS.toString()) { + if (callback != null) { + callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure) != null && operPolicy.failure != FinalResult.FINAL_FAILURE.toString()) { + if (callback != null) { + callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_retries) != null && operPolicy.failure_retries != FinalResult.FINAL_FAILURE_RETRIES.toString()) { + if (callback != null) { + callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_timeout) != null && operPolicy.failure_timeout != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { + if (callback != null) { + callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_exception) != null && operPolicy.failure_exception != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { + if (callback != null) { + callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.failure_guard) != null && operPolicy.failure_guard != FinalResult.FINAL_FAILURE_GUARD.toString()) { + if (callback != null) { + callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + } + okToAdd = false; + } + // + // Is it still ok to add? + // + if (okToAdd == false) { + // + // Do not add it in + // + continue; + } + // + // Create wrapper policy node and save it into our map so we can + // easily retrieve it. + // + PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); + mapNodes.put(operPolicy, node); + graph.addVertex(node); + // + // Is this the trigger policy? + // + if (operPolicy.id.equals(policy.controlLoop.trigger_policy)) { + // + // Yes add an edge from our trigger event node to this policy + // + graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); + } + } + // + // last sweep to connect remaining edges for policy results + // + for (Policy operPolicy : policy.policies) { + PolicyNodeWrapper node = mapNodes.get(operPolicy); + // + // Just ensure this has something + // + if (node == null) { + continue; + } + if (FinalResult.isResult(operPolicy.success, FinalResult.FINAL_SUCCESS)) { + graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.success); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " success is connected to unknown policy " + operPolicy.success); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); + } + } + if (FinalResult.isResult(operPolicy.failure, FinalResult.FINAL_FAILURE)) { + graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure is connected to unknown policy " + operPolicy.failure); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); + } + } + if (FinalResult.isResult(operPolicy.failure_timeout, FinalResult.FINAL_FAILURE_TIMEOUT)) { + graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_timeout); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_timeout is connected to unknown policy " + operPolicy.failure_timeout); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); + } + } + if (FinalResult.isResult(operPolicy.failure_retries, FinalResult.FINAL_FAILURE_RETRIES)) { + graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_retries); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_retries is connected to unknown policy " + operPolicy.failure_retries); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); + } + } + if (FinalResult.isResult(operPolicy.failure_exception, FinalResult.FINAL_FAILURE_EXCEPTION)) { + graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_exception); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_exception is connected to unknown policy " + operPolicy.failure_exception); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); + } + } + if (FinalResult.isResult(operPolicy.failure_guard, FinalResult.FINAL_FAILURE_GUARD)) { + graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.failure_guard); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.id + " failure_guard is connected to unknown policy " + operPolicy.failure_guard); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); + } + } + } + // + // Now validate all the nodes/edges + // + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + System.out.println("Trigger Node " + node.toString()); + if (graph.inDegreeOf(node) > 0 ) { + // + // Really should NEVER get here unless someone messed up the code above. + // + throw new CompilerException("No inputs to event trigger"); + } + // + // Should always be 1, except in the future we may support multiple events + // + if (graph.outDegreeOf(node) > 1) { + throw new CompilerException("The event trigger should only go to ONE node"); + } + } else if (node instanceof FinalResultNodeWrapper) { + System.out.println("FinalResult Node " + node.toString()); + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } else if (node instanceof PolicyNodeWrapper) { + System.out.println("Policy Node " + node.toString()); + // + // All Policy Nodes should have the 5 out degrees defined. + // + if (graph.outDegreeOf(node) != 6) { + throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); + } + // + // Chenfei: All Policy Nodes should have at least 1 in degrees + // + if (graph.inDegreeOf(node) == 0) { + if (callback != null) { + callback.onWarning("Policy " + node.getID() + " is not reachable."); + } + } + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ + System.out.println(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); + } + } + } + } + + private static PolicyNodeWrapper findPolicyNode(Map<Policy, PolicyNodeWrapper> mapNodes, String id) { + for (Policy key : mapNodes.keySet()) { + if (key.id.equals(id)) { + return mapNodes.get(key); + } + } + return null; + } + + private interface NodeWrapper { + + public String getID(); + + } + + private static class TriggerNodeWrapper implements NodeWrapper { + public String closedLoopControlName; + + public TriggerNodeWrapper(String closedLoopControlName) { + this.closedLoopControlName = closedLoopControlName; + } + + @Override + public String toString() { + return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; + } + + @Override + public String getID() { + return closedLoopControlName; + } + + } + + private static class FinalResultNodeWrapper implements NodeWrapper { + + public FinalResult result; + + public FinalResultNodeWrapper(FinalResult result) { + this.result = result; + } + + @Override + public String toString() { + return "FinalResultNodeWrapper [result=" + result + "]"; + } + + @Override + public String getID() { + return result.toString(); + } + } + + private static class PolicyNodeWrapper implements NodeWrapper { + + public Policy policy; + + public PolicyNodeWrapper(Policy operPolicy) { + this.policy = operPolicy; + } + + @Override + public String toString() { + return "PolicyNodeWrapper [policy=" + policy + "]"; + } + + @Override + public String getID() { + return policy.id; + } + } + + private interface EdgeWrapper { + + public String getID(); + + } + + private static class TriggerEdgeWrapper implements EdgeWrapper { + + private String trigger; + + public TriggerEdgeWrapper(String trigger) { + this.trigger = trigger; + } + + @Override + public String getID() { + return trigger; + } + + @Override + public String toString() { + return "TriggerEdgeWrapper [trigger=" + trigger + "]"; + } + + } + + private static class PolicyResultEdgeWrapper implements EdgeWrapper { + public PolicyResult policyResult; + + public PolicyResultEdgeWrapper(PolicyResult policyResult) { + super(); + this.policyResult = policyResult; + } + + @Override + public String toString() { + return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; + } + + @Override + public String getID() { + return policyResult.toString(); + } + + + } + + private static class FinalResultEdgeWrapper implements EdgeWrapper { + + public FinalResult finalResult; + public FinalResultEdgeWrapper(FinalResult result) { + this.finalResult = result; + } + + @Override + public String toString() { + return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; + } + + @Override + public String getID() { + return finalResult.toString(); + } + } + + + private static class LabeledEdge extends DefaultEdge { + + /** + * + */ + private static final long serialVersionUID = 579384429573385524L; + + private NodeWrapper from; + private NodeWrapper to; + private EdgeWrapper edge; + + public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { + this.from = from; + this.to = to; + this.edge = edge; + } + + @SuppressWarnings("unused") + public NodeWrapper from() { + return from; + } + + @SuppressWarnings("unused") + public NodeWrapper to() { + return to; + } + + @SuppressWarnings("unused") + public EdgeWrapper edge() { + return edge; + } + + @Override + public String toString() { + return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; + } + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java new file mode 100644 index 000000000..e07b77640 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java @@ -0,0 +1,29 @@ +/*- + * ============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.compiler; + +public interface ControlLoopCompilerCallback { + + public boolean onWarning(String message); + + public boolean onError(String message); + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java new file mode 100644 index 000000000..491e4c872 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.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.guard.compiler; + + +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; + +public class ControlLoopGuardCompiler { + + public static ControlLoopGuard compile(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure ControlLoopGuard has at least one guard policies + // + validateControlLoopGuard(CLGuard, callback); + // + // Ensure each guard policy has at least one constraints and all guard policies are unique + // + validateGuardPolicies(CLGuard.guards, callback); + // + // Ensure constraints for each guard policy are unique + // + validateConstraints(CLGuard.guards, callback); + + return CLGuard; + } + + public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopGuard)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); + } + return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); + } + + private static void validateControlLoopGuard(ControlLoopGuard CLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + if (CLGuard == null) { + if (callback != null) { + callback.onError("ControlLoop Guard cannot be null"); + } + throw new CompilerException("ControlLoop Guard cannot be null"); + } + if (CLGuard.guard == null) { + if (callback != null) { + callback.onError("Guard version cannot be null"); + } + } + if (CLGuard.guards == null) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } else if (CLGuard.guards.size() < 1) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } + } + + private static void validateGuardPolicies(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + // + // Ensure all guard policies are unique + // + Set<GuardPolicy> newSet = new HashSet<GuardPolicy>(policies); + if (newSet.size() != policies.size()) { + if (callback != null) { + callback.onWarning("There are duplicate guard policies"); + } + } + // + // Ensure each guard policy has at least one constraints + // + for (GuardPolicy policy : policies) { + if (policy.limit_constraints == null || policy.limit_constraints.size() < 1) { + if (callback != null) { + callback.onError("Guard policy " + policy.name + " does not have any limit constraint"); + } + throw new CompilerException("Guard policy " + policy.name + " does not have any limit constraint"); + } + } + } + + private static void validateConstraints(List<GuardPolicy> policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + for (GuardPolicy policy : policies) { + Set<Constraint> newSet = new HashSet<Constraint>(policy.limit_constraints); + if (newSet.size() != policy.limit_constraints.size()) { + if (callback != null) { + callback.onWarning("Guard policy " + policy.name + " has duplicate limit constraints"); + } + } + } + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java new file mode 100644 index 000000000..368424bfe --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java @@ -0,0 +1,139 @@ +/*- + * ============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; + +import java.util.LinkedList; + +import org.onap.policy.aai.PNF; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.Service; + +public class ControlLoop { + + public static String VERSION = "2.0.0"; + + public String controlLoopName; + public final String version = VERSION; + public LinkedList<Service> services; + public LinkedList<Resource> resources; + public PNF pnf; + public String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + public Integer timeout; + public Boolean abatement = false; + + public ControlLoop() { + + } + + public ControlLoop(ControlLoop controlLoop) { + this.controlLoopName = controlLoop.controlLoopName; + this.services = new LinkedList<Service>(); + if (controlLoop.services != null) { + for (Service service : controlLoop.services) { + this.services.add(service); + } + } + this.resources = new LinkedList<Resource>(); + if (controlLoop.resources != null) { + for (Resource resource: controlLoop.resources) { + this.resources.add(resource); + } + } + if (controlLoop.pnf != null) { + this.pnf = new PNF(controlLoop.pnf); + } + this.trigger_policy = controlLoop.trigger_policy; + this.timeout = controlLoop.timeout; + this.abatement = controlLoop.abatement; + } + @Override + public String toString() { + return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services + + ", resources=" + resources + ", pnf=" + pnf + ", trigger_policy=" + trigger_policy + ", timeout=" + + timeout + ", abatement=" + abatement + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((pnf == null) ? 0 : pnf.hashCode()); + result = prime * result + ((resources == null) ? 0 : resources.hashCode()); + result = prime * result + ((services == null) ? 0 : services.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + result = prime * result + ((abatement == null) ? 0 : abatement.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; + ControlLoop other = (ControlLoop) obj; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (pnf == null) { + if (other.pnf != null) + return false; + } else if (!pnf.equals(other.pnf)) + return false; + if (resources == null) { + if (other.resources != null) + return false; + } else if (!resources.equals(other.resources)) + return false; + if (services == null) { + if (other.services != null) + return false; + } else if (!services.equals(other.services)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + if (trigger_policy == null) { + if (other.trigger_policy != null) + return false; + } else if (!trigger_policy.equals(other.trigger_policy)) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + if (abatement == null) { + if (other.abatement != null) + return false; + } else if (!abatement.equals(other.abatement)) + return false; + return true; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java new file mode 100644 index 000000000..013e242aa --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java @@ -0,0 +1,67 @@ +/*- + * ============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; + +import java.util.LinkedList; + +public class ControlLoopPolicy { + + public ControlLoop controlLoop; + + public LinkedList<Policy> policies; + + @Override + public String toString() { + return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); + result = prime * result + ((policies == null) ? 0 : policies.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; + ControlLoopPolicy other = (ControlLoopPolicy) obj; + if (controlLoop == null) { + if (other.controlLoop != null) + return false; + } else if (!controlLoop.equals(other.controlLoop)) + return false; + if (policies == null) { + if (other.policies != null) + return false; + } else if (!policies.equals(other.policies)) + return false; + return true; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java new file mode 100644 index 000000000..f69e4b93c --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java @@ -0,0 +1,93 @@ +/*- + * ============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; + +public enum FinalResult { + /** + * The Control Loop Policy successfully completed its Operations. + */ + FINAL_SUCCESS("Final_Success"), + /** + * The Control Loop Policy was an Open Loop and is finished. + */ + FINAL_OPENLOOP("Final_OpenLoop"), + /** + * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. + */ + FINAL_FAILURE("Final_Failure"), + /** + * The Control Loop Policy failed because the overall timeout was met. + */ + FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), + /** + * The Control Loop Policy failed because an Operation Policy met its retry limit. + */ + FINAL_FAILURE_RETRIES("Final_Failure_Retries"), + /** + * The Control Loop Policy failed due to an exception. + */ + FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), + /** + * The Control Loop Policy failed due to guard denied + */ + FINAL_FAILURE_GUARD("Final_Failure_Guard") + ; + + String result; + + private FinalResult(String result) { + this.result = result; + } + + public static FinalResult toResult(String result) { + if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { + return FINAL_SUCCESS; + } + if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { + return FINAL_OPENLOOP; + } + if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { + return FINAL_FAILURE; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { + return FINAL_FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { + return FINAL_FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { + return FINAL_FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { + return FINAL_FAILURE_GUARD; + } + return null; + } + + public static boolean isResult(String result, FinalResult finalResult) { + FinalResult toResult = FinalResult.toResult(result); + if (toResult == null) { + return false; + } + return (toResult.equals(finalResult)); + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java new file mode 100644 index 000000000..4aaea12c9 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java @@ -0,0 +1,84 @@ +/*- + * ============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; + +import java.io.Serializable; + +public class OperationsAccumulateParams implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3597358159130168247L; + + public String period; + public Integer limit; + + public OperationsAccumulateParams() { + + } + + public OperationsAccumulateParams(OperationsAccumulateParams ops) { + this.period = ops.period; + this.limit = ops.limit; + } + + public OperationsAccumulateParams(String period, Integer limit) { + this.period = period; + this.limit = limit; + } + + @Override + public String toString() { + return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((period == null) ? 0 : period.hashCode()); + result = prime * result + ((limit == null) ? 0 : limit.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; + OperationsAccumulateParams other = (OperationsAccumulateParams) obj; + if (period == null) { + if (other.period != null) + return false; + } else if (!period.equals(other.period)) + return false; + if (limit == null) { + if (other.limit != null) + return false; + } else if (!limit.equals(other.limit)) + return false; + return true; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java new file mode 100644 index 000000000..fbc9558bd --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Policy.java @@ -0,0 +1,245 @@ +/*- + * ============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; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +public class Policy { + + public String id = UUID.randomUUID().toString(); + public String name; + public String description; + public String actor; + public String recipe; + public Map<String, String> payload; + public Target target; + public OperationsAccumulateParams operationsAccumulateParams; + public Integer retry = 0; + public Integer timeout = 300; + public String success = FinalResult.FINAL_SUCCESS.toString(); + public String failure = FinalResult.FINAL_FAILURE.toString(); + public String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + public String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + public String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + public String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + + + public Policy() { + + } + + public Policy(String id) { + this.id = id; + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + this.target = target; + if (payload != null) { +// this.payload = new LinkedList<Map<String, String>>(); + this.payload = Collections.unmodifiableMap(payload); + } + } + + public Policy(String name, String actor, String recipe, Map<String, String> payload, Target target, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target); + this.retry = retries; + this.timeout = timeout; + } + + public Policy(String id, String name, String description, String actor, Map<String, String> payload, Target target, String recipe, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target, retries, timeout); + this.id = id; + this.description = description; + } + + public Policy(Policy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.actor = policy.actor; + this.recipe = policy.recipe; + if (policy.payload != null) { +// this.payload = new LinkedList<Map<String, String>>(); +// this.payload.addAll(policy.payload); + this.payload = Collections.unmodifiableMap(policy.payload); + } + this.target = policy.target; + this.operationsAccumulateParams = policy.operationsAccumulateParams; + this.retry = policy.retry; + this.timeout = policy.timeout; + this.success = policy.success; + this.failure = policy.failure; + this.failure_exception = policy.failure_exception; + this.failure_guard = policy.failure_guard; + this.failure_retries = policy.failure_retries; + this.failure_timeout = policy.failure_timeout; + } + + public boolean isValid() { + try { + if (id == null) { + throw new NullPointerException(); + } + if (name == null) { + throw new NullPointerException(); + } + if (actor == null) { + throw new NullPointerException(); + } + if (recipe == null) { + throw new NullPointerException(); + } + if (target == null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout + + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries + + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; + } + + @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 + ((failure == null) ? 0 : failure.hashCode()); + result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); + result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); + result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); + result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((retry == null) ? 0 : retry.hashCode()); + result = prime * result + ((success == null) ? 0 : success.hashCode()); + result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.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; + Policy other = (Policy) obj; + if (actor != other.actor) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (failure == null) { + if (other.failure != null) + return false; + } else if (!failure.equals(other.failure)) + return false; + if (failure_exception == null) { + if (other.failure_exception != null) + return false; + } else if (!failure_exception.equals(other.failure_exception)) + return false; + if (failure_guard == null) { + if (other.failure_guard != null) + return false; + } else if (!failure_guard.equals(other.failure_guard)) + return false; + if (failure_retries == null) { + if (other.failure_retries != null) + return false; + } else if (!failure_retries.equals(other.failure_retries)) + return false; + if (failure_timeout == null) { + if (other.failure_timeout != null) + return false; + } else if (!failure_timeout.equals(other.failure_timeout)) + return false; + if (id == null) { + if (other.id != null) + 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 (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (retry == null) { + if (other.retry != null) + return false; + } else if (!retry.equals(other.retry)) + return false; + if (success == null) { + if (other.success != null) + return false; + } else if (!success.equals(other.success)) + return false; + if (operationsAccumulateParams == null) { + if (other.operationsAccumulateParams != null) + return false; + } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) + return false; + if (target == null) { + if (other.target != null) + return false; + } else if (!target.equals(other.target)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + return true; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java new file mode 100644 index 000000000..0a504339f --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java @@ -0,0 +1,82 @@ +/*- + * ============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; + +public enum PolicyResult { + /** + * Operation was successful. + */ + SUCCESS("Success"), + /** + * Operation failed. + */ + FAILURE("Failure"), + /** + * Operation failed due to maximum retries being met. + */ + FAILURE_RETRIES("Failure_Retries"), + /** + * Operation failed due to timeout occurring. + */ + FAILURE_TIMEOUT("Failure_Timeout"), + /** + * Operation failed due to an exception. + */ + FAILURE_EXCEPTION("Failure_Exception"), + /** + * Operation failed since Guard did not permit. + */ + FAILURE_GUARD("Failure_Guard") + ; + + private String result; + + private PolicyResult(String result) { + this.result = result; + } + + public String toString() { + return this.result; + } + + public static PolicyResult toResult(String result) { + if (result.equalsIgnoreCase(SUCCESS.toString())) { + return SUCCESS; + } + if (result.equalsIgnoreCase(FAILURE.toString())) { + return FAILURE; + } + if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { + return FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { + return FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { + return FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { + return FAILURE_GUARD; + } + return null; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java new file mode 100644 index 000000000..ba05e9b69 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/Target.java @@ -0,0 +1,91 @@ +/*- + * ============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; + +import java.io.Serializable; + +public class Target implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 2180988443264988319L; + + public String resourceID; + public TargetType type; + + public Target() { + + } + + public Target(TargetType type) { + this.type = type; + } + + public Target(String resourceID) { + this.resourceID = resourceID; + } + + public Target(TargetType type, String resourceID) { + this.type = type; + this.resourceID = resourceID; + } + + public Target(Target target) { + this.type = target.type; + this.resourceID = target.resourceID; + } + + @Override + public String toString() { + return "Target [type=" + type + ", resourceID=" + resourceID + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((resourceID == null) ? 0 : resourceID.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; + Target other = (Target) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (resourceID == null) { + if (other.resourceID != null) + return false; + } else if (!resourceID.equals(other.resourceID)) + return false; + return true; + } +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java new file mode 100644 index 000000000..30ee323bf --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java @@ -0,0 +1,39 @@ +/*- + * ============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; + +public enum TargetType { + VM("VM"), + PNF("PNF"), + VFC("VFC") + ; + + private String targetType; + + private TargetType(String targetType) { + this.targetType = targetType; + } + + public String toString() { + return this.targetType; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java new file mode 100644 index 000000000..5fc8ffb6e --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java @@ -0,0 +1,34 @@ +/*- + * ============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.builder; + +public class BuilderException extends Exception { + + public BuilderException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = 610064813684337895L; + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java new file mode 100644 index 000000000..fcc783570 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -0,0 +1,315 @@ +/*- + * ============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.builder; + +import java.util.Map; + +import org.onap.policy.aai.PNF; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.builder.impl.ControlLoopPolicyBuilderImpl; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.Service; + +public interface ControlLoopPolicyBuilder { + + /** + * Adds one or more services to the ControlLoop + * + * + * @param service + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; + + /** + * @param services + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; + + /** + * Adds one or more resources to the ControlLoop + * + * + * @param resource + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; + + /** + * @param resources + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; + + /** + * @param pnf + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removePNF() throws BuilderException; + + /** + * @param abatement + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; + + + /** + * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, + * then this overall timeout value should exceed all those values. + * + * @param timeout + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; + + /** + * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. + * + * + * @return Integer + */ + public Integer calculateTimeout(); + + /** + * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ECOMP Policy Platform. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @return Policy + * @throws BuilderException + */ + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException; + + /** + * + * Changes the trigger policy to point to another existing Policy. + * + * + * @param id + * @return ControlLoop + * @throws BuilderException + */ + public ControlLoop setTriggerPolicy(String id) throws BuilderException; + + /** + * @return + */ + public boolean isOpenLoop(); + + /** + * @return + * @throws BuilderException + */ + public Policy getTriggerPolicy() throws BuilderException; + + /** + * Simply returns a copy of the ControlLoop information. + * + * + * @return ControlLoop + */ + public ControlLoop getControlLoop(); + + /** + * Creates a policy that is chained to the result of another Policy. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; + + + /** + * Sets the policy result(s) to an existing Operational Policy. + * + * + * @param policyResultID + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; + + /** + * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any + * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. + * + * + * @param policyID + * @return + * @throws BuilderException + */ + public boolean removePolicy(String policyID) throws BuilderException; + + /** + * Resets a policy's results to defualt FINAL_* codes. + * + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy resetPolicyResults(String policyID) throws BuilderException; + + /** + * Removes all existing Operational Policies and reverts back to an Open Loop. + * + * @return + */ + public ControlLoopPolicyBuilder removeAllPolicies(); + + /** + * Adds an operationsAccumulateParams to an existing operational policy + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; + + /** + * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopPolicyBuilder implementation. + * + * @author pameladragosh + * + */ + public static class Factory { + + /** + * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you + * want to interactively build a Closed Loop. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); + + return builder; + } + + /** + * Build a Control Loop for a resource and services associated with the resource. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @param resource - Resource this closed loop is for. Should come from ASDC, but if not available use resourceName to distinguish. + * @param services - Zero or more services associated with this resource. Should come from ASDC, but if not available use serviceName to distinguish. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); + + return builder; + } + + /** + * @param controlLoopName + * @param timeout + * @param service + * @param resources + * @return + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); + + return builder; + } + + /** + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @param pnf - Physical Network Function. Should come from AIC, but if not available use well-known name to distinguish. Eg. eNodeB + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, pnf); + + return builder; + } + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java new file mode 100644 index 000000000..e620276b0 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java @@ -0,0 +1,29 @@ +/*- + * ============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.builder; + +public interface Message { + + public String getMessage(); + + public MessageLevel getLevel(); + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java new file mode 100644 index 000000000..ffd63d691 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java @@ -0,0 +1,30 @@ +/*- + * ============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.builder; + +public enum MessageLevel { + INFO, + WARNING, + ERROR, + EXCEPTION + ; + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java new file mode 100644 index 000000000..fa309cc1f --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java @@ -0,0 +1,33 @@ +/*- + * ============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.builder; + +import java.util.List; + +public interface Results { + + public List<Message> getMessages(); + + public String getSpecification(); + + public boolean isValid(); + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java new file mode 100644 index 000000000..131d7d766 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -0,0 +1,519 @@ +/*- + * ============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.builder.impl; + +import java.util.LinkedList; +import java.util.Map; +import java.util.UUID; + +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; + +import org.onap.policy.aai.PNF; +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompiler; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.Service; + +public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { + + private ControlLoopPolicy policy; + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { + policy = new ControlLoopPolicy(); + policy.controlLoop = new ControlLoop(); + policy.controlLoop.controlLoopName = controlLoopName; + policy.controlLoop.timeout = timeout; + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + this(controlLoopName, timeout); + this.addResource(resource); + this.addService(services); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, PNF pnf) throws BuilderException { + this(controlLoopName, timeout); + this.setPNF(pnf); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { + this(controlLoopName, timeout); + this.addService(service); + this.addResource(resources); + } + + @Override + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { + if (services == null) { + throw new BuilderException("Service must not be null"); + } + for (Service service : services) { + if (service.serviceUUID == null) { + if (service.serviceName == null || service.serviceName.length() < 1) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + } + if (policy.controlLoop.services == null) { + policy.controlLoop.services = new LinkedList<Service>(); + } + policy.controlLoop.services.add(service); + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { + if (services == null) { + throw new BuilderException("Service must not be null"); + } + if (policy.controlLoop.services == null) { + throw new BuilderException("No existing services to remove"); + } + for (Service service : services) { + if (service.serviceUUID == null) { + if (service.serviceName == null || service.serviceName.length() < 1) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + } + boolean removed = policy.controlLoop.services.remove(service); + if (!removed) { + throw new BuilderException("Unknown service " + service.serviceName); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { + policy.controlLoop.services.clear(); + return this; + } + + + @Override + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { + if (resources == null) { + throw new BuilderException("resources must not be null"); + } + for (Resource resource : resources) { + if (resource.resourceUUID == null) { + if (resource.resourceName == null || resource.resourceName.length() <= 0) { + throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); + } + } + if (policy.controlLoop.resources == null) { + policy.controlLoop.resources = new LinkedList<Resource>(); + } + policy.controlLoop.resources.add(resource); + } + return this; + } + + @Override + public ControlLoopPolicyBuilder setPNF(PNF pnf) throws BuilderException { + if (pnf == null) { + throw new BuilderException("PNF must not be null"); + } + if (pnf.PNFName == null) { + if (pnf.PNFType == null) { + throw new BuilderException("Invalid PNF - need either pnfName or pnfType"); + } + } + policy.controlLoop.pnf = pnf; + return this; + } + + @Override + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ + if (abatement == null) { + throw new BuilderException("abatement must not be null"); + } + policy.controlLoop.abatement = abatement; + return this; + } + + @Override + public ControlLoopPolicyBuilder setTimeout(Integer timeout) { + policy.controlLoop.timeout = timeout; + return this; + } + + @Override + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, + Map<String, String> payload, Integer retries, Integer timeout) throws BuilderException { + + Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + + policy.controlLoop.trigger_policy = trigger.id; + + this.addNewPolicy(trigger); + // + // Return a copy of the policy + // + return new Policy(trigger); + } + + @Override + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map<String, String> payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Create the new Policy + // + Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.failure = newPolicy.id; + break; + case FAILURE_EXCEPTION: + existingPolicy.failure_exception = newPolicy.id; + break; + case FAILURE_RETRIES: + existingPolicy.failure_retries = newPolicy.id; + break; + case FAILURE_TIMEOUT: + existingPolicy.failure_timeout = newPolicy.id; + break; + case FAILURE_GUARD: + existingPolicy.failure_guard = newPolicy.id; + break; + case SUCCESS: + existingPolicy.success = newPolicy.id; + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + // + // Add it to our list + // + this.policy.policies.add(newPolicy); + // + // Return a policy to them + // + return new Policy(newPolicy); + } + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + public ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(policy); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopCompiler.compile(policy, callback); + } catch (CompilerException e) { + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + + private void addNewPolicy(Policy policy) { + if (this.policy.policies == null) { + this.policy.policies = new LinkedList<Policy>(); + } + this.policy.policies.add(policy); + } + + private Policy findPolicy(String id) { + for (Policy policy : this.policy.policies) { + if (policy.id.equals(id)) { + return policy; + } + } + return null; + } + + @Override + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { + if (resources == null) { + throw new BuilderException("Resource must not be null"); + } + if (policy.controlLoop.resources == null) { + throw new BuilderException("No existing resources to remove"); + } + for (Resource resource : resources) { + if (resource.resourceUUID == null) { + if (resource.resourceName == null || resource.resourceName.length() < 1) { + throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); + } + } + boolean removed = policy.controlLoop.resources.remove(resource); + if (!removed) { + throw new BuilderException("Unknown resource " + resource.resourceName); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { + policy.controlLoop.resources.clear(); + return this; + } + + @Override + public ControlLoopPolicyBuilder removePNF() throws BuilderException { + policy.controlLoop.pnf = null; + return this; + } + + @Override + public Integer calculateTimeout() { + int sum = 0; + for (Policy policy : this.policy.policies) { + sum += policy.timeout.intValue(); + } + return new Integer(sum); + } + + @Override + public ControlLoop setTriggerPolicy(String id) throws BuilderException { + if (id == null) { + throw new BuilderException("Id must not be null"); + } + Policy trigger = this.findPolicy(id); + if (trigger == null) { + throw new BuilderException("Unknown policy " + id); + } + else { + this.policy.controlLoop.trigger_policy = id; + } + return new ControlLoop(this.policy.controlLoop); + } + + @Override + public boolean isOpenLoop() { + if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + return true; + } + else { + return false; + } + } + + @Override + public Policy getTriggerPolicy() throws BuilderException { + if (this.policy.controlLoop.trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())) { + return null; + } + else { + Policy trigger = new Policy(this.findPolicy(this.policy.controlLoop.trigger_policy)); + return trigger; + } + } + + @Override + public ControlLoop getControlLoop() { + ControlLoop loop = new ControlLoop(this.policy.controlLoop); + return loop; + } + + @Override + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException(policyID + " does not exist"); + } + if (this.findPolicy(policyResultID) == null) { + throw new BuilderException("Operational policy " + policyResultID + " does not exist"); + } + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.failure = policyResultID; + break; + case FAILURE_EXCEPTION: + existingPolicy.failure_exception = policyResultID; + break; + case FAILURE_RETRIES: + existingPolicy.failure_retries = policyResultID; + break; + case FAILURE_TIMEOUT: + existingPolicy.failure_timeout = policyResultID; + break; + case FAILURE_GUARD: + existingPolicy.failure_guard = policyResultID; + break; + case SUCCESS: + existingPolicy.success = policyResultID; + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + return new Policy(this.findPolicy(policyResultID)); + } + + @Override + public boolean removePolicy(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Check if the policy to remove is trigger_policy + // + if (this.policy.controlLoop.trigger_policy.equals(policyID)) { + this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + } + else { + // + // Update policies + // + for (Policy policy : this.policy.policies) { + int index = this.policy.policies.indexOf(policy); + if (policy.success.equals(policyID)) { + policy.success = FinalResult.FINAL_SUCCESS.toString(); + } + if (policy.failure.equals(policyID)) { + policy.failure = FinalResult.FINAL_FAILURE.toString(); + } + if (policy.failure_retries.equals(policyID)) { + policy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + } + if (policy.failure_timeout.equals(policyID)) { + policy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + } + if (policy.failure_exception.equals(policyID)) { + policy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + } + if (policy.failure_guard.equals(policyID)) { + policy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + } + this.policy.policies.set(index, policy); + } + } + // + // remove the policy + // + boolean removed = this.policy.policies.remove(existingPolicy); + return removed; + } + + @Override + public Policy resetPolicyResults(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // reset policy results + // + existingPolicy.success = FinalResult.FINAL_SUCCESS.toString(); + existingPolicy.failure = FinalResult.FINAL_FAILURE.toString(); + existingPolicy.failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + existingPolicy.failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + existingPolicy.failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + existingPolicy.failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + return new Policy(existingPolicy); + } + + @Override + public ControlLoopPolicyBuilder removeAllPolicies() { + // + // Remove all existing operational policies + // + this.policy.policies.clear(); + // + // Revert controlLoop back to an open loop + // + this.policy.controlLoop.trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + return this; + } + + @Override + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Add operationsAccumulateParams to existingPolicy + // + existingPolicy.operationsAccumulateParams = operationsAccumulateParams; + return new Policy(existingPolicy); + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java new file mode 100644 index 000000000..45de842f9 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java @@ -0,0 +1,46 @@ +/*- + * ============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.builder.impl; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; + +public class MessageImpl implements Message { + + private String message; + private MessageLevel level; + + public MessageImpl(String message, MessageLevel level) { + this.message = message; + this.level = level; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public MessageLevel getLevel() { + return level; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java new file mode 100644 index 000000000..3a9840c6c --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java @@ -0,0 +1,56 @@ +/*- + * ============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.builder.impl; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.Results; + +public class ResultsImpl implements Results { + + private String specification; + private List<Message> messages = new LinkedList<Message>(); + + @Override + public List<Message> getMessages() { + return messages; + } + + @Override + public String getSpecification() { + return specification; + } + + @Override + public boolean isValid() { + return (this.specification != null); + } + + public void addMessage(Message message) { + this.messages.add(message); + } + + public void setSpecification(String spec) { + this.specification = spec; + } +} 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 new file mode 100644 index 000000000..54f230876 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.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.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class Constraint { + + public Integer num; + //public String duration; + public Map<String, String> duration; + public Map<String, String> time_in_range; + + public LinkedList<String> blacklist; + + public Constraint() { + + } + + public Constraint(Integer num, Map<String, String> duration) { + this.num = num; + this.duration = duration; + } + + public Constraint(List<String> blacklist) { + this.blacklist = new LinkedList<String>(blacklist); + + } + + public Constraint(Integer num, Map<String, String> duration, List<String> blacklist) { + this.num = num; + this.duration = Collections.unmodifiableMap(duration); + this.blacklist = new LinkedList<String>(blacklist); + } + + public Constraint(Integer num, Map<String, String> duration, Map<String, String> time_in_range, List<String> 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); + } + this.blacklist = new LinkedList<String>(blacklist); + } + + 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.blacklist = new LinkedList<String>(constraint.blacklist); + } + + public boolean isValid() { + try { + if (num == null && duration != null) { + throw new NullPointerException(); + } + if (duration == null && num != null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Constraint [num=" + num + ", duration=" + duration + ", time_in_range=" + time_in_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 + ((blacklist == null) ? 0 : blacklist.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; + Constraint other = (Constraint) obj; + if (num == null) { + if (other.num != null) + return false; + } else if (!num.equals(other.num)) + return false; + if (duration == null) { + if (other.duration != null) + return false; + } else if (!duration.equals(other.duration)) + return false; + if (time_in_range == null) { + if (other.time_in_range != null) + return false; + } else if (!time_in_range.equals(other.time_in_range)) + return false; + if (blacklist == null) { + if (other.blacklist != null) + return false; + } else if (!blacklist.equals(other.blacklist)) + return false; + return true; + } +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java new file mode 100644 index 000000000..34dc20191 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -0,0 +1,77 @@ +/*- + * ============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 ControlLoopGuard { + + public Guard guard; + + public LinkedList<GuardPolicy> guards; + + public ControlLoopGuard() { + + } + + public ControlLoopGuard(ControlLoopGuard CLGuard) { + this.guard = new Guard(); + this.guards = new LinkedList<GuardPolicy>(CLGuard.guards); + } + + @Override + public String toString() { + return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((guard == null) ? 0 : guard.hashCode()); + result = prime * result + ((guards == null) ? 0 : guards.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; + ControlLoopGuard other = (ControlLoopGuard) obj; + if (guard == null) { + if (other.guard != null) + return false; + } else if (!guard.equals(other.guard)) + return false; + if (guards == null) { + if (other.guards != null) + return false; + } else if (!guards.equals(other.guards)) + return false; + return true; + } + + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java new file mode 100644 index 000000000..3c09b3201 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java @@ -0,0 +1,60 @@ +/*- + * ============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; + +public class Guard { + + public static String VERSION = "2.0.0"; + + public final String version = VERSION; + + public Guard() { + + } + + @Override + public String toString() { + return "Guard [version=" + version + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((version == null) ? 0 : version.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; + Guard other = (Guard) obj; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } +} 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 new file mode 100644 index 000000000..a850b36ed --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java @@ -0,0 +1,167 @@ +/*- + * ============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.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +public class GuardPolicy { + + public String id = UUID.randomUUID().toString(); + public String name; + public String description; + public String actor; + public String recipe; + public LinkedList<Constraint> limit_constraints; + + public GuardPolicy() { + + } + + public GuardPolicy(String id) { + this.id = id; + } + + public GuardPolicy(String name, String actor, String recipe) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + } + + public GuardPolicy(String id, String name, String description, String actor, String recipe) { + this(name, actor, recipe); + this.id = id; + this.description = description; + } + + public GuardPolicy(String name, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, actor, recipe); + if (limit_constraints != null) { + this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(limit_constraints); + } + } + + public GuardPolicy(String name, String description, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, actor, recipe, limit_constraints); + this.description = description; + } + + public GuardPolicy(String id, String name, String description, String actor, String recipe, List<Constraint> limit_constraints) { + this(name, description, actor, recipe, 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; + if (policy.limit_constraints != null) { + this.limit_constraints = (LinkedList<Constraint>) Collections.unmodifiableList(policy.limit_constraints); + } + } + + public boolean isValid() { + try { + if (id == null) { + throw new NullPointerException(); + } + if (name == null) { + throw new NullPointerException(); + } + if (actor == null) { + throw new NullPointerException(); + } + if (recipe == null) { + throw new NullPointerException(); + } + } catch (Exception e) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", 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()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + 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; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + 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) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + return true; + } + + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java new file mode 100644 index 000000000..0086342e7 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -0,0 +1,236 @@ +/*- + * ============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.builder.impl; + +import java.util.LinkedList; + +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; + +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.builder.impl.MessageImpl; +import org.onap.policy.controlloop.policy.builder.impl.ResultsImpl; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.poligy.guard.builder.ControlLoopGuardBuilder; + +public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { + + private ControlLoopGuard CLGuard; + + public ControlLoopGuardBuilderImpl(Guard guard) { + CLGuard = new ControlLoopGuard(); + CLGuard.guard = guard; + } + + @Override + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + if (CLGuard.guards == null) { + CLGuard.guards = new LinkedList<GuardPolicy>(); + } + CLGuard.guards.add(policy); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + if (CLGuard.guards == null) { + throw new BuilderException("No existing guard policies to remove"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + boolean removed = CLGuard.guards.remove(policy); + if (!removed) { + throw new BuilderException("Unknown guard policy: " + policy.name); + } + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { + CLGuard.guards.clear(); + return this; + } + + @Override + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + // + // We could have only one guard policy matching the id + // + if (policy.id.equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + if (policy.limit_constraints == null) { + policy.limit_constraints = new LinkedList<Constraint>(); + } + policy.limit_constraints.add(cons); + } + break; + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + // + // We could have only one guard policy matching the id + // + if (policy.id.equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + boolean removed = policy.limit_constraints.remove(cons); + if (!removed) { + throw new BuilderException("Unknown guard constraint: " + cons); + } + } + break; + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { + if (CLGuard.guards == null || CLGuard.guards.isEmpty()) { + throw new BuilderException("No guard policies exist"); + } + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + boolean exist = false; + for (GuardPolicy policy: CLGuard.guards) { + if (policy.id.equals(id)) { + exist = true; + policy.limit_constraints.clear(); + } + } + if (exist == false) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + public ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public ControlLoopGuard getControlLoopGuard() { + ControlLoopGuard guard = new ControlLoopGuard(this.CLGuard); + return guard; + } + + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(CLGuard); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopGuardCompiler.compile(CLGuard, callback); + } catch (CompilerException e) { + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + +} diff --git a/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java new file mode 100644 index 000000000..e948b5238 --- /dev/null +++ b/controlloop/common/policy-yaml/src/main/java/org/onap/policy/controlloop/poligy/guard/builder/ControlLoopGuardBuilder.java @@ -0,0 +1,129 @@ +/*- + * ============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.poligy.guard.builder; + +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; + +public interface ControlLoopGuardBuilder { + + /** + * Adds one or more guard policies to the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes one or more guard policies from the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes all guard policies from the Control Loop Guard + * + * + * @param + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; + + /** + * Adds one or more time limit constraints to the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes one or more time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes all time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; + + /** + * Simply return a copy of control loop guard + * + * @return ControlLoopGuard + */ + public ControlLoopGuard getControlLoopGuard(); + + /** + * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopGuardBuilder implementation. + * + */ + public static class Factory { + + /** + * @param guard + * @return ControlLoopGuardBuilder object + * @throws BuilderException + */ + public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { + + ControlLoopGuardBuilder builder = new ControlLoopGuardBuilderImpl(guard); + + return builder; + } + } +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java new file mode 100644 index 000000000..ee5ed785d --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.compiler; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; + +public class ControlLoopCompilerTest { + + @Test + public void testTest() { + try { + this.test("src/test/resources/v1.0.0/test.yaml"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testBad1() { + try { + this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + @Test + public void testBad2() { + try { + this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad() { + try { + this.test("src/test/resources/v1.0.0/bad_policies_1.yaml"); + } catch (Exception e) { + } + } + + public void test(String testFile) throws Exception { + try (InputStream is = new FileInputStream(new File(testFile))) { + ControlLoopCompiler.compile(is, null); + } catch (FileNotFoundException e) { + fail(e.getMessage()); + } catch (IOException e) { + fail(e.getMessage()); + } catch (Exception e) { + throw e; + } + } + +} 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 new file mode 100644 index 000000000..ddee23cef --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.compiler; + +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 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"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testBad1() { + try { + this.test("src/test/resources/v2.0.0-guard/no_guard_policy.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad2() { + try { + this.test("src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad3() { + try { + this.test("src/test/resources/v2.0.0-guard/no_guard_constraint.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad4() { + try { + this.test("src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void test(String testFile) throws Exception { + try (InputStream is = new FileInputStream(new File(testFile))) { + ControlLoopGuardCompiler.compile(is, null); + } catch (FileNotFoundException e) { + fail(e.getMessage()); + } catch (IOException e) { + fail(e.getMessage()); + } catch (Exception e) { + throw e; + } + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java new file mode 100644 index 000000000..f8ad499f0 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java @@ -0,0 +1,540 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.policy; + +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.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.error.YAMLException; + +import org.onap.policy.aai.PNF; +import org.onap.policy.aai.PNFType; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.sdc.Resource; +import org.onap.policy.sdc.ResourceType; +import org.onap.policy.sdc.Service; + + +public class ControlLoopPolicyBuilderTest { + + @Test + public void testControlLoop() { + try { + // + // Create a builder for our policy + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test add services + // + Service vSCP = new Service("vSCP"); + Service vUSP = new Service("vUSP"); + Service vTrinity = new Service("Trinity"); + builder = builder.addService(vSCP, vUSP, vTrinity); + assertTrue(builder.getControlLoop().services.size() == 3); + // + // Test remove services + // + builder = builder.removeService(vSCP); + assertTrue(builder.getControlLoop().services.size() == 2); + builder = builder.removeAllServices(); + assertTrue(builder.getControlLoop().services.size() == 0); + // + // Test add resources + // + Resource vCTS = new Resource("vCTS", ResourceType.VF); + Resource vCOM = new Resource("vCTS", ResourceType.VF); + Resource vRAR = new Resource("vCTS", ResourceType.VF); + builder = builder.addResource(vCTS, vCOM, vRAR); + assertTrue(builder.getControlLoop().resources.size() == 3); + // + // Test remove resources + // + builder = builder.removeResource(vCTS); + assertTrue(builder.getControlLoop().resources.size() == 2); + builder = builder.removeAllResources(); + assertTrue(builder.getControlLoop().resources.size() == 0); + // + // Test set pnf + // + PNF pnf = new PNF(); + pnf.PNFName = UUID.randomUUID().toString(); + pnf.PNFType = PNFType.ENODEB; + assertTrue(builder.getControlLoop().pnf == null); + builder = builder.setPNF(pnf); + assertTrue(builder.getControlLoop().pnf != null); + // + // Test remove pnf + // + builder = builder.removePNF(); + assertTrue(builder.getControlLoop().pnf == null); + // + // Test set abatement + // + assertFalse(builder.getControlLoop().abatement); + builder = builder.setAbatement(true); + assertTrue(builder.getControlLoop().abatement); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTimeout() { + try { + // + // Create a builder for our policy + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test setTimeout + // + assertTrue(builder.getControlLoop().timeout == 2400); + builder = builder.setTimeout(800); + assertTrue(builder.getControlLoop().timeout == 800); + // + // Test calculateTimeout + // + Policy trigger = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + @SuppressWarnings("unused") + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + trigger.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600))); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTriggerPolicyMethods() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test isOpenLoop + // + assertTrue(builder.isOpenLoop()); + // + // Test set initial trigger policy + // + Policy triggerPolicy1 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + assertTrue(builder.isOpenLoop() == false); + assertTrue(builder.getControlLoop().trigger_policy.equals(triggerPolicy1.id)); + // + // Set trigger policy to a new policy + // + @SuppressWarnings("unused") + Policy triggerPolicy2 = builder.setTriggerPolicy( + "Rebuild the VM", + "Upon getting the trigger event, rebuild the VM", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 2, + 300); + // + // Test set trigger policy to another existing policy + // + @SuppressWarnings("unused") + ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.id); + assertTrue(builder.getControlLoop().trigger_policy.equals(triggerPolicy1.id)); + // + // Test get trigger policy + // + assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1)); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testAddRemovePolicies() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + // + // Test create a policy and chain it to the results of trigger policy + // + Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + triggerPolicy.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT, + PolicyResult.FAILURE_GUARD); + // + assertTrue(builder.getTriggerPolicy().failure.equals(onRestartFailurePolicy1.id)); + assertTrue(builder.getTriggerPolicy().failure_retries.equals(onRestartFailurePolicy1.id)); + assertTrue(builder.getTriggerPolicy().failure_timeout.equals(onRestartFailurePolicy1.id)); + assertTrue(builder.getTriggerPolicy().failure_guard.equals(onRestartFailurePolicy1.id)); + // + // Test remove policy + // + boolean removed = builder.removePolicy(onRestartFailurePolicy1.id); + assertTrue(removed); + assertTrue(builder.getTriggerPolicy().failure.equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().failure_retries.equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().failure_timeout.equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + assertTrue(builder.getTriggerPolicy().failure_guard.equals(FinalResult.FINAL_FAILURE_GUARD.toString())); + // + // Create another policy and chain it to the results of trigger policy + // + Policy onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 2, + 600, + triggerPolicy.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + // + // Test reset policy results + // + triggerPolicy = builder.resetPolicyResults(triggerPolicy.id); + assertTrue(builder.getTriggerPolicy().failure.equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().failure_retries.equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().failure_timeout.equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + // + // Test set the policy results to an existing operational policy + // + onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( + onRestartFailurePolicy2.id, + triggerPolicy.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + assertTrue(builder.getTriggerPolicy().failure.equals(onRestartFailurePolicy2.id)); + assertTrue(builder.getTriggerPolicy().failure_retries.equals(onRestartFailurePolicy2.id)); + assertTrue(builder.getTriggerPolicy().failure_timeout.equals(onRestartFailurePolicy2.id)); + + // + // Test remove all existing operational policies + // + builder = builder.removeAllPolicies(); + assertTrue(builder.getControlLoop().trigger_policy.equals(FinalResult.FINAL_OPENLOOP.toString())); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testAddOperationsAccumulateParams() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the eNodeB", + "Upon getting the trigger event, restart the eNodeB", + "SDNR", + new Target(TargetType.PNF), + "Restart", + null, + 2, + 300); + // + // Add the operationsAccumulateParams + // + triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.id, new OperationsAccumulateParams("15m", 5)); + assertNotNull(builder.getTriggerPolicy().operationsAccumulateParams); + assertTrue(builder.getTriggerPolicy().operationsAccumulateParams.period.equals("15m")); + assertTrue(builder.getTriggerPolicy().operationsAccumulateParams.limit == 5); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + + @Test + public void testBuildSpecification() { + try { + // + // Create the builder + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800); + // + // Set the first invalid trigger policy + // + Policy policy1 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + null, + null, + "Instantiate", + null, + 2, + 300); + Results results = builder.buildSpecification(); + // + // Check that ERRORs are in results for invalid policy arguments + // + boolean invalid_actor = false; + boolean invalid_recipe = false; + boolean invalid_target = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_actor = true; + } + if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { + invalid_recipe = true; + } + if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_target = true; + } + } + // + assertTrue(invalid_actor); + assertTrue(invalid_recipe); + assertTrue(invalid_target); + // + // Remove the invalid policy + // + //@SuppressWarnings("unused") + boolean removed = builder.removePolicy(policy1.id); + assertTrue(removed); + assertTrue(builder.getTriggerPolicy() == null); + // + // Set a valid trigger policy + // + policy1 = builder.setTriggerPolicy( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600); + // + // Set a second valid trigger policy + // + Policy policy2 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + // + // Now, we have policy1 unreachable + // + results = builder.buildSpecification(); + boolean unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy " + policy1.id + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + // Set policy1 for the failure results of policy2 + // + policy1 = builder.setPolicyForPolicyResult( + policy1.id, + policy2.id, + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + results = builder.buildSpecification(); + boolean invalid_timeout = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { + invalid_timeout = true; + break; + } + } + assertTrue(invalid_timeout); + // + // Remove policy2 (revert controlLoop back to open loop) + // + removed = builder.removePolicy(policy2.id); + // + // ControlLoop is open loop now, but it still has policies (policy1) + // + results = builder.buildSpecification(); + unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + + @Test + public void test() { + this.test("src/test/resources/v1.0.0/policy_Test.yaml"); + } + + @Test + public void testEvilYaml() { + try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + yaml.load(is); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (YAMLException e) { + // + // Should have this + // + } + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopPolicy); + ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( + policyTobuild.controlLoop.controlLoopName, + policyTobuild.controlLoop.timeout); + // + // Add services + // + if (policyTobuild.controlLoop.services != null) { + builder = builder.addService(policyTobuild.controlLoop.services.toArray(new Service[policyTobuild.controlLoop.services.size()])); + } + // + // Add resources + // + if (policyTobuild.controlLoop.resources != null) { + builder = builder.addResource(policyTobuild.controlLoop.resources.toArray(new Resource[policyTobuild.controlLoop.resources.size()])); + } + // + // Set pnf + // + if (policyTobuild.controlLoop.pnf != null) { + builder = builder.setPNF(policyTobuild.controlLoop.pnf); + } + // + // Add the policies and be sure to set the trigger policy + // + if (policyTobuild.policies != null) { + for (Policy policy : policyTobuild.policies) { + if (policy.id == policyTobuild.controlLoop.trigger_policy) { + builder.setTriggerPolicy(policy.name, policy.description, policy.actor, policy.target, policy.recipe, null, policy.retry, policy.timeout); + } + } + } + + // Question : how to change policy ID and results by using builder ?? + + @SuppressWarnings("unused") + Results results = builder.buildSpecification(); + + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + + } + +} diff --git a/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java new file mode 100644 index 000000000..9e91dc4d3 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.policy; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + + +public class ControlLoopPolicyTest { + @Test + public void testSDNO() { + this.test("src/test/resources/v1.0.0/policy_SDNO_1702.yaml"); + } + + @Test + public void test() { + this.test("src/test/resources/v1.0.0/policy_Test.yaml"); + } + + @Test + public void testMultipleService() { + this.test("src/test/resources/v1.0.0/policy_Test_MultipleService.yaml"); + } + + @Test + public void testF5() { + this.test("src/test/resources/v1.0.0/policy_vSCP_F5_1610.yaml"); + } + + @Test + public void testUSP() { + this.test("src/test/resources/v1.0.0/policy_vUSP_1610.yaml"); + } + + @Test + public void testOpenLoop() { + this.test("src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml"); + } + + @Test + public void testvProbes() { + this.test("src/test/resources/v1.0.0/policy_vProbes_1610.yaml"); + } + + @Test + public void test1707() { + this.test("src/test/resources/v2.0.0/policy_vUSP_1707.yaml"); + } + + @Test + public void testeNodeBALU() { + this.test("src/test/resources/v2.0.0/policy_eNodeB_ALU_1707.yaml"); + } + + @Test + public void testeNodeBEricsson() { + this.test("src/test/resources/v2.0.0/policy_eNodeB_Ericsson_1707.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopPolicy); + dump(obj); + // + // Now dump it to a yaml string + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + yaml = new Yaml(options); + String dumpedYaml = yaml.dump(obj); + System.out.println(dumpedYaml); + // + // Read that string back into our java object + // + Object newObject = yaml.load(dumpedYaml); + dump(newObject); + assertNotNull(newObject); + assertTrue(newObject instanceof ControlLoopPolicy); + // + // Have to comment it out tentatively since it causes junit to fail. + // Seems we cannot use assertEquals here. Need advice. + // + //assertEquals(newObject, obj); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + } + + public void dump(Object obj) { + System.out.println("Dumping " + obj.getClass().getCanonicalName()); + System.out.println(obj.toString()); + } +} 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 new file mode 100644 index 000000000..28e3622f8 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.policy.guard; + +import org.junit.Ignore; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +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.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.poligy.guard.builder.ControlLoopGuardBuilder; + +public class ControlLoopGuardBuilderTest { + + @Ignore + @Test + public void testControlLoopGuard() { + try { + // + // Create a builder + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); + // + // Assert there is no guard policies yet + // + Results results = builder.buildSpecification(); + boolean no_guard_policies = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { + no_guard_policies = true; + break; + } + } + assertTrue(no_guard_policies); + // + // Add a guard policy without limit constraint + // + GuardPolicy policy1 = new GuardPolicy("1111", "guardpolicy1", "guardpolicy1", "APPC", "restart"); + builder = builder.addGuardPolicy(policy1); + // + // Assert there is no limit constraint associated with the only guard policy + // + results = builder.buildSpecification(); + boolean no_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { + no_constraint = true; + break; + } + } + assertTrue(no_constraint); + // + // Add a constraint to policy1 + // + Map<String, String> time_in_range = new HashMap<String, String>(); + time_in_range.put("arg2", "PT5H"); + time_in_range.put("arg3", "PT24H"); + List<String> blacklist = new LinkedList<String>(); + blacklist.add("eNodeB_common_id1"); + blacklist.add("eNodeB_common_id2"); + Map<String, String> duration = new HashMap<String, String>(); + duration.put("value", "10"); + duration.put("units", "minute"); + Constraint cons = new Constraint(5, duration, time_in_range, blacklist); + builder = builder.addLimitConstraint(policy1.id, cons); + // + // Add a duplicate constraint to policy1 + // + builder = builder.addLimitConstraint(policy1.id, cons); + // + // Assert there are duplicate constraints associated with the only guard policy + // + results = builder.buildSpecification(); + boolean duplicate_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { + duplicate_constraint = true; + break; + } + } + assertTrue(duplicate_constraint); + // + // Remove the duplicate constraint + // + builder = builder.removeLimitConstraint(policy1.id, cons); + // + // Add a duplicate guard policy + // + builder = builder.addGuardPolicy(policy1); + builder = builder.addLimitConstraint(policy1.id, cons); + // + // Assert there are duplicate guard policies + // + results = builder.buildSpecification(); + boolean duplicate_guard_policy = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { + duplicate_guard_policy = true; + break; + } + } + assertTrue(duplicate_guard_policy); + // + // Remove the duplicate guard policy + // + builder = builder.removeGuardPolicy(policy1); + // + // Assert there are no Error/Warning message + // + results = builder.buildSpecification(); + assertTrue(results.getMessages().size() == 1); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void test1() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopGuard); + ControlLoopGuard guardTobuild = (ControlLoopGuard) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.guard); + // + // Add guard policy + // + if (guardTobuild.guards != null) { + builder = builder.addGuardPolicy(guardTobuild.guards.toArray(new GuardPolicy[guardTobuild.guards.size()])); + } + // + // Build the specification + // + Results results = builder.buildSpecification(); + // + // Print out the specification + // + System.out.println(results.getSpecification()); + // + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + } +} 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 new file mode 100644 index 000000000..1475553d4 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * policy-yaml unit test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.policy.guard; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + + +public class ControlLoopGuardTest { + + @Test + public void testGuardvDNS() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); + } + + @Test + public void testGuardvUSP() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml"); + } + + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopGuard); + dump(obj); + // + // Now dump it to a yaml string + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + yaml = new Yaml(options); + String dumpedYaml = yaml.dump(obj); + System.out.println(dumpedYaml); + // + // Read that string back into our java object + // + Object newObject = yaml.load(dumpedYaml); + dump(newObject); + assertNotNull(newObject); + assertTrue(newObject instanceof ControlLoopGuard); + // + // Have to comment it out tentatively since it causes junit to fail. + // Seems we cannot use assertEquals here. Need advice. + // + //assertEquals(newObject, obj); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + } + + public void dump(Object obj) { + System.out.println("Dumping " + obj.getClass().getCanonicalName()); + System.out.println(obj.toString()); + } +} diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml new file mode 100644 index 000000000..f6ad68425 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_policies_1.yaml @@ -0,0 +1,25 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: FINAL_FAILURE + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_1.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_1.yaml new file mode 100644 index 000000000..981229c4a --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_1.yaml @@ -0,0 +1,95 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: FOO + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: unique-policy-id-2-healthcheck-restart + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-healthcheck-restart + name: HealthCheck Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-3-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-4-healthcheck-rebuild + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-4-healthcheck-rebuild + name: HealthCheck the Rebuild Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-5-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-6-healthcheck-migrate + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + + - id: unique-policy-id-6-healthcheck-migrate + name: Healthcheck the Migrate Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_2.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_2.yaml new file mode 100644 index 000000000..1f9715b13 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/bad_trigger_2.yaml @@ -0,0 +1,95 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: FINAL_SUCCESS + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: unique-policy-id-2-healthcheck-restart + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-healthcheck-restart + name: HealthCheck Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-3-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-4-healthcheck-rebuild + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-4-healthcheck-rebuild + name: HealthCheck the Rebuild Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-5-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-6-healthcheck-migrate + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + + - id: unique-policy-id-6-healthcheck-migrate + name: Healthcheck the Migrate Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml new file mode 100644 index 000000000..7fd27fa97 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml @@ -0,0 +1,12 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-Open-fac4ae3d-c3f5-4bab-8e54-0a8581ede132 + services: + - serviceName: Service + resources: + - resourceType: VF + resourceName: Example + trigger_policy: final_openloop + timeout: 0 + +policies: diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_SDNO_1702.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_SDNO_1702.yaml new file mode 100644 index 000000000..339950f6f --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_SDNO_1702.yaml @@ -0,0 +1,26 @@ +controlLoop: + version: 1.0.0 + controlLoopName: PoloControlLoop-vPE-248b154b-ff3f-458f-885c-ec290c615714 + services: + - serviceName: vPE + trigger_policy: unique-policy-id-1-healthdianostic + timeout: 600 + +policies: + - id: unique-policy-id-1-healthdiagnostic + name: Do SDNO Health Diagnostic + description: + actor: SDNO + recipe: health-diagnostic + payload: + health-diagnostic-code: HC99 + health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" + target: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception +
\ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test.yaml new file mode 100644 index 000000000..b89a725cf --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test.yaml @@ -0,0 +1,95 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: unique-policy-id-2-healthcheck-restart + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-healthcheck-restart + name: HealthCheck Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-3-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-4-healthcheck-rebuild + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-4-healthcheck-rebuild + name: HealthCheck the Rebuild Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-5-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-6-healthcheck-migrate + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + + - id: unique-policy-id-6-healthcheck-migrate + name: Healthcheck the Migrate Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml new file mode 100644 index 000000000..8ce707729 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml @@ -0,0 +1,26 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ClosedLoop-FRWL-SIG-d925ed73-8231-4d02-9545-db4e101f88f8 + services: + - serviceName: vSCP + - serviceName: vSBG + resources: + - resourceName: F5FW + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vProbes_1610.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vProbes_1610.yaml new file mode 100644 index 000000000..2a5f513ab --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vProbes_1610.yaml @@ -0,0 +1,24 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ControlLoop-vProbes-41aba939-9a93-4535-b193-973c68fc8763 + services: + resources: + - resourceName: vProbes + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 600 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vSCP_F5_1610.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vSCP_F5_1610.yaml new file mode 100644 index 000000000..7feaecf7e --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vSCP_F5_1610.yaml @@ -0,0 +1,26 @@ +controlLoop: + version: 1.0.0 + controlLoopName: ClosedLoop-FRWL-SIG-d925ed73-8231-4d02-9545-db4e101f88f8 + services: + - serviceName: vSCP + - serviceName: trinity + resources: + - resourceName: F5FW + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vUSP_1610.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vUSP_1610.yaml new file mode 100644 index 000000000..aebde931e --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/policy_vUSP_1610.yaml @@ -0,0 +1,61 @@ +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: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: 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: VM + retry: 0 + timeout: 600 + success: final_success + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: 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: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml new file mode 100644 index 000000000..b89a725cf --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test.yaml @@ -0,0 +1,95 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: APPC + recipe: Restart + target: VM + retry: 2 + timeout: 300 + success: unique-policy-id-2-healthcheck-restart + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-2-healthcheck-restart + name: HealthCheck Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-3-rebuild + failure_timeout: unique-policy-id-3-rebuild + failure_retries: unique-policy-id-3-rebuild + failure_exception: final_failure_exception + + - id: unique-policy-id-3-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-4-healthcheck-rebuild + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-4-healthcheck-rebuild + name: HealthCheck the Rebuild Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: unique-policy-id-5-migrate + failure_timeout: unique-policy-id-5-migrate + failure_retries: unique-policy-id-5-migrate + failure_exception: final_failure_exception + + - id: unique-policy-id-5-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: VM + retry: 0 + timeout: 600 + success: unique-policy-id-6-healthcheck-migrate + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + + - id: unique-policy-id-6-healthcheck-migrate + name: Healthcheck the Migrate Policy + description: + actor: APPC + recipe: HealthCheck + target: VM + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test_evil.yaml b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test_evil.yaml new file mode 100644 index 000000000..347e84e5e --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v1.0.0/test_evil.yaml @@ -0,0 +1,25 @@ +controlLoop: + controlLoopName: ControlLoop-TEST-5dfa8fce-bd7a-4424-b60d-ee2ad2f254a3 + version: 1.0.0 + services: + - serviceName: Foo Service + resources: + - resourceName: Bar VNF + resourceType: VF + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy for Trigger Event + description: + actor: MSO + recipe: Instantiate + target: VM + retry: 2 + timeout: 300 + success: final_failure_exception + failure: final_success + failure_timeout: final_success + failure_retries: final_success + failure_exception: final_failure_exception diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml new file mode 100644 index 000000000..adb1ca171 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml @@ -0,0 +1,21 @@ +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 + time_in_range: + arg2: PT5H + arg3: PT24H + # + - num: 5 + time_in_range: + arg2: PT5H + arg3: PT24H
\ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml new file mode 100644 index 000000000..2d54e8517 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml @@ -0,0 +1,27 @@ +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 + time_in_range: + arg2: PT5H + arg3: PT24H + # + - 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 + time_in_range: + arg2: PT5H + arg3: PT24H
\ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml new file mode 100644 index 000000000..6ab3d67fa --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml @@ -0,0 +1,11 @@ +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 +
\ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_policy.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_policy.yaml new file mode 100644 index 000000000..51f41d457 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/no_guard_policy.yaml @@ -0,0 +1,2 @@ +guard: + version: 2.0.0 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 new file mode 100644 index 000000000..7b5f17c61 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml @@ -0,0 +1,14 @@ +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~ new file mode 100644 index 000000000..a0d76d225 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml~ @@ -0,0 +1,12 @@ +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_vUSP_1707_appc.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml new file mode 100644 index 000000000..a487210cd --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0-guard/policy_guard_vUSP_1707_appc.yaml @@ -0,0 +1,26 @@ +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/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml new file mode 100644 index 000000000..f3e9bc4e4 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml @@ -0,0 +1,1698 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 + UUID: d7d28881-b24d-4512-bfee-1e2eb335591f + name: 59a2ee3f-b580-45fe-b5a1 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + resourceVendor: 185c637a-3885-463e-8fd0 + resourceVendorRelease: '1.0' +imports: +- NeutronNet: + file: resource-Neutronnet-template.yml +- NeutronPort: + file: resource-Neutronport-template.yml +- 59a2ee3fB58045feB5a1.nodes.heat.vlb: + file: resource-59a2ee3fb58045feb5a1NodesHeatVlb-template.yml +- 59a2ee3fB58045feB5a1.nodes.heat.vdns: + file: resource-59a2ee3fb58045feb5a1NodesHeatVdns-template.yml +topology_template: + inputs: + vf_module_id: + type: string + description: The vLoadBalancer Module ID is provided by ECOMP + ecomp_private_subnet_id: + type: string + description: Private sub-network that connects ECOMP component and the VNF + repo_url_blob: + type: string + description: URL of the repository that hosts the demo packages + vlb_private_net_cidr: + type: string + description: The CIDR of the vLoadBalancer private network + vlb_private_net_id: + type: string + description: Private network that connects vLoadBalancer with vDNSs + public_net_id: + type: string + default: 00000000-0000-0000-0000-000000000000 + description: Public network that enables remote connection to VNF + demo_artifacts_version: + type: string + description: Artifacts (jar, tar.gz) version used in demo vnfs + ecomp_private_net_id: + type: string + description: Private network that connects ECOMP component and the VNF + pub_key: + type: string + description: Public key to be installed on the compute instance + vlb_private_ip_1: + type: string + description: Private IP address that is assigned to the vLoadBalancer to communicate with ECOMP components + key_name: + type: string + description: Public/Private key pair name + vdns_name_0: + type: string + description: Name of the vDNS + repo_url_artifacts: + type: string + description: URL of the repository that hosts the demo packages + vlb_name_0: + type: string + description: Name of the vLoadBalancer + vdns_private_ip_0: + type: string + description: Private IP address that is assigned to the vDNS to communicate with the vLoadBalancer + vnf_id: + type: string + description: The VNF ID is provided by ECOMP + dcae_collector_ip: + type: string + description: IP address of the DCAE collector + vdns_private_ip_1: + type: string + description: Private IP address that is assigned to the vDNS to communicate with ECOMP components + dcae_collector_port: + type: string + description: Port of the DCAE collector + vlb_image_name: + type: string + default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) + description: Image to be used for compute instance + vlb_flavor_name: + type: string + default: 4 GB General Purpose v1 + description: Type of instance (flavor) to be used + vlb_private_ip_0: + type: string + description: Private IP address that is assigned to the vLoadBalancer to communicate with the vDNSs + ecomp_private_net_cidr: + type: string + description: The CIDR of the protected private network + node_templates: + vdns_private_1_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: ecomp_private_subnet_id + ip_address: + get_input: vdns_private_ip_1 + network: + get_input: ecomp_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vdns_0 + relationship: tosca.relationships.network.BindsTo + vlb_private_network: + type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: vlb_private_net_id + subnets: + vlb_private_subnet: + name: + get_input: vlb_private_net_id + cidr: + get_input: vlb_private_net_cidr + vlb_private_1_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: ecomp_private_subnet_id + ip_address: + get_input: vlb_private_ip_1 + network: + get_input: ecomp_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vlb_0 + relationship: tosca.relationships.network.BindsTo + vdns_0: + type: org.openecomp.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vdns + metadata: + invariantUUID: ee585c30-127b-492e-b2c1-871dc61d1dde + UUID: d816cb01-b5d0-4bbb-b614-f7c3e230ab19 + version: '1.0' + name: 59a2ee3fB58045feB5a1.nodes.heat.vdns + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vlb_flavor_name + image: + get_input: vlb_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vdns_name_0 + vlb_private_0_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: vlb_private_network + ip_address: + get_input: vlb_private_ip_0 + network: vlb_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: vlb_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vlb_0 + relationship: tosca.relationships.network.BindsTo + vdns_private_0_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: vlb_private_net_id + ip_address: + get_input: vdns_private_ip_0 + network: + get_input: vlb_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vdns_0 + relationship: tosca.relationships.network.BindsTo + vlb_0: + type: org.openecomp.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vlb + metadata: + invariantUUID: f7f1d745-cfb1-4aa9-83fc-31280d0ce513 + UUID: 1821f13e-411f-4b29-87a5-ae935897b2e1 + version: '1.0' + name: 59a2ee3fB58045feB5a1.nodes.heat.vlb + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vlb_flavor_name + image: + get_input: vlb_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vlb_name_0 + groups: + base_vlb: + type: org.openecomp.groups.heat.HeatStack + members: + - vdns_private_1_port + - vlb_private_network + - vlb_private_1_port + - vdns_0 + - vlb_private_0_port + - vdns_private_0_port + - vlb_0 + metadata: + invariantUUID: 097f71b3-90a1-4064-bc83-f76bf30195fe + UUID: 4daf7600-0a06-4515-859a-c45ec11abd29 + version: '1' + name: base_vlb + 59a2ee3fB58045feB5a1..dnsscaling..module-1: + type: org.openecomp.groups.VfModule + members: + - vdns_private_1_port + - vdns_0 + - vdns_private_0_port + metadata: + vfModuleModelName: 59a2ee3fB58045feB5a1..dnsscaling..module-1 + vfModuleModelInvariantUUID: 395d61a9-309b-4c0f-a442-ca47903e231e + vfModuleModelUUID: 40846490-abf4-4e1d-8f1a-2286968fa231 + vfModuleModelVersion: '1' + properties: + vf_module_type: Expansion + vf_module_description: + volume_group: false + 59a2ee3fB58045feB5a1..base_vlb..module-0: + type: org.openecomp.groups.VfModule + members: + - vdns_private_1_port + - vlb_private_network + - vlb_private_1_port + - vdns_0 + - vlb_private_0_port + - vdns_private_0_port + - vlb_0 + metadata: + vfModuleModelName: 59a2ee3fB58045feB5a1..base_vlb..module-0 + vfModuleModelInvariantUUID: 5ae76f74-6324-4835-a86c-0c96d16afd38 + vfModuleModelUUID: 17c4f752-a3da-4f3d-9cc5-1c4d28e5442d + vfModuleModelVersion: '1' + properties: + vf_module_type: Base + vf_module_description: + volume_group: false + dnsscaling: + type: org.openecomp.groups.heat.HeatStack + members: + - vdns_private_1_port + - vdns_0 + - vdns_private_0_port + metadata: + invariantUUID: 7c2971fa-9369-4fed-a449-a5e21c022f97 + UUID: ae8c3b79-77d3-425a-8bab-6558007f8392 + version: '1' + name: dnsscaling + substitution_mappings: + node_type: org.openecomp.resource.vf.59a2ee3fB58045feB5a1 + capabilities: + vdns_0.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vdns_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vlb_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vlb_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vlb_0.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vlb_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_0.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vlb_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vlb_0.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vlb_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vlb_0.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vdns_0.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vdns_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vdns_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_0.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + requirements: + vdns_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vlb_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vdns_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vdns_private_0_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vdns_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vlb_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vdns_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vdns_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml new file mode 100644 index 000000000..3ce20b597 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml @@ -0,0 +1,2525 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 + UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a + name: eace9331-04d4-43b4-96b8 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + resourceVendor: 31125954-23a0-4d41-95e5 + resourceVendorRelease: '1.0' +imports: +- NeutronPort: + file: resource-Neutronport-template.yml +- Eace933104d443b496b8.nodes.heat.vfw: + file: resource-Eace933104d443b496b8NodesHeatVfw-template.yml +- Eace933104d443b496b8.nodes.heat.vpg: + file: resource-Eace933104d443b496b8NodesHeatVpg-template.yml +- NeutronNet: + file: resource-Neutronnet-template.yml +- Eace933104d443b496b8.nodes.heat.vsn: + file: resource-Eace933104d443b496b8NodesHeatVsn-template.yml +topology_template: + inputs: + vf_module_id: + type: string + description: The vFirewall Module ID is provided by ECOMP + repo_url_blob: + type: string + description: URL of the repository that hosts the demo packages + public_net_id: + type: string + default: 00000000-0000-0000-0000-000000000000 + description: Public network that enables remote connection to VNF + vfw_private_ip_1: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with the vSink + vfw_private_ip_0: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with the vPacketGenerator + vfw_private_ip_2: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with ECOMP components + vfw_name_0: + type: string + description: Name of the vFirewall + vnf_id: + type: string + description: The VNF ID is provided by ECOMP + dcae_collector_ip: + type: string + description: IP address of the DCAE collector + dcae_collector_port: + type: string + description: Port of the DCAE collector + vpg_private_ip_1: + type: string + description: Private IP address that is assigned to the vPacketGenerator to communicate with ECOMP components + vsn_private_ip_0: + type: string + description: Private IP address that is assigned to the vSink to communicate with the vFirewall + vpg_name_0: + type: string + description: Name of the vPacketGenerator + vpg_private_ip_0: + type: string + description: Private IP address that is assigned to the vPacketGenerator to communicate with the vFirewall + vsn_private_ip_1: + type: string + description: Private IP address that is assigned to the vSink to communicate with ECOMP components + protected_private_net_cidr: + type: string + description: The CIDR of the protected private network + ecomp_private_net_cidr: + type: string + description: The CIDR of the protected private network + unprotected_private_net_cidr: + type: string + description: The CIDR of the unprotected private network + ecomp_private_subnet_id: + type: string + description: Private sub-network that connects ECOMP component and the VNF + vsn_name_0: + type: string + description: Name of the vSink + unprotected_private_net_id: + type: string + description: Private network that connects vPacketGenerator with vFirewall + vfw_flavor_name: + type: string + default: 4 GB General Purpose v1 + description: Type of instance (flavor) to be used + demo_artifacts_version: + type: string + description: Artifacts (jar, tar.gz) version used in demo vnfs + ecomp_private_net_id: + type: string + description: Private network that connects ECOMP component and the VNF + pub_key: + type: string + description: Public key to be installed on the compute instance + key_name: + type: string + description: Public/Private key pair name + repo_url_artifacts: + type: string + description: URL of the repository that hosts the demo packages + vfw_image_name: + type: string + default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) + description: Image to be used for compute instance + protected_private_net_id: + type: string + description: Private network that connects vFirewall with vSink + node_templates: + vfw_private_0_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: unprotected_private_network + ip_address: + get_input: vfw_private_ip_0 + network: unprotected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: unprotected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vsn_private_1_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: ecomp_private_subnet_id + ip_address: + get_input: vsn_private_ip_1 + network: + get_input: ecomp_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vsn_0 + relationship: tosca.relationships.network.BindsTo + unprotected_private_network: + type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: unprotected_private_net_id + subnets: + unprotected_private_subnet: + cidr: + get_input: unprotected_private_net_cidr + vpg_private_1_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: ecomp_private_subnet_id + ip_address: + get_input: vpg_private_ip_1 + network: + get_input: ecomp_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vpg_0 + relationship: tosca.relationships.network.BindsTo + vfw_0: + type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vfw + metadata: + invariantUUID: 0129e34c-d9fa-442d-bb2c-f925d018000a + UUID: 7fa1f6c7-c6bd-4444-8db2-63334a5aed1b + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vfw + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vfw_name_0 + vsn_0: + type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vsn + metadata: + invariantUUID: b19f6643-3db0-4d73-b280-94d6f21caa71 + UUID: 6dca6eb9-330c-4090-a542-7aca5f446e21 + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vsn + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vsn_name_0 + vpg_private_0_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: unprotected_private_network + ip_address: + get_input: vpg_private_ip_0 + network: unprotected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: unprotected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vpg_0 + relationship: tosca.relationships.network.BindsTo + vsn_private_0_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: protected_private_network + ip_address: + get_input: vsn_private_ip_0 + network: protected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: protected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vsn_0 + relationship: tosca.relationships.network.BindsTo + vfw_private_1_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: protected_private_network + ip_address: + get_input: vfw_private_ip_1 + network: protected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: protected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vfw_private_2_port: + type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: ecomp_private_subnet_id + ip_address: + get_input: vfw_private_ip_2 + network: + get_input: ecomp_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vpg_0: + type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vpg + metadata: + invariantUUID: 7654ae14-4e98-45bc-a8c0-2c43e1805bb4 + UUID: 5267d6dd-f676-4f98-abec-6387ce6beaf2 + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vpg + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vpg_name_0 + protected_private_network: + type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: protected_private_net_id + subnets: + protected_private_subnet: + cidr: + get_input: protected_private_net_cidr + groups: + base_vfw: + type: org.openecomp.groups.heat.HeatStack + members: + - vfw_private_0_port + - vsn_private_1_port + - unprotected_private_network + - vpg_private_1_port + - vfw_0 + - vsn_0 + - vpg_private_0_port + - vsn_private_0_port + - vfw_private_1_port + - vfw_private_2_port + - vpg_0 + - protected_private_network + metadata: + invariantUUID: 44b0c172-7b61-49b5-a68a-810042087e1f + UUID: 24cb02f0-1d72-441f-a327-22d80180deaa + version: '1' + name: base_vfw + Eace933104d443b496b8..base_vfw..module-0: + type: org.openecomp.groups.VfModule + members: + - vfw_private_0_port + - vsn_private_1_port + - unprotected_private_network + - vpg_private_1_port + - vfw_0 + - vsn_0 + - vpg_private_0_port + - vsn_private_0_port + - vfw_private_1_port + - vfw_private_2_port + - vpg_0 + - protected_private_network + metadata: + vfModuleModelName: Eace933104d443b496b8..base_vfw..module-0 + vfModuleModelInvariantUUID: 58c105fd-9c12-4fb7-8a3e-a5ec280183fb + vfModuleModelUUID: ab251d24-4001-4926-aa5c-c01736b36c68 + vfModuleModelVersion: '1' + properties: + vf_module_type: Base + vf_module_description: + volume_group: false + substitution_mappings: + node_type: org.openecomp.resource.vf.Eace933104d443b496b8 + capabilities: + vfw_0.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vfw_0.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + protected_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vsn_0.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + unprotected_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vpg_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vpg_0.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vpg_0.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_2_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vfw_0.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vsn_0.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vsn_0.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vsn_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vsn_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_0.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + unprotected_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vfw_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_private_2_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + unprotected_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_0.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vpg_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + protected_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vpg_0.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vsn_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vfw_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + protected_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vsn_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + requirements: + vsn_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vfw_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vfw_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vsn_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + protected_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_2_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_2_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + unprotected_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vsn_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vsn_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vsn_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml new file mode 100644 index 000000000..b59c85269 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml @@ -0,0 +1,677 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 5cfe6f4a-41bc-4247-8674-ebd4b98e35cc + UUID: 0f40bba5-986e-4b3c-803f-ddd1b7b25f24 + name: 57e66ea7-0ed6-45c7-970f + description: catalog service description + type: Service + category: Network L1-3 + serviceEcompNaming: false + serviceHoming: false +imports: +- eace9331-04d4-43b4-96b8: + file: resource-Eace933104d443b496b8-template.yml +topology_template: + node_templates: + eace9331-04d4-43b4-96b8 1: + type: org.openecomp.resource.vf.Eace933104d443b496b8 + metadata: + invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 + UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a + version: '1.0' + name: eace9331-04d4-43b4-96b8 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + substitution_mappings: + node_type: org.openecomp.service.57e66ea70ed645c7970f + capabilities: + eace9331-04d4-43b4-96b8 1.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + eace9331-04d4-43b4-96b8 1.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + eace9331-04d4-43b4-96b8 1.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + eace9331-04d4-43b4-96b8 1.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + requirements: + eace9331-04d4-43b4-96b8 1.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + eace9331-04d4-43b4-96b8 1.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + eace9331-04d4-43b4-96b8 1.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml new file mode 100644 index 000000000..302cacc0a --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml @@ -0,0 +1,677 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: dc112d6e-7e73-4777-9c6f-1a7fb5fd1b6f + UUID: 2eea06c6-e1d3-4c3a-b9c4-478c506eeedf + name: d4738992-6497-4dca-9db9 + description: catalog service description + type: Service + category: Network L1-3 + serviceEcompNaming: false + serviceHoming: false +imports: +- 59a2ee3f-b580-45fe-b5a1: + file: resource-59a2ee3fB58045feB5a1-template.yml +topology_template: + node_templates: + 59a2ee3f-b580-45fe-b5a1 1: + type: org.openecomp.resource.vf.59a2ee3fB58045feB5a1 + metadata: + invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 + UUID: d7d28881-b24d-4512-bfee-1e2eb335591f + version: '1.0' + name: 59a2ee3f-b580-45fe-b5a1 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + substitution_mappings: + node_type: org.openecomp.service.D473899264974dca9db9 + capabilities: + 59a2ee3f-b580-45fe-b5a1 1.memory.resident: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.vcpus: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + 59a2ee3f-b580-45fe-b5a1 1.memory.usage: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.instance: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + 59a2ee3f-b580-45fe-b5a1 1.cpu_util: + type: org.openecomp.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.instance:type: + type: org.openecomp.capabilities.metric.Ceilometer + description: Existence of instance <type> (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.cpu.delta: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.memory: + type: org.openecomp.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.cpu: + type: org.openecomp.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + requirements: + 59a2ee3f-b580-45fe-b5a1 1.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + 59a2ee3f-b580-45fe-b5a1 1.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + 59a2ee3f-b580-45fe-b5a1 1.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/pgstreams.json b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/pgstreams.json new file mode 100644 index 000000000..4d118afa1 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/pgstreams.json @@ -0,0 +1,26 @@ +{ + "pg-streams": { + "pg-stream": [ + { + "id": "fw_udp1", + "is-enabled": "true" + }, + { + "id": "fw_udp2", + "is-enabled": "true" + }, + { + "id": "fw_udp3", + "is-enabled": "true" + }, + { + "id": "fw_udp4", + "is-enabled": "true" + }, + { + "id": "fw_udp5", + "is-enabled": "true" + } + ] + } +}
\ No newline at end of file diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml new file mode 100644 index 000000000..5deb8f7ff --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml @@ -0,0 +1,47 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3 + services: + - serviceName: d4738992-6497-4dca-9db9 + serviceInvariantUUID: dc112d6e-7e73-4777-9c6f-1a7fb5fd1b6f + serviceUUID: 2eea06c6-e1d3-4c3a-b9c4-478c506eeedf +# +# OPTIONAL to specify the exact resource VF and/or VFC(s) +# +# resources: +# - resourceInvariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 +# resourceUUID: d7d28881-b24d-4512-bfee-1e2eb335591f +# resourceVersion: '1.0' +# resourceName: 59a2ee3f-b580-45fe-b5a1 +# resourceType: VF +# +# resources: +# - resourceInvariantUUID: ee585c30-127b-492e-b2c1-871dc61d1dde +# resourceUUID: d816cb01-b5d0-4bbb-b614-f7c3e230ab19 +# resourceVersion: '1.0' +# resourceName: 59a2ee3fB58045feB5a1.nodes.heat.vdns +# resourceType: VFC +# - resourceInvariantUUID: f7f1d745-cfb1-4aa9-83fc-31280d0ce513 +# resourceUUID: 1821f13e-411f-4b29-87a5-ae935897b2e1 +# resourceVersion: '1.0' +# resourceName: 59a2ee3fB58045feB5a1.nodes.heat.vlb +# resourceType: VFC + trigger_policy: unique-policy-id-1-scale-up + timeout: 1200 + +policies: + - id: unique-policy-id-1-scale-up + name: Create a new VF Module + description: + actor: MSO + recipe: VF Module Create + target: + resourceID: 59a2ee3fB58045feB5a1.nodes.heat.vdns + retry: 0 + timeout: 1200 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml new file mode 100644 index 000000000..51597714c --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml @@ -0,0 +1,58 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a + services: + - serviceInvariantUUID: 5cfe6f4a-41bc-4247-8674-ebd4b98e35cc + serviceUUID: 0f40bba5-986e-4b3c-803f-ddd1b7b25f24 + serviceName: 57e66ea7-0ed6-45c7-970f +# +# OPTIONAL +# +# IF they want this CL restricted to a particular VFC(s) +# +#resources: +# - resourceInvariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 +# resourceUUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a +# resourceVersion: '1.0' +# resourceName: eace9331-04d4-43b4-96b8 +# resourceType: VF + +# resources: +# - resourceType: VFC +# resourceInvariantUUID: b19f6643-3db0-4d73-b280-94d6f21caa71 +# resourceUUID: 6dca6eb9-330c-4090-a542-7aca5f446e21 +# resourceVersion: '1.0' +# resourceName: Eace933104d443b496b8.nodes.heat.vsn +# - resourceName: vFW +# resourceType: VFC +# resourceInvariantUUID: 0129e34c-d9fa-442d-bb2c-f925d018000a +# resourceUUID: 7fa1f6c7-c6bd-4444-8db2-63334a5aed1b +# resourceVersion: '1.0' +# resourceName: Eace933104d443b496b8.nodes.heat.vfw +# - resourceType: VFC +# resourceInvariantUUID: 7654ae14-4e98-45bc-a8c0-2c43e1805bb4 +# resourceUUID: 5267d6dd-f676-4f98-abec-6387ce6beaf2 +# resourceVersion: '1.0' +# resourceName: Eace933104d443b496b8.nodes.heat.vpg + trigger_policy: unique-policy-id-1-modifyConfig + timeout: 1200 + +policies: + - id: unique-policy-id-1-modifyConfig + name: Change the Load Balancer + description: + actor: APPC + recipe: ModifyConfig + target: + resourceID: Eace933104d443b496b8.nodes.heat.vpg + payload: + generic-vnf.vnf-id: {generic-vnf.vnf-id} + ref$: pgstreams.json + retry: 0 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_ALU_1707.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_ALU_1707.yaml new file mode 100644 index 000000000..9f41f46d9 --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_ALU_1707.yaml @@ -0,0 +1,72 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-eNodeB-ALU-3ee91181-6f05-4cd3-8437-cad5f58653ca + services: + resources: + pnf: + PNFName: eNodeB.ALU + trigger_policy: unique-policy-id-1-check-aots + timeout: 2400 + +policies: + - id: unique-policy-id-1-check-aots + name: Check AOTS CTS + description: Discard sleeping cell based on the new signature if it appears in recent CTS tickets + actor: AOTS + recipe: checkENodeBTicketHours + payload: + timeWindow: 5 + retry: 2 + timeout: 300 + success: unique-policy-id-2-check-aots-cts + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-2-check-aots-cts + name: Check AOTS CTS Equipment + description: Discard sleeping cell based on the new signature if it is not active in CTS equipment data + actor: AOTS + recipe: checkEquipmentStatus + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-eim + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-3-check-aots-eim + name: Check AOTS EIM_RT + description: Discard sleeping cell based on the new signature if it appears in EIM_RT data + actor: AOTS + recipe: checkEimStatus + retry: 2 + timeout: 300 + success: unique-policy-id-4-sdnr-reset + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-4-sdnr-reset + name: Have SDNR Reset + description: SDNR should now reset this sleeper + actor: SDNR + recipe: Reset + operationsAccumulateParams: + period: 15m + limit: 5 + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_Ericsson_1707.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_Ericsson_1707.yaml new file mode 100644 index 000000000..9eff3439d --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_eNodeB_Ericsson_1707.yaml @@ -0,0 +1,86 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-eNodeB-Ericsson-0732e76a-4228-42d1-8185-972510be388c + services: + resources: + pnf: + PNFName: eNodeB.Ericsson + trigger_policy: unique-policy-id-1-check-aots-ticket + timeout: 2400 + +policies: + - id: unique-policy-id-1-check-aots-ticket + name: Check AOTS CTS + description: Discard sleeping cell based on the new signature if it appears in recent CTS tickets + actor: AOTS + recipe: checkENodeBTicketHours + payload: + timeWindow: 5 + retry: 2 + timeout: 300 + success: unique-policy-id-2-check-aots-cts + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-2-check-aots-cts + name: Check AOTS CTS Equipment + description: Discard sleeping cell based on the new signature if it is not active in CTS equipment data + actor: AOTS + recipe: checkEquipmentStatus + payload: + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-eim + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-3-check-aots-eim + name: Check AOTS EIM_RT + description: Discard sleeping cell based on the new signature if it appears in EIM_RT data + actor: AOTS + recipe: checkEimStatus + retry: 2 + timeout: 300 + success: unique-policy-id-3-check-aots-maintenance + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-4-check-aots-maintenance + name: Check AOTS MAINTENANCE + description: Discard sleeping cell based on the new signature if it appears in Maintenance + actor: AOTS + recipe: checkMaintenanceWindow + retry: 2 + timeout: 300 + success: unique-policy-id-5-sdnr-reset + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-5-sdnr-reset + name: Have SDNR Reset + description: SDNR should now reset this sleeper + actor: SDNR + recipe: Reset + operationsAccumulateParams: + period: 15m + limit: 5 + retry: 2 + timeout: 300 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard diff --git a/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vUSP_1707.yaml b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vUSP_1707.yaml new file mode 100644 index 000000000..b1b03f4ee --- /dev/null +++ b/controlloop/common/policy-yaml/src/test/resources/v2.0.0/policy_vUSP_1707.yaml @@ -0,0 +1,107 @@ +controlLoop: + version: 2.0.0 + controlLoopName: ControlLoop-vUSP-vCTS-cbed919f-2212-4ef7-8051-fe6308da1bda + services: + - serviceName: vUSP + resources: + - resourceName: vCTS + resourceType: VFC + - resourceName: vCOM + resourceType: VFC + - resourceName: vRAR + resourceType: VFC + - resourceName: vLCS + resourceType: VFC + - resourceName: v3CB + resourceType: VFC + trigger_policy: unique-policy-id-1-restart + timeout: 1200 + abatement: false + +policies: + - id: unique-policy-id-1-restart + name: Restart Policy + description: + actor: APPC + recipe: Restart + target: + type: VM + retry: 2 + timeout: 300 + success: unique-policy-id-1-healthdiagnostic + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + failure_guard: unique-policy-id-2-rebuild + + - id: unique-policy-id-2-rebuild + name: Rebuild Policy + description: + actor: APPC + recipe: Rebuild + target: + type: VM + retry: 0 + timeout: 600 + success: unique-policy-id-2-healthdiagnostic + failure: unique-policy-id-3-migrate + failure_timeout: unique-policy-id-3-migrate + failure_retries: unique-policy-id-3-migrate + failure_exception: final_failure_exception + failure_guard: unique-policy-id-3-migrate + + - id: unique-policy-id-3-migrate + name: Migrate Policy + description: + actor: APPC + recipe: Migrate + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + + - id: unique-policy-id-1-healthdiagnostic + name: Do SDNO Health Diagnostic + description: + actor: SDNO + recipe: health-diagnostic + payload: + health-diagnostic-code: HC99 + health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: unique-policy-id-2-rebuild + failure_timeout: unique-policy-id-2-rebuild + failure_retries: unique-policy-id-2-rebuild + failure_exception: final_failure_exception + failure_guard: unique-policy-id-2-rebuild + + - id: unique-policy-id-2-healthdiagnostic + name: Do SDNO Health Diagnostic + description: + actor: SDNO + recipe: health-diagnostic + payload: + health-diagnostic-code: HC99 + health-diagnostic-code-parameters: "{\"Junk\":\"--version\",\"Junk2\":\"--help\"}" + target: + type: VM + retry: 0 + timeout: 600 + success: final_success + failure: final_failure + failure_timeout: final_failure_timeout + failure_retries: final_failure_retries + failure_exception: final_failure_exception + failure_guard: final_failure_guard + diff --git a/controlloop/common/pom.xml b/controlloop/common/pom.xml new file mode 100644 index 000000000..76f788a38 --- /dev/null +++ b/controlloop/common/pom.xml @@ -0,0 +1,45 @@ +<!-- + ============LICENSE_START======================================================= + Drools PDP Application Common Models + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <artifactId>common</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>controlloop</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>actors</module> + <module>eventmanager</module> + <module>guard</module> + <module>model-impl</module> + <module>packages</module> + <module>policy-yaml</module> + </modules> + + +</project> diff --git a/controlloop/pom.xml b/controlloop/pom.xml index ea5621042..8cb9ef415 100644 --- a/controlloop/pom.xml +++ b/controlloop/pom.xml @@ -1,6 +1,6 @@ <!-- ============LICENSE_START======================================================= - Drools PDP Application Models + drools-pdp-apps ================================================================================ Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. ================================================================================ @@ -18,29 +18,24 @@ ============LICENSE_END========================================================= --> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <artifactId>controlloop</artifactId> + <modelVersion>4.0.0</modelVersion> + + <artifactId>controlloop</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>drools-pdp-apps</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>common</module> + <module>templates</module> + </modules> - <parent> - <groupId>org.openecomp.policy.drools-applications</groupId> - <artifactId>drools-pdp-apps</artifactId> - <version>1.1.0-SNAPSHOT</version> - </parent> - <dependencies> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>4.12</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>com.google.code.gson</groupId> - <artifactId>gson</artifactId> - <version>2.5</version> - <scope>provided</scope> - </dependency> - </dependencies> </project> diff --git a/controlloop/templates/pom.xml b/controlloop/templates/pom.xml new file mode 100644 index 000000000..046ccee6e --- /dev/null +++ b/controlloop/templates/pom.xml @@ -0,0 +1,41 @@ +<!-- + ============LICENSE_START======================================================= + drools-pdp-apps Control Loop Drools Templates + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <artifactId>templates</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>controlloop</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>template.demo</module> + <module>template.demo.v1.0.0</module> + </modules> + + +</project> diff --git a/controlloop/templates/template.demo.v1.0.0/README.md b/controlloop/templates/template.demo.v1.0.0/README.md new file mode 100644 index 000000000..3d5a32dcd --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/README.md @@ -0,0 +1,2 @@ + +This is the legacy template to support vFW/vDNS W/O integration with AAI. diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/pom.xml b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/pom.xml new file mode 100644 index 000000000..2e43a6019 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/pom.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + drools-pdp-apps Control Loop Drools Templates + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>template.demo.v1.0.0</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>archetype-closedloop-demo-rules</artifactId> + <packaging>maven-archetype</packaging> + + <name>archetype-closed-loop-demo-rules</name> + <description>archetype to generate a closed loop demo rules jar</description> + + <build> + <extensions> + <extension> + <groupId>org.apache.maven.archetype</groupId> + <artifactId>archetype-packaging</artifactId> + <version>2.4</version> + </extension> + </extensions> + + <pluginManagement> + <plugins> + <plugin> + <artifactId>maven-archetype-plugin</artifactId> + <version>2.4</version> + </plugin> + </plugins> + </pluginManagement> + </build> + +</project> diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/META-INF/maven/archetype-metadata.xml b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 000000000..a0b5506fc --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + archetype-closed-loop-demo-rules + ================================================================================ + 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========================================================= + --> + +<archetype-descriptor xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd" + name="closed-loop-rules" + xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + + <requiredProperties> + <requiredProperty key="closedLoopControlName"></requiredProperty> + <requiredProperty key="policyScope"></requiredProperty> + <requiredProperty key="policyName"></requiredProperty> + <requiredProperty key="policyVersion"></requiredProperty> + <requiredProperty key="actor"></requiredProperty> + <requiredProperty key="aaiURL"></requiredProperty> + <requiredProperty key="aaiUsername"></requiredProperty> + <requiredProperty key="aaiPassword"></requiredProperty> + <requiredProperty key="aaiNamedQueryUUID"></requiredProperty> + <requiredProperty key="aaiPatternMatch"></requiredProperty> + <requiredProperty key="msoURL"></requiredProperty> + <requiredProperty key="msoUsername"></requiredProperty> + <requiredProperty key="msoPassword"></requiredProperty> + <requiredProperty key="appcTopic"></requiredProperty> + <requiredProperty key="appcServers"></requiredProperty> + <requiredProperty key="appcApiKey"></requiredProperty> + <requiredProperty key="appcApiSecret"></requiredProperty> + <requiredProperty key="notificationTopic"></requiredProperty> + <requiredProperty key="notificationServers"></requiredProperty> + <requiredProperty key="notificationApiKey"></requiredProperty> + <requiredProperty key="notificationApiSecret"></requiredProperty> + <requiredProperty key="dcaeTopic"></requiredProperty> + <requiredProperty key="dcaeServers"></requiredProperty> + <requiredProperty key="dcaeApiKey"></requiredProperty> + <requiredProperty key="dcaeApiSecret"></requiredProperty> + <requiredProperty key="dependenciesVersion"></requiredProperty> + </requiredProperties> + + <fileSets> + <fileSet filtered="true" encoding="UTF-8"> + <directory>src/main/resources</directory> + <includes> + <include>**/*.xml</include> + </includes> + </fileSet> + <fileSet filtered="true" encoding="UTF-8"> + <directory>src/main/resources</directory> + <includes> + <include>**/*.drl</include> + </includes> + </fileSet> + <fileSet filtered="true" encoding="UTF-8"> + <directory>src/main/config</directory> + <includes> + <include>**/*.properties</include> + <include>**/*.json</include> + </includes> + </fileSet> + </fileSets> +</archetype-descriptor> diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/pom.xml b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 000000000..c3973a7d9 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + archetype-closed-loop-demo-rules + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>${groupId}</groupId> + <artifactId>${artifactId}</artifactId> + <version>${version}</version> + + <name>${artifactId}</name> + <description>Closed Loop Demo Rules</description> + + <properties> + <maven.compiler.source>1.8</maven.compiler.source> + <maven.compiler.target>1.8</maven.compiler.target> + </properties> + + <dependencies> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>demo</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>controlloop</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>rest</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>mso</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + <dependency> + <groupId>org.openecomp.policy.drools-applications</groupId> + <artifactId>trafficgenerator</artifactId> + <version>${dependenciesVersion}</version> + </dependency> + </dependencies> +</project> diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.properties b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.properties new file mode 100644 index 000000000..9c3885947 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.properties @@ -0,0 +1,55 @@ +### +# ============LICENSE_START======================================================= +# archetype-closed-loop-demo-rules +# ================================================================================ +# 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========================================================= +### + +controller.name=${artifactId} + +ueb.source.topics=${dcaeTopic},${appcTopic} + +ueb.source.topics.${dcaeTopic}.servers=${dcaeServers} +ueb.source.topics.${dcaeTopic}.apiKey=${dcaeApiKey} +ueb.source.topics.${dcaeTopic}.apiSecret=${dcaeApiSecret} +ueb.source.topics.${dcaeTopic}.events=org.openecomp.policy.controlloop.VirtualControlLoopEvent +ueb.source.topics.${dcaeTopic}.events.org.openecomp.policy.controlloop.VirtualControlLoopEvent.filter=closedLoopEventStatus=.* +ueb.source.topics.${dcaeTopic}.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +ueb.source.topics.${appcTopic}.servers=${appcServers} +ueb.source.topics.${appcTopic}.apiKey=${appcApiKey} +ueb.source.topics.${appcTopic}.apiSecret=${appcApiSecret} +ueb.source.topics.${appcTopic}.events=org.openecomp.policy.appc.Response +ueb.source.topics.${appcTopic}.events.org.openecomp.policy.appc.Response.filter=CommonHeader=.*,Status=.* +ueb.source.topics.${appcTopic}.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics=${appcTopic},${notificationTopic} + +ueb.sink.topics.${appcTopic}.servers=${appcServers} +ueb.sink.topics.${appcTopic}.apiKey=${appcApiKey} +ueb.sink.topics.${appcTopic}.apiSecret=${appcApiSecret} +ueb.sink.topics.${appcTopic}.events=org.openecomp.policy.appc.Request +ueb.sink.topics.${appcTopic}.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics.${notificationTopic}.servers=${notificationServers} +ueb.sink.topics.${notificationTopic}.apiKey=${notificationApiKey} +ueb.sink.topics.${notificationTopic}.apiSecret=${notificationApiSecret} +ueb.sink.topics.${notificationTopic}.events=org.openecomp.policy.controlloop.VirtualControlLoopNotification +ueb.sink.topics.${notificationTopic}.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +rules.groupId=${groupId} +rules.artifactId=${artifactId} +rules.version=${version} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.rest.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.rest.json new file mode 100644 index 000000000..de5db52df --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/__artifactId__-controller.rest.json @@ -0,0 +1,37 @@ +{ + "controller.name": "${artifactId}", + + "ueb.source.topics": "${dcaeTopic},${appcTopic}", + + "ueb.source.topics.${dcaeTopic}.servers": "${dcaeServers}", + "ueb.source.topics.${dcaeTopic}.apiKey": "${dcaeApiKey}", + "ueb.source.topics.${dcaeTopic}.apiSecret": "${dcaeApiSecret}", + "ueb.source.topics.${dcaeTopic}.events": "org.openecomp.policy.controlloop.VirtualControlLoopEvent", + "ueb.source.topics.${dcaeTopic}.events.org.openecomp.policy.controlloop.VirtualControlLoopEvent.filter": "closedLoopEventStatus=.*", + "ueb.source.topics.${dcaeTopic}.events.custom.gson": "org.openecomp.policy.controlloop.util.Serialization,gsonPretty", + + "ueb.source.topics.${appcTopic}.servers": "${appcServers}", + "ueb.source.topics.${appcTopic}.apiKey": "${appcApiKey}", + "ueb.source.topics.${appcTopic}.apiSecret": "${appcApiSecret}", + "ueb.source.topics.${appcTopic}.events": "org.openecomp.policy.appc.Response", + "ueb.source.topics.${appcTopic}.events.org.openecomp.policy.appc.Response.filter": "CommonHeader=.*,Status=.*", + "ueb.source.topics.${appcTopic}.events.custom.gson": "org.openecomp.policy.appc.util.Serialization,gsonPretty", + + "ueb.sink.topics": "${appcTopic},${notificationTopic}", + + "ueb.sink.topics.${appcTopic}.servers": "${appcServers}", + "ueb.sink.topics.${appcTopic}.apiKey": "${appcApiKey}", + "ueb.sink.topics.${appcTopic}.apiSecret": "${appcApiSecret}", + "ueb.sink.topics.${appcTopic}.events": "org.openecomp.policy.appc.Request", + "ueb.sink.topics.${appcTopic}.events.custom.gson": "org.openecomp.policy.appc.util.Serialization,gsonPretty", + + "ueb.sink.topics.${notificationTopic}.servers": "${notificationServers}", + "ueb.sink.topics.${notificationTopic}.apiKey": "${notificationApiKey}", + "ueb.sink.topics.${notificationTopic}.apiSecret": "${notificationApiSecret}", + "ueb.sink.topics.${notificationTopic}.events": "org.openecomp.policy.controlloop.VirtualControlLoopNotification", + "ueb.sink.topics.${notificationTopic}.events.custom.gson": "org.openecomp.policy.controlloop.util.Serialization,gsonPretty", + + "rules.groupId": "${groupId}", + "rules.artifactId": "${artifactId}", + "rules.version": "${version}" +} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.accepted.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.accepted.json new file mode 100644 index 000000000..01be66011 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.accepted.json @@ -0,0 +1 @@ +{"Status":{"Value":"ACCEPTED","Code":"100"},"Payload":{"pg-streams":"{\\\"pg-streams\\\": {\\\"pg-stream\\\":[{\\\"id\\\":\\\"fw_udp1\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp2\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp3\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp4\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp5\\\", \\\"is-enabled\\\":\\\"true\\\"}]}}","generic-vnf.vnf-id":"fw0001vm001fw001"},"CommonHeader":{"TimeStamp":"1493841850199","APIver":"1.01","RequestID":"664be3d2-6c12-4f4b-a3e7-c349acced200","SubrequestID":null,"OriginatorID":null}} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.success.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.success.json new file mode 100644 index 000000000..b9ef41f50 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/appc.success.json @@ -0,0 +1 @@ +{"Status":{"Value":"SUCCESS","Code":"400"},"Payload":{"pg-streams":"{\\\"pg-streams\\\": {\\\"pg-stream\\\":[{\\\"id\\\":\\\"fw_udp1\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp2\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp3\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp4\\\", \\\"is-enabled\\\":\\\"true\\\"},{\\\"id\\\":\\\"fw_udp5\\\", \\\"is-enabled\\\":\\\"true\\\"}]}}","generic-vnf.vnf-id":"fw0001vm001fw001"},"CommonHeader":{"TimeStamp":"1493841850199","APIver":"1.01","RequestID":"664be3d2-6c12-4f4b-a3e7-c349acced200","SubrequestID":null,"OriginatorID":null}} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/dcae.onset.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/dcae.onset.json new file mode 100644 index 000000000..4553faa13 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/dcae.onset.json @@ -0,0 +1,14 @@ +{ + "closedLoopControlName": "${closedLoopControlName}", + "closedLoopAlarmStart": 1463679805324, + "closedLoopEventClient": "microservice.stringmatcher", + "closedLoopEventStatus": "ONSET", + "requestID": "664be3d2-6c12-4f4b-a3e7-c349acced200", + "target_type": "VF", + "target": "generic-vnf.vnf-id", + "AAI": { + "generic-vnf.vnf-id": "fw0001vm001fw001" + }, + "from": "DCAE", + "version": "1.0.2" +} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.properties b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.properties new file mode 100644 index 000000000..5cbe5f682 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.properties @@ -0,0 +1,49 @@ +### +# ============LICENSE_START======================================================= +# archetype-closed-loop-demo-rules +# ================================================================================ +# 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========================================================= +### + +controller.name=vFWsim + +ueb.source.topics=${appcTopic} + +ueb.source.topics.${appcTopic}.servers=${appcServers} +ueb.source.topics.${appcTopic}.apiKey=${appcApiKey} +ueb.source.topics.${appcTopic}.apiSecret=${appcApiSecret} +ueb.source.topics.${appcTopic}.events=org.openecomp.policy.appc.Request,org.openecomp.policy.sim.vfw.OnsetEvent +ueb.source.topics.${appcTopic}.events.org.openecomp.policy.appc.Request.filter=CommonHeader=.*,Action=.* +ueb.source.topics.${appcTopic}.events.org.openecomp.policy.sim.vfw.OnsetEvent.filter=appcResponseCode=.* +ueb.source.topics.${appcTopic}.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +ueb.sink.topics=${dcaeTopic},${appcTopic} + +ueb.sink.topics.${dcaeTopic}.servers=${dcaeServers} +ueb.sink.topics.${dcaeTopic}.apiKey=${dcaeApiKey} +ueb.sink.topics.${dcaeTopic}.apiSecret=${dcaeApiSecret} +ueb.sink.topics.${dcaeTopic}.events=org.openecomp.policy.controlloop.VirtualControlLoopEvent +ueb.sink.topics.${dcaeTopic}.events.custom.gson=org.openecomp.policy.controlloop.util.Serialization,gsonPretty + +ueb.sink.topics.${appcTopic}.servers=${appcServers} +ueb.sink.topics.${appcTopic}.apiKey=${appcApiKey} +ueb.sink.topics.${appcTopic}.apiSecret=${appcApiSecret} +ueb.sink.topics.${appcTopic}.events=org.openecomp.policy.appc.Response +ueb.sink.topics.${appcTopic}.events.custom.gson=org.openecomp.policy.appc.util.Serialization,gsonPretty + +rules.groupId=org.openecomp.policy.drools-applications +rules.artifactId=vfwsim +rules.version=${dependenciesVersion} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.rest.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.rest.json new file mode 100644 index 000000000..23840c48b --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vFWsim-controller.rest.json @@ -0,0 +1,31 @@ +{ + "controller.name": "vFWsim", + + "ueb.source.topics": "${appcTopic}", + + "ueb.source.topics.${appcTopic}.servers": "${appcServers}", + "ueb.source.topics.${appcTopic}.apiKey": "${appcApiKey}", + "ueb.source.topics.${appcTopic}.apiSecret": "${appcApiSecret}", + "ueb.source.topics.${appcTopic}.events": "org.openecomp.policy.appc.Request,org.openecomp.policy.sim.vfw.OnsetEvent", + "ueb.source.topics.${appcTopic}.events.org.openecomp.policy.appc.Request.filter": "CommonHeader=.*,Action=.*", + "ueb.source.topics.${appcTopic}.events.org.openecomp.policy.sim.vfw.OnsetEvent.filter": "appcResponseCode=.*", + "ueb.source.topics.${appcTopic}.events.custom.gson": "org.openecomp.policy.appc.util.Serialization,gsonPretty", + + "ueb.sink.topics": "${dcaeTopic},${appcTopic}", + + "ueb.sink.topics.${dcaeTopic}.servers": "${dcaeServers}", + "ueb.sink.topics.${dcaeTopic}.apiKey": "${dcaeApiKey}", + "ueb.sink.topics.${dcaeTopic}.apiSecret": "${dcaeApiSecret}", + "ueb.sink.topics.${dcaeTopic}.events": "org.openecomp.policy.controlloop.VirtualControlLoopEvent", + "ueb.sink.topics.${dcaeTopic}.events.custom.gson": "org.openecomp.policy.controlloop.util.Serialization,gsonPretty", + + "ueb.sink.topics.${appcTopic}.servers": "${appcServers}", + "ueb.sink.topics.${appcTopic}.apiKey": "${appcApiKey}", + "ueb.sink.topics.${appcTopic}.apiSecret": "${appcApiSecret}", + "ueb.sink.topics.${appcTopic}.events": "org.openecomp.policy.appc.Response", + "ueb.sink.topics.${appcTopic}.events.custom.gson": "org.openecomp.policy.appc.util.Serialization,gsonPretty", + + "rules.groupId": "org.openecomp.policy.drools-applications", + "rules.artifactId": "vfwsim", + "rules.version": "${dependenciesVersion}" +}
\ No newline at end of file diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vfwsim-onset.json b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vfwsim-onset.json new file mode 100644 index 000000000..dd559c039 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/config/vfwsim-onset.json @@ -0,0 +1,5 @@ +{ + "dcaeTopic": "${dcaeTopic}", + "appcTopic": "${appcTopic}", + "appcResponseCode": 400 +} diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl new file mode 100644 index 000000000..98b7b060c --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl @@ -0,0 +1,1140 @@ +/*- + * ============LICENSE_START======================================================= + * archetype-closed-loop-demo-rules + * ================================================================================ + * 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; + +import java.util.List; +import java.util.LinkedList; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.ControlLoopOperationWrapper; +import org.onap.policy.controlloop.ControlLoopException; + +import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; +import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; +import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; +import org.onap.policy.aai.AAINQF199.AAINQF199Manager; +import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; +import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Request; +import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; +import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; +import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; +import org.onap.policy.aai.AAINQF199.AAINQF199VServer; +import org.onap.policy.aai.util.Serialization; + +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appc.ResponseValue; + +import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +import org.onap.policy.mso.MSOManager; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestStatus; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSOResponse; + +import org.openecomp.policy.drools.system.PolicyEngine; + +// +// These parameters are required to build the runtime policy +// +declare Params + closedLoopControlName : String + actor : String + aaiURL : String + aaiUsername : String + aaiPassword : String + msoURL : String + msoUsername : String + msoPassword : String + aaiNamedQueryUUID : String + aaiPatternMatch : int + notificationTopic : String + appcTopic : String +end + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* NOTE: If this file is to be used as a template to be used with the policy BRMS GW, please comment out this line +* as the BRMS_GW already generates a SETUP rule +* +*/ +rule "${policyName}.SETUP" + when + then + System.out.println("rule SETUP is triggered."); + Params params = new Params(); + params.setClosedLoopControlName("${closedLoopControlName}"); + params.setActor("${actor}"); + params.setAaiURL("${aaiURL}"); + params.setAaiUsername("${aaiUsername}"); + params.setAaiPassword("${aaiPassword}"); + params.setMsoURL("${msoURL}"); + params.setMsoUsername("${msoUsername}"); + params.setMsoPassword("${msoPassword}"); + params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); + params.setAaiPatternMatch(${aaiPatternMatch}); + params.setNotificationTopic("${notificationTopic}"); + params.setAppcTopic("${appcTopic}"); + // + // This stays in memory as long as the rule is alive and running + // + insert(params); +end + + +/* +* +* This rule responds to DCAE Events +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )) + then + System.out.println("rule EVENT is triggered."); + try { + // + // Check the requestID in the event to make sure it is not null before we create the EventManager. + // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID from DCAE event"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + System.out.println("Event with requestID=null has been retracted."); + } else { + // + // Create an EventManager + // + ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID); + // + // Determine if EventManager can actively process the event (i.e. syntax) + // + VirtualControlLoopNotification notification = manager.activate($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + } else { + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this same RequestIDs + // and for different RequestIDs but with the same closedLoopControlName and target. + // + } + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is created. We can start the operations for this closed loop. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) + then + System.out.println("rule EVENT.MANAGER is triggered."); + // + // Check which event this is. + // + ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET) { + System.out.println("Retracting "+eventStatus+" Event."); + retract($event); + return; + } + // + // Now the event in memory is first onset event + // + try { + // + // Pull the known AAI field from the Event + // + // generic-vnf is needed for vFirewall case + // vserver-name is needed for vLoadBalancer case + // + String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); + String vserver = $event.AAI.get("vserver.vserver-name"); + // + // Check if we are implementing a simple pattern match. + // + if ($params.getAaiPatternMatch() == 1) { + // + // Yes + // + //Basic naming characteristics: + //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) + //Example: + //VF Name (9 characters): cscf0001v + //VM Name(13 characters): cscf0001vm001 + //VFC name(19 characters): cscf0001vm001cfg001 + // + // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 + // replaced with + // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 + // + int index = genericVNF.lastIndexOf("fwl"); + if (index == -1) { + System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); + } else { + genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); + } + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + // + } else { + // + // create AAI named-query request with UUID started with "F199" + // + AAINQF199Request aainqf199request = new AAINQF199Request(); + AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); + AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); + AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); + // + // queryParameters + // + aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); + aainqf199queryparam.namedQuery = aainqf199namedquery; + aainqf199request.queryParameters = aainqf199queryparam; + // + // instanceFilters + // + Map aainqf199instancefiltermap = new HashMap(); + Map aainqf199instancefiltermapitem = new HashMap(); + aainqf199instancefiltermapitem.put("vserver-name", vserver); + aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); + aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); + aainqf199request.instanceFilters = aainqf199instancefilter; + // + // print aainqf199request for debug + // + System.out.println("AAI Request sent:"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); + // + // Create AAINQF199RequestWrapper + // + AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); + // + // insert aainqf199request into memory + // + insert(aainqf199RequestWrapper); + } + // + } catch (Exception e) { + e.printStackTrace(); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager +* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); + // + // send the request + // + AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), + $aainqf199RequestWrapper.aainqf199request, $event.requestID); + + // + // Check AAI response + // + if (aainqf199response == null) { + System.err.println("Failed to get AAI response"); + // + // Fail and retract everything + // + retract($event); + retract($manager); + retract($aainqf199RequestWrapper); + } else { + // + // Create AAINQF199ResponseWrapper + // + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); + // + // insert aainqf199ResponseWrapper to memeory + // + insert(aainqf199ResponseWrapper); + } +end + +/* +* +* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); + // + // Extract related fields out of AAINQF199RESPONSE + // + String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, + vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, + serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, + vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, + vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; + try { + // + // vnfItem + // + vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; + vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; + serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // Find the index for base vf module and non-base vf module + // + int baseIndex = -1; + int nonBaseIndex = -1; + List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; + for (AAINQF199InventoryResponseItem m : inventoryItems) { + if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { + baseIndex = inventoryItems.indexOf(m); + } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { + nonBaseIndex = inventoryItems.indexOf(m); + } + // + if (baseIndex != -1 && nonBaseIndex != -1) { + break; + } + } + // + // Report the error if either base vf module or non-base vf module is not found + // + if (baseIndex == -1 || nonBaseIndex == -1) { + System.err.println("Either base or non-base vf module is not found from AAI response."); + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // This comes from the base module + // + vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; + vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; + vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; + vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; + // + // tenantItem + // + tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Invalid named-query response from AAI"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // Extracted fields should not be null + // + if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || + (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || + (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || + (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || + (serviceItemModelType == null) || (serviceItemModelVersion == null) || + (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || + (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || + (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || + (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { + // + System.err.println("some fields are missing from AAI response."); + // + // Fail and retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // We don't need them any more + // + retract($aainqf199ResponseWrapper); + retract($aainqf199RequestWrapper); + // + // check the actor of this closed loop + // + switch ($params.getActor()) { + case "APPC": + { + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case + // + String genericVNF = "zdfw1fwl01pgn02"; + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + } + break; + case "MSO": + { + // + // Construct an operation + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "createModuleInstance"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + // + // + // + if (request != null) { + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL + // + String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; + // + // Call MSO + // + MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); + + + if (response != null) { + // + // Assign requestId + // + request.requestId = $event.requestID.toString(); + response.request.requestId = $event.requestID.toString(); + // + // Insert facts + // + insert(operationWrapper); + insert(request); + insert(response); + } else { + // + // MSO request not even accepted + // + notification.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + notification.history.add(operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Retract everything + // + retract($event); + retract($manager); + } + } else { + System.err.println("constructed MSO request is invalid."); + } + } + break; + } +end + +/* +* +* This rule responds to APPC Response Events +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : Request( getCommonHeader().RequestID == $event.requestID ) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + System.out.println("rule APPC.RESPONSE is triggered."); + if ($response.Status == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); + if (code == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + $operationWrapper.operation.outcome = "PROCESSING"; + break; + case ERROR: + case REJECT: + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + break; + case SUCCESS: + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + break; + case FAILURE: + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + break; + } + if ($operationWrapper.operation.outcome.equals("SUCCESS")) { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { + retract($response); + } else { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end + +/* +* +* This rule is used to clean up APPC response +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); + retract($response); +end + +/* +* +* This rule responds to MSO Response Events +* +*/ +rule "${policyName}.MSO.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : MSORequest( requestId == $event.requestID.toString() ) + $response : MSOResponse( request.requestId == $event.requestID.toString() ) + then + System.out.println("rule MSO.RESPONSE is triggered."); + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // The operation can either be succeeded or failed + // + if($response.request.requestStatus.requestState.equals("COMPLETE")) { + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else { + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } +end + +/* + * Sample Queries for illustration with and without arguments + * The results of the query can be introspected (and retracted if desired) + * through REST API. + */ +query "${policyName}.QUERY.EVENT.ONSET" + event : VirtualControlLoopEvent( closedLoopEventStatus == ControlLoopEventStatus.ONSET ) +end + +query "${policyName}.QUERY.MANAGER.RNA" (String aRequestId, Integer numOnsetsLowerBound, Boolean aActivated) + manager : ControlLoopEventManager( closedLoopControlName == "${closedLoopControlName}", + requestID.toString() == aRequestId, + numOnsets > numOnsetsLowerBound, + activated == aActivated ) +end diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/META-INF/kmodule.xml b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/META-INF/kmodule.xml new file mode 100644 index 000000000..8116d880a --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/main/resources/archetype-resources/src/main/resources/META-INF/kmodule.xml @@ -0,0 +1,29 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + archetype-closed-loop-demo-rules + ================================================================================ + 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========================================================= + --> + +<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> + <kbase name="rules"> + <ksession name="closedloop-demo"/> + </kbase> +</kmodule> diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/archetype.properties b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/archetype.properties new file mode 100644 index 000000000..6dce9747d --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/archetype.properties @@ -0,0 +1,50 @@ +### +# ============LICENSE_START======================================================= +# archetype-closed-loop-demo-rules +# ================================================================================ +# 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========================================================= +### + +groupId=org.openecomp.policy.demo.drools +artifactId=closedloop-demo-rules +version=1.0.0-SNAPSHOT +package=org.openecomp.policy.demo.drools +closedLoopControlName=CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8 +policyScope=service=test;resource=FRWL;type=configuration +policyName=FirewallDemo +policyVersion=v1.0 +actor=APPC +appcTopic=APPC-CL +appcApiKey=NO-API-KEY +appcApiSecret=NO-API-SECRET +appcServers=server1,server2,server3 +notificationTopic=POLICY-CL-MGT +notificationApiKey=NO-API-KEY +notificationApiSecret=NO-API-SECRET +notificationServers=server1,server2,server3 +dcaeTopic=DCAE-CL-EVENT +dcaeServers=server1,server2,server3 +dcaeApiKey=NO-API-KEY +dcaeApiSecret=NO-API-SECRET +dependenciesVersion=1.0.0-SNAPSHOT +aaiURL=http://localhost:8080/TestREST/Test +aaiUsername=policy +aaiPassword=policy +aaiNamedQueryUUID=d925ed73-8231-4d02-9545-db4e101fffff +aaiPatternMatch=false +msoURL=http://localhost:8080/TestREST/Test +msoUsername=policy +msoPassword=policy diff --git a/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/goal.txt b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/goal.txt new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/archetype-closedloop-demo-rules/src/test/resources/projects/basic/goal.txt diff --git a/controlloop/templates/template.demo.v1.0.0/pom.xml b/controlloop/templates/template.demo.v1.0.0/pom.xml new file mode 100644 index 000000000..4a746135a --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/pom.xml @@ -0,0 +1,41 @@ +<!-- + ============LICENSE_START======================================================= + drools-pdp-apps Control Loop Drools Templates + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <artifactId>template.demo.v1.0.0</artifactId> + <packaging>pom</packaging> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>templates</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <modules> + <module>archetype-closedloop-demo-rules</module> + <module>template.demo</module> + </modules> + + +</project> diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/pom.xml b/controlloop/templates/template.demo.v1.0.0/template.demo/pom.xml new file mode 100644 index 000000000..e48b78709 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/pom.xml @@ -0,0 +1,112 @@ +<!-- + ============LICENSE_START======================================================= + drools-pdp-apps Control Loop Drools Templates + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>demo</artifactId> + + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>template.demo.v1.0.0</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.2</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.5</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-core</artifactId> + <version>6.3.0.Final</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-compiler</artifactId> + <version>6.3.0.Final</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>mso</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>trafficgenerator</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>eventmanager</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>guard</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>policy-yaml</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl b/controlloop/templates/template.demo.v1.0.0/template.demo/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl new file mode 100644 index 000000000..4ac822661 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl @@ -0,0 +1,1316 @@ +/*- + * ============LICENSE_START======================================================= + * archetype-closed-loop-demo-rules + * ================================================================================ + * 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; + +import java.util.List; +import java.util.LinkedList; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.ControlLoopOperationWrapper; +import org.onap.policy.controlloop.ControlLoopException; + +import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; +import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; +import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; +import org.onap.policy.aai.AAINQF199.AAINQF199Manager; +import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; +import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Request; +import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; +import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; +import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; +import org.onap.policy.aai.AAINQF199.AAINQF199VServer; +import org.onap.policy.aai.util.Serialization; + +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appc.ResponseValue; + +import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +import org.onap.policy.mso.MSOManager; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestStatus; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSOResponse; + +//import org.openecomp.policy.drools.system.PolicyEngine; + +// +// These parameters are required to build the runtime policy +// +declare Params + closedLoopControlName : String + actor : String + aaiURL : String + aaiUsername : String + aaiPassword : String + msoURL : String + msoUsername : String + msoPassword : String + aaiNamedQueryUUID : String + aaiPatternMatch : int + notificationTopic : String + appcTopic : String +end + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* NOTE: If this file is to be used as a template to be used with the policy BRMS GW, please comment out this line +* as the BRMS_GW already generates a SETUP rule +* +*/ +rule "${policyName}.SETUP" + when + then + System.out.println("rule SETUP is triggered."); + Params params = new Params(); + params.setClosedLoopControlName("${closedLoopControlName}"); + params.setActor("${actor}"); + params.setAaiURL("${aaiURL}"); + params.setAaiUsername("${aaiUsername}"); + params.setAaiPassword("${aaiPassword}"); + params.setMsoURL("${msoURL}"); + params.setMsoUsername("${msoUsername}"); + params.setMsoPassword("${msoPassword}"); + params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); + params.setAaiPatternMatch(${aaiPatternMatch}); + params.setNotificationTopic("${notificationTopic}"); + params.setAppcTopic("${appcTopic}"); + // + // This stays in memory as long as the rule is alive and running + // + insert(params); +end + + +/* +* +* This rule responds to DCAE Events +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )) + then + System.out.println("rule EVENT is triggered."); + try { + // + // Check the requestID in the event to make sure it is not null before we create the EventManager. + // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID from DCAE event"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + System.out.println("Event with requestID=null has been retracted."); + } else { + // + // Create an EventManager + // + ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID); + // + // Determine if EventManager can actively process the event (i.e. syntax) + // + VirtualControlLoopNotification notification = manager.activate($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + } else { + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this same RequestIDs + // and for different RequestIDs but with the same closedLoopControlName and target. + // + } + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is created. We can start the operations for this closed loop. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) + then + System.out.println("rule EVENT.MANAGER is triggered."); + // + // Check which event this is. + // + ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != ControlLoopEventManager.NEW_EVENT_STATUS.FIRST_ONSET) { + System.out.println("Retracting "+eventStatus+" Event."); + retract($event); + return; + } + // + // Now the event in memory is first onset event + // + try { + // + // Pull the known AAI field from the Event + // + // generic-vnf is needed for vFirewall case + // vserver-name is needed for vLoadBalancer case + // + String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); + String vserver = $event.AAI.get("vserver.vserver-name"); + // + // Check if we are implementing a simple pattern match. + // + if ($params.getAaiPatternMatch() == 1) { + // + // Yes + // + //Basic naming characteristics: + //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) + //Example: + //VF Name (9 characters): cscf0001v + //VM Name(13 characters): cscf0001vm001 + //VFC name(19 characters): cscf0001vm001cfg001 + // + // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 + // replaced with + // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 + // + int index = genericVNF.lastIndexOf("fwl"); + if (index == -1) { + System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); + } else { + genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); + } + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + //PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + // + } else { + // + // create AAI named-query request with UUID started with "F199" + // + AAINQF199Request aainqf199request = new AAINQF199Request(); + AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); + AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); + AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); + // + // queryParameters + // + aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); + aainqf199queryparam.namedQuery = aainqf199namedquery; + aainqf199request.queryParameters = aainqf199queryparam; + // + // instanceFilters + // + Map aainqf199instancefiltermap = new HashMap(); + Map aainqf199instancefiltermapitem = new HashMap(); + aainqf199instancefiltermapitem.put("vserver-name", vserver); + aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); + aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); + aainqf199request.instanceFilters = aainqf199instancefilter; + // + // print aainqf199request for debug + // + System.out.println("AAI Request sent:"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); + // + // Create AAINQF199RequestWrapper + // + AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); + // + // insert aainqf199request into memory + // + insert(aainqf199RequestWrapper); + } + // + } catch (Exception e) { + e.printStackTrace(); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager +* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); + // + // send the request + // + AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), + $aainqf199RequestWrapper.aainqf199request, $event.requestID); + + + + ////////////////////////////////////////////////////////// + // Simulate a valid aainqf199response for junit test + // Remove this for real deployment + // + + AAINQF199InventoryResponseItem serviceItem = new AAINQF199InventoryResponseItem(); + serviceItem.modelName = "service-instance"; + serviceItem.serviceInstance = new AAINQF199ServiceInstance(); + serviceItem.serviceInstance.serviceInstanceID = "cf8426a6-0b53-4e3d-bfa6-4b2f4d5913a5"; + serviceItem.serviceInstance.serviceInstanceName = "Service_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"; + serviceItem.serviceInstance.personaModelId = "4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b"; + serviceItem.serviceInstance.personaModelVersion = "1.0"; + serviceItem.serviceInstance.resourceVersion = "1485542400"; + serviceItem.extraProperties = new AAINQF199ExtraProperties(); + serviceItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name", "8330e932-2a23-4943-8606")); + serviceItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-type", "service")); + serviceItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-version", "1")); + serviceItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-id", "4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b")); + serviceItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name-version-id", "5c996219-b2e2-4c76-9b43-7e8672a33c1d")); + + AAINQF199InventoryResponseItem vfModuleItem = new AAINQF199InventoryResponseItem(); + vfModuleItem.modelName = "C15ce9e1E9144c8fB8bb..base_vlb..module-0"; + vfModuleItem.vfModule = new AAINQF199VfModule(); + vfModuleItem.vfModule.vfModuleId = "b0eff878-e2e1-4947-9597-39afdd0f51dd"; + vfModuleItem.vfModule.vfModuleName = "Vfmodule_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"; + vfModuleItem.vfModule.heatStackId = "Vfmodule_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8/5845f37b-6cda-4e91-8ca3-f5572d226488"; + vfModuleItem.vfModule.orchestrationStatus = "active"; + vfModuleItem.vfModule.isBaseVfModule = true; + vfModuleItem.vfModule.resourceVersion = "1485542667"; + vfModuleItem.vfModule.personaModelId = "79ee24cd-fc9a-4f14-afae-5e1dd2ab2941"; + vfModuleItem.vfModule.personaModelVersion = "1"; + + vfModuleItem.extraProperties = new AAINQF199ExtraProperties(); + vfModuleItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name", "C15ce9e1E9144c8fB8bb..base_vlb..module-0")); + vfModuleItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-type", "resource")); + vfModuleItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-version", "1")); + vfModuleItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-id", "79ee24cd-fc9a-4f14-afae-5e1dd2ab2941")); + vfModuleItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name-version-id", "5484cabb-1a0d-4f29-a616-094a3f643d73")); + + + AAINQF199InventoryResponseItem vfModuleItem1 = new AAINQF199InventoryResponseItem(); + //vfModuleItem1.modelName = "vf-module"; + vfModuleItem1.vfModule = new AAINQF199VfModule(); + vfModuleItem1.vfModule.vfModuleId = "dummy"; + vfModuleItem1.vfModule.vfModuleName = "dummy"; + vfModuleItem1.vfModule.isBaseVfModule = false; + vfModuleItem1.vfModule.resourceVersion = "1485561752"; + vfModuleItem1.vfModule.personaModelId = "f32568ec-2f1c-458a-864b-0593d53d141a"; + vfModuleItem1.vfModule.personaModelVersion = "1.0"; + + vfModuleItem1.extraProperties = new AAINQF199ExtraProperties(); + vfModuleItem1.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name", "C15ce9e1E9144c8fB8bb..dnsscaling..module-1")); + vfModuleItem1.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-type", "resource")); + vfModuleItem1.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-version", "1")); + vfModuleItem1.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-id", "f32568ec-2f1c-458a-864b-0593d53d141a")); + vfModuleItem1.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name-version-id", "69615025-879d-4f0d-afe3-b7d1a7eeed1f")); + + + + AAINQF199InventoryResponseItem vfModuleItem2 = new AAINQF199InventoryResponseItem(); + //vfModuleItem2.modelName = "vf-module"; + vfModuleItem2.vfModule = new AAINQF199VfModule(); + vfModuleItem2.vfModule.vfModuleId = "8cd79e44-1fae-48c1-a160-609f90b46749"; + vfModuleItem2.vfModule.vfModuleName = "vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"; + vfModuleItem2.vfModule.heatStackId = "vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8/f447ce51-14dd-4dcd-9957-68a047c79673"; + vfModuleItem2.vfModule.orchestrationStatus = "active"; + vfModuleItem2.vfModule.isBaseVfModule = false; + vfModuleItem2.vfModule.resourceVersion = "1485562712"; + vfModuleItem2.vfModule.personaModelId = "f32568ec-2f1c-458a-864b-0593d53d141a"; + vfModuleItem2.vfModule.personaModelVersion = "1.0"; + + vfModuleItem2.extraProperties = new AAINQF199ExtraProperties(); + vfModuleItem2.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name", "C15ce9e1E9144c8fB8bb..dnsscaling..module-1")); + vfModuleItem2.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-type", "resource")); + vfModuleItem2.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-version", "1")); + vfModuleItem2.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-id", "f32568ec-2f1c-458a-864b-0593d53d141a")); + vfModuleItem2.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name-version-id", "69615025-879d-4f0d-afe3-b7d1a7eeed1f")); + + + + + + AAINQF199InventoryResponseItem genericVNFItem = new AAINQF199InventoryResponseItem(); + genericVNFItem.modelName = "generic-vnf"; + genericVNFItem.genericVNF = new AAINQF199GenericVNF(); + genericVNFItem.genericVNF.vnfID = "594e2fe0-48b8-41ff-82e2-3d4bab69b192"; + genericVNFItem.genericVNF.vnfName = "Vnf_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8"; + genericVNFItem.genericVNF.vnfType = "8330e932-2a23-4943-8606/c15ce9e1-e914-4c8f-b8bb 1"; + genericVNFItem.genericVNF.serviceId = "b3f70641-bdb9-4030-825e-6abb73a1f929"; +// genericVNFItem.genericVNF.provStatus = "PREPROV"; +// genericVNFItem.genericVNF.operationalState = "dhv-test-operational-state"; +// genericVNFItem.genericVNF.ipv4OamAddress = "dhv-test-gvnf-ipv4-oam-address"; +// genericVNFItem.genericVNF.ipv4Loopback0Address = "dhv-test-gvnfipv4-loopback0-address"; + genericVNFItem.genericVNF.inMaint = false; + genericVNFItem.genericVNF.isClosedLoopDisabled = false; + genericVNFItem.genericVNF.resourceVersion = "1485542422"; +// genericVNFItem.genericVNF.encrypedAccessFlag = true; + genericVNFItem.genericVNF.personaModelId = "033a32ed-aa65-4764-a736-36f2942f1aa0"; + genericVNFItem.genericVNF.personaModelVersion = "1.0"; + genericVNFItem.extraProperties = new AAINQF199ExtraProperties(); + genericVNFItem.extraProperties.extraProperty = new LinkedList<AAINQF199ExtraProperty>(); + genericVNFItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name", "c15ce9e1-e914-4c8f-b8bb")); + genericVNFItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-type", "resource")); + genericVNFItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-version", "1")); + genericVNFItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-id", "033a32ed-aa65-4764-a736-36f2942f1aa0")); + genericVNFItem.extraProperties.extraProperty.add(new AAINQF199ExtraProperty("model.model-name-version-id", "d4d072dc-4e21-4a03-9524-628985819a8e")); + genericVNFItem.items = new AAINQF199InventoryResponseItems(); + genericVNFItem.items.inventoryResponseItems = new LinkedList<AAINQF199InventoryResponseItem>(); + genericVNFItem.items.inventoryResponseItems.add(serviceItem); + genericVNFItem.items.inventoryResponseItems.add(vfModuleItem); + genericVNFItem.items.inventoryResponseItems.add(vfModuleItem1); + genericVNFItem.items.inventoryResponseItems.add(vfModuleItem2); + + AAINQF199InventoryResponseItem cloudItem = new AAINQF199InventoryResponseItem(); + cloudItem.cloudRegion = new AAINQF199CloudRegion(); + cloudItem.cloudRegion.cloudOwner = "OWNER"; + cloudItem.cloudRegion.cloudRegionId = "REGIONID"; + cloudItem.cloudRegion.cloudRegionVersion = "2.5"; + cloudItem.cloudRegion.complexName = "COMPLEXNAME"; + cloudItem.cloudRegion.resourceVersion = "1485465545"; + + AAINQF199InventoryResponseItem tenantItem = new AAINQF199InventoryResponseItem(); + tenantItem.tenant = new AAINQF199Tenant(); + tenantItem.tenant.tenantId = "1015548"; + tenantItem.tenant.tenantName = "1015548"; + tenantItem.tenant.resourceVersion = "1485465545"; + tenantItem.items = new AAINQF199InventoryResponseItems(); + tenantItem.items.inventoryResponseItems = new LinkedList<AAINQF199InventoryResponseItem>(); + tenantItem.items.inventoryResponseItems.add(cloudItem); + + AAINQF199InventoryResponseItem vserverItem = new AAINQF199InventoryResponseItem(); + vserverItem.vserver = new AAINQF199VServer(); + vserverItem.vserver.vserverId = "70f081eb-2a87-4c81-9296-4b93d7d145c6"; + vserverItem.vserver.vserverName = "vlb-lb-32c8"; + vserverItem.vserver.vserverName2 = "vlb-lb-32c8"; + vserverItem.vserver.provStatus = "ACTIVE"; + vserverItem.vserver.vserverSelflink = "https://dfw.servers.api.rackspacecloud.com/v2/1015548/servers/70f081eb-2a87-4c81-9296-4b93d7d145c6"; + vserverItem.vserver.inMaint = false; + vserverItem.vserver.isClosedLoopDisabled = false; + vserverItem.vserver.resourceVersion = "1485546436"; + vserverItem.items = new AAINQF199InventoryResponseItems(); + vserverItem.items.inventoryResponseItems = new LinkedList<AAINQF199InventoryResponseItem>(); + vserverItem.items.inventoryResponseItems.add(genericVNFItem); + vserverItem.items.inventoryResponseItems.add(tenantItem); + + aainqf199response = new AAINQF199Response(); + aainqf199response.inventoryResponseItems.add(vserverItem); + + System.out.println("PAM"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199response)); + + ////////////////////////////////////////////////////////// + + + + + + + // + // Check AAI response + // + if (aainqf199response == null) { + System.err.println("Failed to get AAI response"); + // + // Fail and retract everything + // + retract($event); + retract($manager); + retract($aainqf199RequestWrapper); + } else { + // + // Create AAINQF199ResponseWrapper + // + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); + // + // insert aainqf199ResponseWrapper to memeory + // + insert(aainqf199ResponseWrapper); + } +end + +/* +* +* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); + // + // Extract related fields out of AAINQF199RESPONSE + // + String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, + vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, + serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, + vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, + vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; + try { + // + // vnfItem + // + vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; + vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; + serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // Find the index for base vf module and non-base vf module + // + int baseIndex = -1; + int nonBaseIndex = -1; + List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; + for (AAINQF199InventoryResponseItem m : inventoryItems) { + if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { + baseIndex = inventoryItems.indexOf(m); + } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { + nonBaseIndex = inventoryItems.indexOf(m); + } + // + if (baseIndex != -1 && nonBaseIndex != -1) { + break; + } + } + // + // Report the error if either base vf module or non-base vf module is not found + // + if (baseIndex == -1 || nonBaseIndex == -1) { + System.err.println("Either base or non-base vf module is not found from AAI response."); + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // This comes from the base module + // + vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; + vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; + vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; + vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; + // + // tenantItem + // + tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Invalid named-query response from AAI"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // Extracted fields should not be null + // + if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || + (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || + (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || + (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || + (serviceItemModelType == null) || (serviceItemModelVersion == null) || + (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || + (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || + (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || + (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { + // + System.err.println("some fields are missing from AAI response."); + // + // Fail and retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // We don't need them any more + // + retract($aainqf199ResponseWrapper); + retract($aainqf199RequestWrapper); + // + // check the actor of this closed loop + // + switch ($params.getActor()) { + case "APPC": + { + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case + // + String genericVNF = "zdfw1fwl01pgn02"; + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + //PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + } + break; + case "MSO": + { + // + // Construct an operation + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "createModuleInstance"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + // + // + // + if (request != null) { + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL + // + String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; + // + // Call MSO + // + MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); + + + + + ////////////////////////////////////////////////////////// + // Simulate a valid MSOResponse for junit test + // Remove this for real deployment + // + response = new MSOResponse(); + response.request = new MSORequest(); + response.request.requestStatus = new MSORequestStatus(); + response.request.requestStatus.requestState = "COMPLETE"; + ////////////////////////////////////////////////////////// + + + + + + if (response != null) { + // + // Assign requestId + // + request.requestId = $event.requestID.toString(); + response.request.requestId = $event.requestID.toString(); + // + // Insert facts + // + insert(operationWrapper); + insert(request); + insert(response); + } else { + // + // MSO request not even accepted + // + notification.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + notification.history.add(operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Retract everything + // + retract($event); + retract($manager); + } + } else { + System.err.println("constructed MSO request is invalid."); + } + } + break; + } +end + +/* +* +* This rule responds to APPC Response Events +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : Request( getCommonHeader().RequestID == $event.requestID ) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + System.out.println("rule APPC.RESPONSE is triggered."); + if ($response.Status == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); + if (code == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + $operationWrapper.operation.outcome = "PROCESSING"; + break; + case ERROR: + case REJECT: + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + break; + case SUCCESS: + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + break; + case FAILURE: + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + break; + } + if ($operationWrapper.operation.outcome.equals("SUCCESS")) { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { + retract($response); + } else { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end + +/* +* +* This rule is used to clean up APPC response +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); + retract($response); +end + +/* +* +* This rule responds to MSO Response Events +* +*/ +rule "${policyName}.MSO.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : MSORequest( requestId == $event.requestID.toString() ) + $response : MSOResponse( request.requestId == $event.requestID.toString() ) + then + System.out.println("rule MSO.RESPONSE is triggered."); + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // The operation can either be succeeded or failed + // + if($response.request.requestStatus.requestState.equals("COMPLETE")) { + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else { + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + //PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } +end + +/* + * Sample Queries for illustration with and without arguments + * The results of the query can be introspected (and retracted if desired) + * through REST API. + */ +query "${policyName}.QUERY.EVENT.ONSET" + event : VirtualControlLoopEvent( closedLoopEventStatus == ControlLoopEventStatus.ONSET ) +end + +query "${policyName}.QUERY.MANAGER.RNA" (String aRequestId, Integer numOnsetsLowerBound, Boolean aActivated) + manager : ControlLoopEventManager( closedLoopControlName == "${closedLoopControlName}", + requestID.toString() == aRequestId, + numOnsets > numOnsetsLowerBound, + activated == aActivated ) +end diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestAPPCPayload.java b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestAPPCPayload.java new file mode 100644 index 000000000..73501bce5 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestAPPCPayload.java @@ -0,0 +1,58 @@ +/*- + * ============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 java.util.HashMap; +import java.util.UUID; + +import org.junit.Test; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.util.Serialization; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +public class TestAPPCPayload { + + @Test + public void test() { + PGRequest request = new PGRequest(); + request.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + request.pgStreams.pgStream.add(pgStream); + } + + Request appc = new Request(); + appc.CommonHeader = new CommonHeader(); + appc.CommonHeader.RequestID = UUID.randomUUID(); + appc.Action = "ModifyConfig"; + appc.Payload = new HashMap<String, Object>(); + appc.Payload.put("pg-streams", request); + System.out.println(Serialization.gsonPretty.toJson(appc)); + } + +} diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestFirewallDemo.java b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestFirewallDemo.java new file mode 100644 index 000000000..e48aafdad --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestFirewallDemo.java @@ -0,0 +1,593 @@ +/*- + * ============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 java.io.IOException; +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.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.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopTargetType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.appc.util.Serialization; + + + +public class TestFirewallDemo { + + + @Test + public void testvDNS() throws IOException { + // + // Build a container + // + final String closedLoopControlName = "CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8"; + final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl", + closedLoopControlName, + "type=operational", + "myFirewallDemoPolicy", + "v1.0", + "MSO", + "http://localhost:8080/TestREST/Test", + "POLICY", + "POLICY", + "http://localhost:8080/TestREST/Test", + "POLICY", + "POLICY", + "4ff56a54-9e3f-46b7-a337-07a1d3c6b469", + 0, + "POLICY-CL-MGT", + "APPC-CL" + ); + // + // Initial fire of rules + // + kieSession.fireAllRules(); + // + // Kick a thread that starts testing + // + new Thread(new Runnable() { + + @Override + public void run() { + // + // Generate an invalid DCAE Event with requestID=null + // + VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent(); + invalidEvent.closedLoopControlName = closedLoopControlName; + invalidEvent.requestID = null; + invalidEvent.closedLoopEventClient = "tca.instance00001"; + invalidEvent.target_type = ControlLoopTargetType.VF; + invalidEvent.target = "generic-vnf.vnf-id"; + invalidEvent.from = "DCAE"; + invalidEvent.closedLoopAlarmStart = Instant.now(); + invalidEvent.AAI = new HashMap<String, String>(); + invalidEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + + System.out.println("----- Invalid ONSET -----"); + System.out.println(Serialization.gsonPretty.toJson(invalidEvent)); + + // + // Insert invalid DCAE Event into memory + // + kieSession.insert(invalidEvent); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + // + // Generate first DCAE ONSET Event + // + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.closedLoopControlName = closedLoopControlName; + onsetEvent.requestID = UUID.randomUUID(); + onsetEvent.closedLoopEventClient = "tca.instance00001"; + onsetEvent.target_type = ControlLoopTargetType.VF; + onsetEvent.target = "generic-vnf.vnf-id"; + onsetEvent.from = "DCAE"; + onsetEvent.closedLoopAlarmStart = Instant.now(); + onsetEvent.AAI = new HashMap<String, String>(); + onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + + System.out.println("----- ONSET -----"); + System.out.println(Serialization.gsonPretty.toJson(onsetEvent)); + + // + // Insert first DCAE ONSET Event into memory + // + kieSession.insert(onsetEvent); + // + // We have test for subsequent ONSET Events in testvFirewall() + // So no need to test it again here + // + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + } + // + // Test is finished, so stop the kieSession + // + kieSession.halt(); + } + // + }).start(); + // + // Start firing rules + // + kieSession.fireUntilHalt(); + // + // Dump working memory + // + dumpFacts(kieSession); + // + // See if there is anything left in memory, there SHOULD only be + // a params fact. + // + assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + Object fact = kieSession.getObject(handle); + assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName()); + } + } + + @Test + public void testvFirewall() throws IOException { + // + // Build a container + // + final String closedLoopControlName = "CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8"; + final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl", + closedLoopControlName, + "type=operational", + "myFirewallDemoPolicy", + "v1.0", + "APPC", + "http://localhost:8080/TestREST/Test", + "POLICY", + "POLICY", + null, + null, + null, + null, + 1, + "POLICY-CL-MGT", + "APPC-CL" + ); + // + // Initial fire of rules + // + kieSession.fireAllRules(); + // + // Kick a thread that starts testing + // + new Thread(new Runnable() { + + @Override + public void run() { + // + // Generate an invalid DCAE Event with requestID=null + // + VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent(); + invalidEvent.closedLoopControlName = closedLoopControlName; + invalidEvent.requestID = null; + invalidEvent.closedLoopEventClient = "tca.instance00001"; + invalidEvent.target_type = ControlLoopTargetType.VF; + invalidEvent.target = "generic-vnf.vnf-id"; + invalidEvent.from = "DCAE"; + invalidEvent.closedLoopAlarmStart = Instant.now(); + invalidEvent.AAI = new HashMap<String, String>(); + invalidEvent.AAI.put("generic-vnf.vnf-id", "foo"); + invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + + System.out.println("----- Invalid ONSET -----"); + System.out.println(Serialization.gsonPretty.toJson(invalidEvent)); + + // + // Insert invalid DCAE Event into memory + // + kieSession.insert(invalidEvent); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + // + // Generate first DCAE ONSET Event + // + VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); + onsetEvent.closedLoopControlName = closedLoopControlName; + onsetEvent.requestID = UUID.randomUUID(); + onsetEvent.closedLoopEventClient = "tca.instance00001"; + onsetEvent.target_type = ControlLoopTargetType.VF; + onsetEvent.target = "generic-vnf.vnf-id"; + onsetEvent.from = "DCAE"; + onsetEvent.closedLoopAlarmStart = Instant.now(); + onsetEvent.AAI = new HashMap<String, String>(); + onsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001"); + //onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + + System.out.println("----- ONSET -----"); + System.out.println(Serialization.gsonPretty.toJson(onsetEvent)); + + // + // Insert first DCAE ONSET Event into memory + // + kieSession.insert(onsetEvent); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + + + Thread thread = new Thread(new Runnable() { + + @Override + public void run() { + while (true) { + // + // Generate subsequent DCAE ONSET Event + // + VirtualControlLoopEvent subOnsetEvent = new VirtualControlLoopEvent(); + subOnsetEvent.closedLoopControlName = closedLoopControlName; + subOnsetEvent.requestID = UUID.randomUUID(); + subOnsetEvent.closedLoopEventClient = "tca.instance00001"; + subOnsetEvent.target_type = ControlLoopTargetType.VF; + subOnsetEvent.target = "generic-vnf.vnf-id"; + subOnsetEvent.from = "DCAE"; + subOnsetEvent.closedLoopAlarmStart = Instant.now(); + subOnsetEvent.AAI = new HashMap<String, String>(); + subOnsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001"); + //subOnsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + subOnsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET; + + System.out.println("----- Subsequent ONSET -----"); + System.out.println(Serialization.gsonPretty.toJson(subOnsetEvent)); + + // + // Insert subsequent DCAE ONSET Event into memory + // + kieSession.insert(subOnsetEvent); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + break; + } + } + } + + }); + thread.start(); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + } + // + // Stop the thread + // + thread.interrupt(); + // + // Generate APPC ACCEPT Response + // + Response response1 = new Response(); + // CommonHeader + CommonHeader commonHeader1 = new CommonHeader(); + commonHeader1.RequestID = onsetEvent.requestID; + response1.CommonHeader = commonHeader1; + // ResponseStatus + ResponseStatus responseStatus1 = new ResponseStatus(); + responseStatus1.Code = 100; + response1.Status = responseStatus1; + // + System.out.println("----- APP-C RESPONSE 100 -----"); + System.out.println(Serialization.gsonPretty.toJson(response1)); + // + // Insert APPC Response into memory + // + kieSession.insert(response1); + // + // Simulating APPC takes some time for processing the recipe + // and then gives response + // + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + // + // Generate APPC SUCCESS Response + // + Response response2 = new Response(); + // CommonHeader + CommonHeader commonHeader2 = new CommonHeader(); + commonHeader2.RequestID = onsetEvent.requestID; + response2.CommonHeader = commonHeader2; + // ResponseStatus + ResponseStatus responseStatus2 = new ResponseStatus(); + responseStatus2.Code = 400; + response2.Status = responseStatus2; + // + System.out.println("----- APP-C RESPONSE 400 -----"); + System.out.println(Serialization.gsonPretty.toJson(response2)); + // + // Insert APPC Response into memory + // + kieSession.insert(response2); + // + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + } + // + // Test is finished, so stop the kieSession + // + kieSession.halt(); + } + // + }).start(); + // + // Start firing rules + // + kieSession.fireUntilHalt(); + // + // Dump working memory + // + dumpFacts(kieSession); + // + // See if there is anything left in memory, there SHOULD only be + // a params fact. + // + assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + Object fact = kieSession.getObject(handle); + assertEquals("Non-Param Fact left in working memory", "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); + } + } + + public static KieSession buildContainer(String droolsTemplate, + String closedLoopControlName, + String policyScope, + String policyName, + String policyVersion, + String actor, + String aaiURL, + String aaiUsername, + String aaiPassword, + String msoURL, + String msoUsername, + String msoPassword, + String aaiNamedQuery, + int aaiPatternMatch, + String notificationTopic, + String appcTopic ) 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, + actor, + aaiURL, + aaiUsername, + aaiPassword, + msoURL, + msoUsername, + msoPassword, + aaiNamedQuery, + aaiPatternMatch, + notificationTopic, + appcTopic + ); + + 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(); + } + public static String generatePolicy(String ruleContents, + String closedLoopControlName, + String policyScope, + String policyName, + String policyVersion, + String actor, + String aaiURL, + String aaiUsername, + String aaiPassword, + String msoURL, + String msoUsername, + String msoPassword, + String aaiNamedQueryUUID, + int aaiPatternMatch, + String notificationTopic, + String appcTopic) { + + 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("\\$\\{actor\\}"); + m = p.matcher(ruleContents); + ruleContents = m.replaceAll(actor); + + p = Pattern.compile("\\$\\{aaiURL\\}"); + m = p.matcher(ruleContents); + if (aaiURL == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(aaiURL); + } + + p = Pattern.compile("\\$\\{aaiUsername\\}"); + m = p.matcher(ruleContents); + if (aaiUsername == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(aaiUsername); + } + + p = Pattern.compile("\\$\\{aaiPassword\\}"); + m = p.matcher(ruleContents); + if (aaiPassword == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(aaiPassword); + } + + p = Pattern.compile("\\$\\{msoURL\\}"); + m = p.matcher(ruleContents); + if (msoURL == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(msoURL); + } + + p = Pattern.compile("\\$\\{msoUsername\\}"); + m = p.matcher(ruleContents); + if (msoUsername == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(msoUsername); + } + + p = Pattern.compile("\\$\\{msoPassword\\}"); + m = p.matcher(ruleContents); + if (msoPassword == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(msoPassword); + } + + p = Pattern.compile("\\$\\{aaiNamedQueryUUID\\}"); + m = p.matcher(ruleContents); + if (aaiNamedQueryUUID == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(aaiNamedQueryUUID); + } + + p = Pattern.compile("\\$\\{aaiPatternMatch\\}"); + m = p.matcher(ruleContents); + if (aaiPatternMatch == 1) { + ruleContents = m.replaceAll("1"); + } else { + ruleContents = m.replaceAll("0"); + } + + p = Pattern.compile("\\$\\{notificationTopic\\}"); + m = p.matcher(ruleContents); + if (notificationTopic == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(notificationTopic); + } + + p = Pattern.compile("\\$\\{appcTopic\\}"); + m = p.matcher(ruleContents); + if (appcTopic == null) { + ruleContents = m.replaceAll("null"); + } else { + ruleContents = m.replaceAll(appcTopic); + } + + System.out.println(ruleContents); + + return ruleContents; + } + +} diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestMSO.java b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestMSO.java new file mode 100644 index 000000000..a960661ee --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/java/org/onap/policy/template/demo/TestMSO.java @@ -0,0 +1,159 @@ +/*- + * ============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 java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.UUID; + +import org.junit.Test; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.mso.util.Serialization; + +import com.google.gson.Gson; +import com.google.gson.stream.JsonReader; + +public class TestMSO { + + @Test + public void test() throws FileNotFoundException { + Gson gson = new Gson(); + JsonReader reader = new JsonReader(new FileReader("src/test/resources/aairesponse.json")); + AAINQF199Response response = gson.fromJson(reader, AAINQF199Response.class); + + System.out.println(Serialization.gsonPretty.toJson(response)); + + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper(UUID.randomUUID(), response); + + // + // + // vnfItem + // + String vnfItemVnfId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + String vnfItemVnfType = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + String vnfItemPersonaModelId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + String vnfItemPersonaModelVersion = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + String vnfItemModelName = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + String vnfItemModelNameVersionId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + String serviceItemServiceInstanceId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + String serviceItemPersonaModelId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + String serviceItemModelName = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + String serviceItemModelVersion = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + String serviceItemModelNameVersionId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // This comes from the base module + // + String vfModuleItemVfModuleName = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + String vfModuleItemPersonaModelId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(2).vfModule.personaModelId; + String vfModuleItemPersonaModelVersion = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(2).vfModule.personaModelVersion; + String vfModuleItemModelName = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(2).extraProperties.extraProperty.get(0).propertyValue; + String vfModuleItemModelNameVersionId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(2).extraProperties.extraProperty.get(4).propertyValue; + + // + // tenantItem + // + String tenantItemTenantId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + String cloudRegionItemCloudRegionId = aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemPersonaModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + } + +} diff --git a/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/resources/aairesponse.json b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/resources/aairesponse.json new file mode 100644 index 000000000..66da8e715 --- /dev/null +++ b/controlloop/templates/template.demo.v1.0.0/template.demo/src/test/resources/aairesponse.json @@ -0,0 +1,227 @@ +{ + "inventory-response-item": [ + { + "extra-properties": {}, + "inventory-response-items": { + "inventory-response-item": [ + { + "extra-properties": { + "extra-property": [ + { + "property-name": "model.model-name", + "property-value": "c15ce9e1-e914-4c8f-b8bb" + }, + { + "property-name": "model.model-type", + "property-value": "resource" + }, + { + "property-name": "model.model-version", + "property-value": "1" + }, + { + "property-name": "model.model-id", + "property-value": "033a32ed-aa65-4764-a736-36f2942f1aa0" + }, + { + "property-name": "model.model-name-version-id", + "property-value": "d4d072dc-4e21-4a03-9524-628985819a8e" + } + ] + }, + "generic-vnf": { + "in-maint": false, + "is-closed-loop-disabled": false, + "orchestration-status": "Created", + "persona-model-id": "033a32ed-aa65-4764-a736-36f2942f1aa0", + "persona-model-version": "1.0", + "resource-version": "1485542422", + "service-id": "b3f70641-bdb9-4030-825e-6abb73a1f929", + "vnf-id": "594e2fe0-48b8-41ff-82e2-3d4bab69b192", + "vnf-name": "Vnf_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8", + "vnf-type": "8330e932-2a23-4943-8606/c15ce9e1-e914-4c8f-b8bb 1" + }, + "inventory-response-items": { + "inventory-response-item": [ + { + "extra-properties": { + "extra-property": [ + { + "property-name": "model.model-name", + "property-value": "8330e932-2a23-4943-8606" + }, + { + "property-name": "model.model-type", + "property-value": "service" + }, + { + "property-name": "model.model-version", + "property-value": "1" + }, + { + "property-name": "model.model-id", + "property-value": "4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b" + }, + { + "property-name": "model.model-name-version-id", + "property-value": "5c996219-b2e2-4c76-9b43-7e8672a33c1d" + } + ] + }, + "service-instance": { + "persona-model-id": "4fcbc1c0-7793-46d8-8aa1-fa1c2ed9ec7b", + "persona-model-version": "1.0", + "resource-version": "1485542400", + "service-instance-id": "cf8426a6-0b53-4e3d-bfa6-4b2f4d5913a5", + "service-instance-name": "Service_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8" + } + }, + { + "extra-properties": { + "extra-property": [ + { + "property-name": "model.model-name", + "property-value": "C15ce9e1E9144c8fB8bb..base_vlb..module-0" + }, + { + "property-name": "model.model-type", + "property-value": "resource" + }, + { + "property-name": "model.model-version", + "property-value": "1" + }, + { + "property-name": "model.model-id", + "property-value": "79ee24cd-fc9a-4f14-afae-5e1dd2ab2941" + }, + { + "property-name": "model.model-name-version-id", + "property-value": "5484cabb-1a0d-4f29-a616-094a3f643d73" + } + ] + }, + "model-name": "C15ce9e1E9144c8fB8bb..base_vlb..module-0", + "vf-module": { + "heat-stack-id": "Vfmodule_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8/5845f37b-6cda-4e91-8ca3-f5572d226488", + "is-base-vf-module": true, + "orchestration-status": "active", + "persona-model-id": "79ee24cd-fc9a-4f14-afae-5e1dd2ab2941", + "persona-model-version": "1", + "resource-version": "1485542667", + "vf-module-id": "b0eff878-e2e1-4947-9597-39afdd0f51dd", + "vf-module-name": "Vfmodule_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8" + } + }, + { + "extra-properties": { + "extra-property": [ + { + "property-name": "model.model-name", + "property-value": "C15ce9e1E9144c8fB8bb..dnsscaling..module-1" + }, + { + "property-name": "model.model-type", + "property-value": "resource" + }, + { + "property-name": "model.model-version", + "property-value": "1" + }, + { + "property-name": "model.model-id", + "property-value": "f32568ec-2f1c-458a-864b-0593d53d141a" + }, + { + "property-name": "model.model-name-version-id", + "property-value": "69615025-879d-4f0d-afe3-b7d1a7eeed1f" + } + ] + }, + "vf-module": { + "is-base-vf-module": false, + "persona-model-id": "f32568ec-2f1c-458a-864b-0593d53d141a", + "persona-model-version": "1.0", + "resource-version": "1485561752", + "vf-module-id": "dummy", + "vf-module-name": "dummy" + } + }, + { + "extra-properties": { + "extra-property": [ + { + "property-name": "model.model-name", + "property-value": "C15ce9e1E9144c8fB8bb..dnsscaling..module-1" + }, + { + "property-name": "model.model-type", + "property-value": "resource" + }, + { + "property-name": "model.model-version", + "property-value": "1" + }, + { + "property-name": "model.model-id", + "property-value": "f32568ec-2f1c-458a-864b-0593d53d141a" + }, + { + "property-name": "model.model-name-version-id", + "property-value": "69615025-879d-4f0d-afe3-b7d1a7eeed1f" + } + ] + }, + "vf-module": { + "heat-stack-id": "vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8/f447ce51-14dd-4dcd-9957-68a047c79673", + "is-base-vf-module": false, + "orchestration-status": "active", + "persona-model-id": "f32568ec-2f1c-458a-864b-0593d53d141a", + "persona-model-version": "1.0", + "resource-version": "1485562712", + "vf-module-id": "8cd79e44-1fae-48c1-a160-609f90b46749", + "vf-module-name": "vDNS_Ete_Named90e1ab3-dcd5-4877-9edb-eadfc84e32c8" + } + } + ] + } + }, + { + "extra-properties": {}, + "inventory-response-items": { + "inventory-response-item": [ + { + "cloud-region": { + "cloud-owner": "Rackspace", + "cloud-region-id": "DFW", + "cloud-region-version": "v1", + "cloud-type": "SharedNode", + "cloud-zone": "CloudZone", + "owner-defined-type": "OwnerType", + "resource-version": "1485465545" + }, + "extra-properties": {} + } + ] + }, + "tenant": { + "resource-version": "1485465545", + "tenant-id": "1015548", + "tenant-name": "1015548" + } + } + ] + }, + "vserver": { + "in-maint": false, + "is-closed-loop-disabled": false, + "prov-status": "ACTIVE", + "resource-version": "1485546436", + "vserver-id": "70f081eb-2a87-4c81-9296-4b93d7d145c6", + "vserver-name": "vlb-lb-32c8", + "vserver-name2": "vlb-lb-32c8", + "vserver-selflink": "https://dfw.servers.api.rackspacecloud.com/v2/1015548/servers/70f081eb-2a87-4c81-9296-4b93d7d145c6" + } + } + ] +} diff --git a/controlloop/templates/template.demo/README.md b/controlloop/templates/template.demo/README.md new file mode 100644 index 000000000..a037ba80d --- /dev/null +++ b/controlloop/templates/template.demo/README.md @@ -0,0 +1,3 @@ + +This is the ongoing implementation of template to support vFW/vDNS with integration with AAI. + diff --git a/controlloop/templates/template.demo/pom.xml b/controlloop/templates/template.demo/pom.xml new file mode 100644 index 000000000..e7aab68b3 --- /dev/null +++ b/controlloop/templates/template.demo/pom.xml @@ -0,0 +1,112 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>templates</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + <artifactId>template.demo</artifactId> + <dependencies> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-core</artifactId> + <version>6.3.0.Final</version> + </dependency> + <dependency> + <groupId>org.drools</groupId> + <artifactId>drools-compiler</artifactId> + <version>6.3.0.Final</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>appc</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>guard</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>aai</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>sdc</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>events</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>policy-yaml</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>eventmanager</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.4</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.2</version> + </dependency> + <dependency> + <groupId>com.att.research.xacml</groupId> + <artifactId>xacml</artifactId> + <version>1.0.0</version> + </dependency> + <dependency> + <groupId>com.att.research.xacml</groupId> + <artifactId>xacml-pdp</artifactId> + <version>1.0.0</version> + </dependency> + <dependency> + <groupId>javax.persistence</groupId> + <artifactId>persistence-api</artifactId> + <version>1.0.2</version> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>org.eclipse.persistence.jpa</artifactId> + <version>2.6.4</version> + </dependency> + + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-applications</groupId> + <artifactId>actor.appc</artifactId> + <version>1.1.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_1707_xacml_guard.drl b/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_1707_xacml_guard.drl new file mode 100644 index 000000000..330f41b56 --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/ControlLoop_Template_1707_xacml_guard.drl @@ -0,0 +1,917 @@ +/*- + * ============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 com.att.ecomp.policy.controlloop; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopLogger; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; +import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS; +import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.guard.PolicyGuard; +import org.onap.policy.guard.PolicyGuard.LockResult; +import org.onap.policy.guard.TargetLock; +import org.onap.policy.guard.GuardResult; +import org.onap.policy.guard.PolicyGuardRequest; +import org.onap.policy.guard.PolicyGuardResponse; +import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.annotations.RequestParser; +import org.onap.policy.guard.PolicyGuardXacmlHelper; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.Policy; +import java.net.URLDecoder; +import org.eclipse.persistence.exceptions.DatabaseException; + +// +// REPLACE THESE WITH PRODUCTION VERSIONS +// +import org.onap.policy.controlloop.ControlLoopLogger; +import org.onap.policy.drools.PolicyEngine; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +global ControlLoopLogger Logger; +global PolicyEngine Engine; +global PDPEngine XacmlPdpEngine; + +import java.time.Instant; +import java.util.LinkedList; +import java.util.Iterator; + +declare Params + closedLoopControlName : String + controlLoopYaml : String +end + + +declare OperationTimer + closedLoopControlName : String + requestID : String + delay : String +end + +declare ControlLoopTimer + closedLoopControlName : String + requestID : String + delay : String +end + + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* +*/ +rule "${policyName}.SETUP" + when + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Params params = new Params(); + params.setClosedLoopControlName("${closedLoopControlName}"); + params.setControlLoopYaml("${controlLoopYaml}"); + insert(params); + Logger.metrics("Inserted " + params); + Logger.info("------------------------------------------------------------------------------------------------"); + +end + +/* +* +* This rule responds to DCAE Events where there is no manager yet. Either it is +* the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled) +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) ) + then + try { + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + // + // Check the event, because we need it to not be null when + // we create the ControlLoopEventManager. The ControlLoopEventManager + // will do extra syntax checking as well check if the closed loop is disabled. + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } else { + // + // Create an EventManager + // + ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID); + // + // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.) + // + VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event); + notification.from = "pdp-0001-controller=controlloop"; // Engine.getInstanceName() + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Setup the Overall Control Loop timer + // + ControlLoopTimer clTimer = new ControlLoopTimer(); + clTimer.setClosedLoopControlName($event.closedLoopControlName); + clTimer.setRequestID($event.requestID.toString()); + clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s"); + // + // Insert it + // + insert(clTimer); + } else { + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this RequestID. + // + } + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is now created. We can start processing the yaml specification via the Event Manager. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($clTimer); + // + // Check which event this is. + // + ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + Logger.info("Event status is " + eventStatus); + // + // Check what kind of event this is + // + if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) { + // + // We don't care about subsequent onsets + // + Logger.info("Retracting Subsequent Onset " + $event); + retract($event); + return; + } + if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) { + // + // Ignore any bad syntax events + // + Logger.info("Retracting Bad Syntax Event " + $event); + retract($event); + return; + } + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) { + Logger.info("Retracting Event " + $event); + retract($event); + } + Logger.info("Checking due to new event " + $event.target); + // + // Now start seeing if we need to process this event + // + try { + // + // Check if this is a Final Event + // + VirtualControlLoopNotification notification = $manager.isControlLoopFinal(); + + + if (notification != null) { + // + // Its final, but are we waiting for abatement? + // + if ($manager.getNumAbatements() > 0) { + Logger.info("Abatement received, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + // + // TODO - what if we get subsequent Events for this RequestID? + // By default, it will all start over again. May be confusing for Ruby. + // Or, we could track this and then subsequently ignore the events + // + } else { + // + // Check whether we need to wait for abatement + // + if ($manager.getProcessor().getControlLoop().abatement == true && notification.notification == ControlLoopNotificationType.FINAL_SUCCESS) { + Logger.info("Waiting for abatement."); + } else { + Logger.info("No abatement is promised to come, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + } + } + } else { + // + // NOT final, so let's ask for the next operation + // + ControlLoopOperationManager operation = $manager.processControlLoop(); + if (operation != null) { + Logger.info("starting a new operation" + operation); + // + // insert into memory + // + insert(operation); + // + // insert operation timeout object + // + OperationTimer opTimer = new OperationTimer(); + opTimer.setClosedLoopControlName($event.closedLoopControlName); + opTimer.setRequestID($event.requestID.toString()); + opTimer.setDelay(operation.getOperationTimeout().toString() + "s"); + insert(opTimer); + + // + // Let's ask for a lock right away + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("manager returned lock " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } + } else { + // + // Probably waiting for abatement + // + } + } + } catch (Exception e) { + e.printStackTrace(); + /* + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // TODO should we abort if we get an exception? + // + */ + } + +end + + + +/* +* +* +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.NOT_LOCKED.TIMEOUT" + timer (int: 5s 5s) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + not ( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + // + // Need to ask for a Lock + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("Lock acquired: " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } +end + +/* +* +* Guard Permitted, let's send request to the actor. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "Permit" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + + + Object request = $operation.getOperationRequest(); + + if (request != null) { + Logger.info("Starting operation"); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage(); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + switch ($operation.policy.actor){ + + case "APPC": + + if (request instanceof Request) { + Engine.deliver("UEB", "APPC-CL", request); + } + case "SDNR": + default: + } + + + } else { + // + // What happens if its null? + // + } +end + + +/* +* +* We were able to acquire a lock so now let's ask Xacml Guard whether we are allowed to proceed with the request to the actor. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "NONE" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + + + + + // + // We are starting the operation but the actor won't be contacted until Guard is queried and permitted. + // + $operation.startOperation($event); + + // + // Sending notification that we are about to query Guard ("DB write - start operation") + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage(); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + // + // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, just change guardEnabled to false. + // + // In order to use REST XACML, provide a URL instead of "" as a second argument o the CallGuardTask() and set the first + // argument to null (instead of XacmlPdpEngine). + // + boolean guardEnabled = true; + + if(guardEnabled){ + + Thread t = new Thread(new org.onap.policy.guard.CallGuardTask( + XacmlPdpEngine, + "", + drools.getWorkingMemory(), + $operation.policy.actor.toString(), + $operation.policy.recipe, + $manager.getTargetInstance($operation.policy), + //$event.target, + $event.requestID.toString() + )); + t.start(); + } + else{ + insert(new PolicyGuardResponse("Permit", $event.requestID, $operation.policy.recipe)); + } + + + + +end + +// +//This rule will be triggered when a thread talking to the XACML Guard inserts a guardResponse object into the working memory +// +rule "${policyName}.GUARD.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $lock : TargetLock (requestID == $event.requestID) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $guardResponse : PolicyGuardResponse(requestID == $event.requestID, $operation.policy.recipe == operation) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($operation); + Logger.metrics($lock); + Logger.metrics($guardResponse); + + + //we will permit the operation if there was no Guard for it + if($guardResponse.result == "Indeterminate"){ + $guardResponse.result = "Permit"; + } + + // + // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny") + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage($guardResponse.result); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + + + if($guardResponse.result == "Permit"){ + + modify($operation){setGuardApprovalStatus($guardResponse.result)}; + } + else { + //This is the Deny case + $operation.setOperationHasGuardDeny(); + retract($opTimer); + retract($operation); + modify($manager) {finishOperation($operation)}; + } + + retract($guardResponse); + +end + + + + +/* +* +* This rule responds to APPC Response Events +* +* I would have like to be consistent and write the Response like this: +* $response : Response( CommonHeader.RequestID == $onset.requestID ) +* +* However, no compile error was given. But a runtime error was given. I think +* because drools is confused between the classname CommonHeader vs the property CommonHeader. +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $lock : TargetLock (requestID == $event.requestID) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + Logger.metrics($response); + // + // Get the result of the operation + // + PolicyResult policyResult = $operation.onResponse($response); + if (policyResult != null) { + Logger.info("operation finished with result: " + policyResult); + // + // This Operation has completed, construct a notification showing our results. (DB write - end operation) + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + if (policyResult.equals(PolicyResult.SUCCESS)) { + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } else { + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // We must also retract the timer object + // NOTE: We could write a Rule to do this + // + retract($opTimer); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } + } else { + // + // Its not finished yet (i.e. expecting more Response objects) + // + // Or possibly it is a leftover response that we timed the request out previously + // + } + // + // We are going to retract these objects from memory + // + retract($response); +end + +/* +* +* The problem with Responses is that they don't have a controlLoopControlName +* field in them, so the only way to attach them is via RequestID. If we have multiple +* control loop .drl's loaded in the same container, we need to be sure the cleanup +* rules don't remove Responses for other control loops. +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + // + // Retract it + // + retract($response); +end +/* +* +* This is the timer that manages the timeout for an individual operation. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + // + // Tell it its timed out + // + $operation.setOperationHasTimedOut(); + // + // Create a notification for it ("DB Write - end operation") + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Get rid of the timer + // + retract($opTimer); + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } +end + +/* +* +* This is the timer that manages the overall control loop timeout. +* +*/ +rule "${policyName}.EVENT.MANAGER.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $operations : LinkedList() + from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) ) + $opTimers : LinkedList() + from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) ) + $locks : LinkedList() + from collect( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($clTimer); + if ($operations == null) { + Logger.info("no operations found"); + } else { + Logger.info("found " + $operations.size() + " operations"); + } + // + // Tell the Event Manager it has timed out + // + VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut(); + if (notification != null) { + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Retract EVERYTHING + // + retract($event); + retract($manager); + retract($clTimer); + if ($operations != null && $operations.size() > 0) { + Iterator<ControlLoopOperationManager> iter = $operations.iterator(); + while (iter.hasNext()) { + ControlLoopOperationManager manager = iter.next(); + retract(manager); + } + } + if ($opTimers != null && $opTimers.size() > 0) { + Iterator<OperationTimer> iter = $opTimers.iterator(); + while (iter.hasNext()) { + OperationTimer opTimer = iter.next(); + retract(opTimer); + } + } + if ($locks != null && $locks.size() > 0) { + Iterator<TargetLock> iter = $locks.iterator(); + while (iter.hasNext()) { + TargetLock lock = iter.next(); + // + // Ensure we release the lock + // + PolicyGuard.unlockTarget(lock); + // + // + // + retract(lock); + } + } +end diff --git a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml new file mode 100644 index 000000000..560fa57f1 --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-unless-deny"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Deny"> + <Description>DENY - only if target is in black list and guard is active.</Description> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and"> + <VariableReference VariableId="isGuardActive"/> + <VariableReference VariableId="isInBlackList"/> + </Apply> + </Condition> + </Rule> + <VariableDefinition VariableId="isInBlackList"> + <Apply FunctionId="urn:oasis:names:tc:xacml:3.0:function:any-of"> + <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="urn:oasis:names:tc:xacml:1.0:target:target-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Apply> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag"> + ${blackListElement} + <!-- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vserver.vserver-name</AttributeValue>--> + </Apply> + </Apply> + </VariableDefinition> + <VariableDefinition VariableId="isGuardActive"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </VariableDefinition> +</Policy> 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 new file mode 100644 index 000000000..221fd6ddf --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-unless-deny"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Deny"> + <Description>DENY - only if number of operations performed in the past is larger than the limit and the Guard is active.</Description> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and"> + <VariableReference VariableId="isGuardActive"/> + <VariableReference VariableId="isHistoryGreaterThanLimit"/> + </Apply> + </Condition> + </Rule> + <VariableDefinition VariableId="isGuardActive"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </VariableDefinition> + <VariableDefinition VariableId="isHistoryGreaterThanLimit"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="com:att:research:xacml:guard:historydb:tw:${twValue}:${twUnits}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </VariableDefinition> +</Policy> diff --git a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml new file mode 100644 index 000000000..45cc5d829 --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-unless-deny"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${actor}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">${recipe}</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Deny"> + <Description>DENY - only if number of operations performed in the past is larger than the limit and the Guard is active.</Description> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and"> + <VariableReference VariableId="isGuardActive"/> + <VariableReference VariableId="isHistoryGreaterThanLimit"/> + </Apply> + </Condition> + </Rule> + <VariableDefinition VariableId="isGuardActive"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue> + </Apply> + </VariableDefinition> + <VariableDefinition VariableId="isHistoryGreaterThanLimit"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="com:att:research:xacml:test:sql:${timeWindow}" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue> + </Apply> + </VariableDefinition> +</Policy> diff --git a/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1610_v1.1_xacml_guard.drl b/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1610_v1.1_xacml_guard.drl new file mode 100644 index 000000000..a743502ce --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1610_v1.1_xacml_guard.drl @@ -0,0 +1,867 @@ +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2016 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package com.att.ecomp.policy.controlloop; + +import com.att.ecomp.policy.controlloop.ATTControlLoopEvent; +import org.openecomp.policy.controlloop.VirtualControlLoopEvent; +import org.openecomp.policy.controlloop.VirtualControlLoopNotification; +import org.openecomp.policy.controlloop.ControlLoopEventStatus; +import com.att.ecomp.policy.controlloop.ATTControlLoopNotification; +import org.openecomp.policy.controlloop.ControlLoopNotificationType; +import com.att.ecomp.policy.controlloop.ControlLoopLogger; +import com.att.ecomp.policy.controlloop.policy.PolicyResult; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopEventManager; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopOperationManager; +import org.openecomp.policy.appc.Request; +import org.openecomp.policy.appc.Response; +import org.openecomp.policy.appc.CommonHeader; +import com.att.ecomp.policy.guard.PolicyGuard; +import com.att.ecomp.policy.guard.PolicyGuard.LockResult; +import com.att.ecomp.policy.guard.TargetLock; +import com.att.ecomp.policy.guard.GuardResult; +import com.att.ecomp.policy.guard.PolicyGuardRequest; +import com.att.ecomp.policy.guard.PolicyGuardResponse; +import com.att.ecomp.policy.guard.PolicyGuardXacmlRequestAttributes; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.annotations.RequestParser; +import com.att.ecomp.policy.guard.PolicyGuardXacmlHelper; + +// +// REPLACE THESE WITH PRODUCTION VERSIONS +// +import com.att.ecomp.policy.controlloop.ControlLoopLogger; +import com.att.ecomp.policy.drools.PolicyEngine; + +global ControlLoopLogger Logger; +global PolicyEngine Engine; +global PDPEngine XacmlPdpEngine; + +import java.time.Instant; +import java.util.LinkedList; +import java.util.Iterator; + +declare Params + closedLoopControlName : String + controlLoopYaml : String +end + +declare OperationTimer + closedLoopControlName : String + requestID : String + delay : String +end + +declare ControlLoopTimer + closedLoopControlName : String + requestID : String + delay : String +end + + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* +*/ +rule "${policyName}.SETUP" + when + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Params params = new Params(); + params.setClosedLoopControlName("${closedLoopControlName}"); + params.setControlLoopYaml("${controlLoopYaml}"); + insert(params); + Logger.metrics("Inserted " + params); + Logger.info("------------------------------------------------------------------------------------------------"); +end + +/* +* +* This rule responds to DCAE Events where there is no manager yet. Either it is +* the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled) +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) ) + then + try { + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + // + // Check the event, because we need it to not be null when + // we create the ControlLoopEventManager. The ControlLoopEventManager + // will do extra syntax checking as well check if the closed loop is disabled. + // + if ($event.requestID == null) { + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } else { + // + // Create an EventManager + // + ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID); + // + // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.) + // + VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event); + notification.from = "pdp-0001-controller=controlloop"; // Engine.getInstanceName() + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Setup the Overall Control Loop timer + // + ControlLoopTimer clTimer = new ControlLoopTimer(); + clTimer.setClosedLoopControlName($event.closedLoopControlName); + clTimer.setRequestID($event.requestID.toString()); + clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s"); + // + // Insert it + // + insert(clTimer); + } else { + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this RequestID. + // + } + } catch (Exception e) { + e.printStackTrace(); + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is now created. We can start processing the yaml specification via the Event Manager. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($clTimer); + // + // Check which event this is. + // + ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + Logger.info("Event status is " + eventStatus); + // + // Check what kind of event this is + // + if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) { + // + // We don't care about subsequent onsets + // + Logger.info("Retracting Subsequent Onset " + $event); + retract($event); + return; + } + if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) { + // + // Ignore any bad syntax events + // + Logger.info("Retracting Bad Syntax Event " + $event); + retract($event); + return; + } + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) { + Logger.info("Retracting Event " + $event); + retract($event); + } + Logger.info("Checking due to new event " + $event.triggerID); + // + // Now start seeing if we need to process this event + // + try { + // + // Check if this is a Final Event + // + ATTControlLoopNotification notification = $manager.isControlLoopFinal(); + + + if (notification != null) { + // + // Its final, but are we waiting for abatement? + // + if ($manager.getNumAbatements() > 0) { + Logger.info("Abatement received, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + // + // TODO - what if we get subsequent Events for this RequestID? + // By default, it will all start over again. May be confusing for Ruby. + // Or, we could track this and then subsequently ignore the events + // + } else { + // + // Check whether we need to wait for abatement + // + if ($manager.getProcessor().getControlLoop().abatement == true && notification.notification == ControlLoopNotificationType.FINAL_SUCCESS) { + Logger.info("Waiting for abatement."); + } else { + Logger.info("No abatement is promised to come, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + } + } + } else { + // + // NOT final, so let's ask for the next operation + // + ControlLoopOperationManager operation = $manager.processControlLoop(); + if (operation != null) { + Logger.info("starting a new operation" + operation); + // + // insert into memory + // + insert(operation); + // + // insert operation timeout object + // + OperationTimer opTimer = new OperationTimer(); + opTimer.setClosedLoopControlName($event.closedLoopControlName); + opTimer.setRequestID($event.requestID.toString()); + opTimer.setDelay(operation.getOperationTimeout().toString() + "s"); + insert(opTimer); + + // + // Let's ask for a lock right away + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("manager returned lock " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } + } else { + // + // Probably waiting for abatement + // + } + } + } catch (Exception e) { + e.printStackTrace(); + /* + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // TODO should we abort if we get an exception? + // + */ + } + +end + +/* +* +* +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.NOT_LOCKED.TIMEOUT" + timer (int: 5s 5s) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + not ( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + // + // Need to ask for a Lock + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("Lock acquired: " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } +end + +/* +* +* +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "Permit" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + // + // Start the Operation + // + //Object request = $operation.startOperation($event); + //$operation.startOperation($event); + Object request = $operation.getOperationRequest(); + + if (request != null) { + Logger.info("Starting operation"); + // + // Tell interested parties we are performing this Operation + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage(); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Send the APPC request + // + if (request instanceof Request) { + Engine.deliver("UEB", "APPC-CL", request); + } + // + // TODO: send different types of requests + // + + } else { + // + // What happens if its null? + // + } +end + + +/* +* +* +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "NONE" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + + $operation.startOperation($event); + // + // Now send Guard Request to XACML Guard + // + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes($operation.policy.actor.toString(), $operation.policy.recipe, $event.target, $event.requestID.toString()); + //Engine.deliver("UEB", "GUARD-CL", xacmlReq/*request*/); + System.out.println("\n********** XACML REQUEST START ********"); + System.out.println(RequestParser.parseRequest(xacmlReq)); + System.out.println("********** XACML REQUEST END ********\n"); + + com.att.research.xacml.api.Response xacmlResponse = PolicyGuardXacmlHelper.callPDP(XacmlPdpEngine, "", (com.att.research.xacml.api.Request) RequestParser.parseRequest(xacmlReq), false); + + System.out.println("\n********** XACML RESPONSE 1 START ********"); + System.out.println(xacmlResponse); + System.out.println("********** XACML RESPONSE 1 END ********\n"); + + PolicyGuardResponse guardResponse = PolicyGuardXacmlHelper.ParseXacmlPdpResponse(xacmlResponse); + System.out.println("\n\n============ Guard inserted with decision "+ guardResponse.result + " !!! ===========\n\n"); + + + insert(guardResponse); + +end + + + +rule "${policyName}.GUARD.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $lock : TargetLock (requestID == $event.requestID) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $guardResponse : PolicyGuardResponse(/*requestID == $event.requestID, $operation.policy.recipe == operation*/) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($operation); + Logger.metrics($lock); + Logger.metrics($guardResponse); + + + //we will permit the operation if there was no Guard for it + if($guardResponse.result == "Indeterminate"){ + $guardResponse.result = "Permit"; + } + + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage($guardResponse.result);//"Guard result: " + $guardResponse.result; + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + + + if($guardResponse.result == "Permit"){ + + modify($operation){setGuardApprovalStatus($guardResponse.result)}; + } + else { + //This is the Deny case + $operation.setOperationHasGuardDeny(); + retract($opTimer); + retract($operation); + modify($manager) {finishOperation($operation)}; + } + + retract($guardResponse); + +end + + + + +/* +* +* This rule responds to APPC Response Events +* +* I would have like to be consistent and write the Response like this: +* $response : Response( CommonHeader.RequestID == $onset.requestID ) +* +* However, no compile error was given. But a runtime error was given. I think +* because drools is confused between the classname CommonHeader vs the property CommonHeader. +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $lock : TargetLock (requestID == $event.requestID) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + Logger.metrics($response); + // + // Get the result of the operation + // + PolicyResult policyResult = $operation.onResponse($response); + if (policyResult != null) { + Logger.info("operation finished with result: " + policyResult); + // + // This Operation has completed, construct a notification showing our results + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + if (policyResult.equals(PolicyResult.SUCCESS)) { + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } else { + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // We must also retract the timer object + // NOTE: We could write a Rule to do this + // + retract($opTimer); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } + } else { + // + // Its not finished yet (i.e. expecting more Response objects) + // + // Or possibly it is a leftover response that we timed the request out previously + // + } + // + // We are going to retract these objects from memory + // + retract($response); +end + +/* +* +* The problem with Responses is that they don't have a controlLoopControlName +* field in them, so the only way to attach them is via RequestID. If we have multiple +* control loop .drl's loaded in the same container, we need to be sure the cleanup +* rules don't remove Responses for other control loops. +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + // + // Retract it + // + retract($response); +end +/* +* +* This is the timer that manages the timeout for an individual operation. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + // + // Tell it its timed out + // + $operation.setOperationHasTimedOut(); + // + // Create a notification for it + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Get rid of the timer + // + retract($opTimer); + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } +end + +/* +* +* This is the timer that manages the overall control loop timeout. +* +*/ +rule "${policyName}.EVENT.MANAGER.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $operations : LinkedList() + from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) ) + $opTimers : LinkedList() + from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) ) + $locks : LinkedList() + from collect( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($clTimer); + if ($operations == null) { + Logger.info("no operations found"); + } else { + Logger.info("found " + $operations.size() + " operations"); + } + // + // Tell the Event Manager it has timed out + // + VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut(); + if (notification != null) { + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Retract EVERYTHING + // + retract($event); + retract($manager); + retract($clTimer); + if ($operations != null && $operations.size() > 0) { + Iterator<ControlLoopOperationManager> iter = $operations.iterator(); + while (iter.hasNext()) { + ControlLoopOperationManager manager = iter.next(); + retract(manager); + } + } + if ($opTimers != null && $opTimers.size() > 0) { + Iterator<OperationTimer> iter = $opTimers.iterator(); + while (iter.hasNext()) { + OperationTimer opTimer = iter.next(); + retract(opTimer); + } + } + if ($locks != null && $locks.size() > 0) { + Iterator<TargetLock> iter = $locks.iterator(); + while (iter.hasNext()) { + TargetLock lock = iter.next(); + // + // Ensure we release the lock + // + PolicyGuard.unlockTarget(lock); + // + // + // + retract(lock); + } + } +end diff --git a/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1707_xacml_guard_enodeb.drl b/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1707_xacml_guard_enodeb.drl new file mode 100644 index 000000000..b4f160951 --- /dev/null +++ b/controlloop/templates/template.demo/src/main/resources/old/ControlLoop_Template_1707_xacml_guard_enodeb.drl @@ -0,0 +1,952 @@ +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2016 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package com.att.ecomp.policy.controlloop; + +import com.att.ecomp.policy.controlloop.ATTControlLoopEvent; +import org.openecomp.policy.controlloop.VirtualControlLoopEvent; +import org.openecomp.policy.controlloop.VirtualControlLoopNotification; +import org.openecomp.policy.controlloop.ControlLoopEventStatus; +import com.att.ecomp.policy.controlloop.ATTControlLoopNotification; +import org.openecomp.policy.controlloop.ControlLoopNotificationType; +import com.att.ecomp.policy.controlloop.ControlLoopLogger; +import com.att.ecomp.policy.controlloop.policy.PolicyResult; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopEventManager; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS; +import com.att.ecomp.policy.controlloop.eventmanager.ControlLoopOperationManager; +import org.openecomp.policy.appc.Request; +import org.openecomp.policy.appc.Response; +import org.openecomp.policy.appc.CommonHeader; +import com.att.ecomp.policy.guard.PolicyGuard; +import com.att.ecomp.policy.guard.PolicyGuard.LockResult; +import com.att.ecomp.policy.guard.TargetLock; +import com.att.ecomp.policy.guard.GuardResult; +import com.att.ecomp.policy.guard.PolicyGuardRequest; +import com.att.ecomp.policy.guard.PolicyGuardResponse; +import com.att.ecomp.policy.guard.PolicyGuardXacmlRequestAttributes; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.annotations.RequestParser; +import com.att.ecomp.policy.guard.PolicyGuardXacmlHelper; +import com.att.ecomp.policy.controlloop.policy.ControlLoopPolicy; +import com.att.ecomp.policy.controlloop.policy.Policy; +import java.net.URLDecoder; +import org.eclipse.persistence.exceptions.DatabaseException; + +// +// REPLACE THESE WITH PRODUCTION VERSIONS +// +import com.att.ecomp.policy.controlloop.ControlLoopLogger; +import com.att.ecomp.policy.drools.PolicyEngine; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +global ControlLoopLogger Logger; +global PolicyEngine Engine; +global PDPEngine XacmlPdpEngine; + +import java.time.Instant; +import java.util.LinkedList; +import java.util.Iterator; + +declare Params + closedLoopControlName : String + controlLoopYaml : String +end + +declare EnbParams + enbOperationsPeriodicTimer : String +end + + +declare OperationTimer + closedLoopControlName : String + requestID : String + delay : String +end + +declare ControlLoopTimer + closedLoopControlName : String + requestID : String + delay : String +end + + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* +*/ +rule "${policyName}.SETUP" + when + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Params params = new Params(); + params.setClosedLoopControlName("${closedLoopControlName}"); + params.setControlLoopYaml("${controlLoopYaml}"); + insert(params); + Logger.metrics("Inserted " + params); + Logger.info("------------------------------------------------------------------------------------------------"); + EnbParams enbParams = new EnbParams(); + + // + //Fetching the eNodeB timer from the Yaml + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(URLDecoder.decode(params.getControlLoopYaml(), "UTF-8")); + + enbParams.setEnbOperationsPeriodicTimer("0s"); + for(Policy policy : ((ControlLoopPolicy)obj).policies){ + if(policy.actor.equals("APPC")){ + if(policy.payload != null){ + if(policy.payload.containsKey("enbOperationPeriodicTimer")){ + enbParams.setEnbOperationsPeriodicTimer(policy.payload.get("enbOperationPeriodicTimer")); + } + } + break; + } + } + insert(enbParams); + System.out.println("################ got timer: " + enbParams.getEnbOperationsPeriodicTimer()); + +end + +/* +* +* This rule responds to DCAE Events where there is no manager yet. Either it is +* the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled) +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) ) + then + try { + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + // + // Check the event, because we need it to not be null when + // we create the ControlLoopEventManager. The ControlLoopEventManager + // will do extra syntax checking as well check if the closed loop is disabled. + // + if ($event.requestID == null) { + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } else { + // + // Create an EventManager + // + ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID); + // + // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.) + // + VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event); + notification.from = "pdp-0001-controller=controlloop"; // Engine.getInstanceName() + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Setup the Overall Control Loop timer + // + ControlLoopTimer clTimer = new ControlLoopTimer(); + clTimer.setClosedLoopControlName($event.closedLoopControlName); + clTimer.setRequestID($event.requestID.toString()); + clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s"); + // + // Insert it + // + insert(clTimer); + } else { + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this RequestID. + // + } + } catch (Exception e) { + e.printStackTrace(); + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is now created. We can start processing the yaml specification via the Event Manager. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($clTimer); + // + // Check which event this is. + // + ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + Logger.info("Event status is " + eventStatus); + // + // Check what kind of event this is + // + if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) { + // + // We don't care about subsequent onsets + // + Logger.info("Retracting Subsequent Onset " + $event); + retract($event); + return; + } + if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) { + // + // Ignore any bad syntax events + // + Logger.info("Retracting Bad Syntax Event " + $event); + retract($event); + return; + } + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) { + Logger.info("Retracting Event " + $event); + retract($event); + } + Logger.info("Checking due to new event " + $event.triggerID); + // + // Now start seeing if we need to process this event + // + try { + // + // Check if this is a Final Event + // + ATTControlLoopNotification notification = $manager.isControlLoopFinal(); + + + if (notification != null) { + // + // Its final, but are we waiting for abatement? + // + if ($manager.getNumAbatements() > 0) { + Logger.info("Abatement received, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + // + // TODO - what if we get subsequent Events for this RequestID? + // By default, it will all start over again. May be confusing for Ruby. + // Or, we could track this and then subsequently ignore the events + // + } else { + // + // Check whether we need to wait for abatement + // + if ($manager.getProcessor().getControlLoop().abatement == true && notification.notification == ControlLoopNotificationType.FINAL_SUCCESS) { + Logger.info("Waiting for abatement."); + } else { + Logger.info("No abatement is promised to come, close out the control loop for " + $event.requestID); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // In this case, we are done + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Unlock the target + // + TargetLock lock = $manager.unlockCurrentOperation(); + if (lock != null) { + System.out.println("retracting lock " + lock); + retract(lock); + } + // + // Retract everything from memory + // + System.out.println("retracting onset"); + retract($manager.getOnsetEvent()); + retract($manager); + retract($clTimer); + } + } + } else { + // + // NOT final, so let's ask for the next operation + // + ControlLoopOperationManager operation = $manager.processControlLoop(); + if (operation != null) { + Logger.info("starting a new operation" + operation); + // + // insert into memory + // + insert(operation); + // + // insert operation timeout object + // + OperationTimer opTimer = new OperationTimer(); + opTimer.setClosedLoopControlName($event.closedLoopControlName); + opTimer.setRequestID($event.requestID.toString()); + opTimer.setDelay(operation.getOperationTimeout().toString() + "s"); + insert(opTimer); + + // + // Let's ask for a lock right away + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("manager returned lock " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } + } else { + // + // Probably waiting for abatement + // + } + } + } catch (Exception e) { + e.printStackTrace(); + /* + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // TODO should we abort if we get an exception? + // + */ + } + +end + +/* +* +* +* +*/ +rule "${policyName}.PERIODIC_CHECK_OF_PENDING_ENB_OPERATIONS" + timer (expr: "0s", $t) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $enbParams : EnbParams($t : getEnbOperationsPeriodicTimer()) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $operations : LinkedList(size() > 0) + from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName) ) + + then + System.out.println(drools.getRule().getName() + " ********** operations size: " + $operations.size()); + //System.out.println(drools.getRule().getName()); + //The limt of 5 should also be defined in Yaml. +end + + +/* +* +* +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.NOT_LOCKED.TIMEOUT" + timer (int: 5s 5s) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + not ( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + // + // Need to ask for a Lock + // + LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation(); + if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) { + Logger.info("Lock acquired: " + result.getB()); + // + // Insert into memory + // + insert(result.getB()); + } +end + +/* +* +* Guard Permitted, let's send request to the actor. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "Permit" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + + + Object request = $operation.getOperationRequest(); + + if (request != null) { + Logger.info("Starting operation"); + // + // Tell interested parties we are performing this Operation + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage(); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + switch ($operation.policy.actor){ + + case "APPC": + + if (request instanceof Request) { + Engine.deliver("UEB", "APPC-CL", request); + } + case "SDNR": + default: + } + + + } else { + // + // What happens if its null? + // + } +end + + +/* +* +* We were able to acquire a lock so now let's ask Xacml Guard whether we are allowed to proceed with the request to the actor. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "NONE" ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($lock); + + + + + // + // We are starting the operation but the actor won't be contacted until Guard is queried and permitted. + // + $operation.startOperation($event); + + // + // Sending notification that we are about to query Guard ("DB write - start operation") + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage(); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + // + // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, just change guardEnabled to false. + // + // In order to use REST XACML, provide a URL instead of "" as a second argument o the CallGuardTask() and set the first + // argument to null (instead of XacmlPdpEngine). + // + boolean guardEnabled = true; + + if(guardEnabled){ + + Thread t = new Thread(new com.att.ecomp.policy.guard.CallGuardTask( + XacmlPdpEngine, + "", + drools.getWorkingMemory(), + $operation.policy.actor.toString(), + $operation.policy.recipe, + $event.target, + $event.requestID.toString() + )); + t.start(); + } + else{ + insert(new PolicyGuardResponse("Permit", $event.requestID, $operation.policy.recipe)); + } + + + + +end + +// +//This rule will be triggered when a thread talking to the XACML Guard inserts a guardResponse object into the working memory +// +rule "${policyName}.GUARD.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $lock : TargetLock (requestID == $event.requestID) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $guardResponse : PolicyGuardResponse(requestID == $event.requestID, $operation.policy.recipe == operation) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($operation); + Logger.metrics($lock); + Logger.metrics($guardResponse); + + + //we will permit the operation if there was no Guard for it + if($guardResponse.result == "Indeterminate"){ + $guardResponse.result = "Permit"; + } + + // + // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny") + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.message = $operation.getOperationMessage($guardResponse.result); + notification.history = $operation.getHistory(); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + + + + if($guardResponse.result == "Permit"){ + + modify($operation){setGuardApprovalStatus($guardResponse.result)}; + } + else { + //This is the Deny case + $operation.setOperationHasGuardDeny(); + retract($opTimer); + retract($operation); + modify($manager) {finishOperation($operation)}; + } + + retract($guardResponse); + +end + + + + +/* +* +* This rule responds to APPC Response Events +* +* I would have like to be consistent and write the Response like this: +* $response : Response( CommonHeader.RequestID == $onset.requestID ) +* +* However, no compile error was given. But a runtime error was given. I think +* because drools is confused between the classname CommonHeader vs the property CommonHeader. +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) + $lock : TargetLock (requestID == $event.requestID) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($event); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + Logger.metrics($response); + // + // Get the result of the operation + // + PolicyResult policyResult = $operation.onResponse($response); + if (policyResult != null) { + Logger.info("operation finished with result: " + policyResult); + // + // This Operation has completed, construct a notification showing our results. (DB write - end operation) + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + if (policyResult.equals(PolicyResult.SUCCESS)) { + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } else { + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // We must also retract the timer object + // NOTE: We could write a Rule to do this + // + retract($opTimer); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } + } else { + // + // Its not finished yet (i.e. expecting more Response objects) + // + // Or possibly it is a leftover response that we timed the request out previously + // + } + // + // We are going to retract these objects from memory + // + retract($response); +end + +/* +* +* The problem with Responses is that they don't have a controlLoopControlName +* field in them, so the only way to attach them is via RequestID. If we have multiple +* control loop .drl's loaded in the same container, we need to be sure the cleanup +* rules don't remove Responses for other control loops. +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + // + // Retract it + // + retract($response); +end +/* +* +* This is the timer that manages the timeout for an individual operation. +* +*/ +rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) + $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $lock : TargetLock (requestID == $event.requestID) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($operation); + Logger.metrics($opTimer); + Logger.metrics($lock); + // + // Tell it its timed out + // + $operation.setOperationHasTimedOut(); + // + // Create a notification for it ("DB Write - end operation") + // + ATTControlLoopNotification notification = new ATTControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + notification.message = $operation.getOperationHistory(); + notification.history = $operation.getHistory(); + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + // + // Get rid of the timer + // + retract($opTimer); + // + // Ensure the operation is complete + // + if ($operation.isOperationComplete() == true) { + // + // It is complete, remove it from memory + // + retract($operation); + // + // Complete the operation + // + modify($manager) {finishOperation($operation)}; + } else { + // + // Just doing this will kick off the LOCKED rule again + // + modify($operation) {}; + } +end + +/* +* +* This is the timer that manages the overall control loop timeout. +* +*/ +rule "${policyName}.EVENT.MANAGER.TIMEOUT" + timer (expr: $to ) + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : ATTControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() ) + $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) + $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() ) + $operations : LinkedList() + from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) ) + $opTimers : LinkedList() + from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) ) + $locks : LinkedList() + from collect( TargetLock (requestID == $event.requestID) ) + then + // + // Logging + // + Logger.info("------------------------------------------------------------------------------------------------"); + Logger.metrics(Instant.now() + " " + drools.getRule().getName() + " " + drools.getRule().getPackage()); + Logger.metrics($params); + Logger.metrics($manager); + Logger.metrics($clTimer); + if ($operations == null) { + Logger.info("no operations found"); + } else { + Logger.info("found " + $operations.size() + " operations"); + } + // + // Tell the Event Manager it has timed out + // + VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut(); + if (notification != null) { + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + Engine.deliver("UEB", "POLICY-CL-MGT", notification); + } + // + // Retract EVERYTHING + // + retract($event); + retract($manager); + retract($clTimer); + if ($operations != null && $operations.size() > 0) { + Iterator<ControlLoopOperationManager> iter = $operations.iterator(); + while (iter.hasNext()) { + ControlLoopOperationManager manager = iter.next(); + retract(manager); + } + } + if ($opTimers != null && $opTimers.size() > 0) { + Iterator<OperationTimer> iter = $opTimers.iterator(); + while (iter.hasNext()) { + OperationTimer opTimer = iter.next(); + retract(opTimer); + } + } + if ($locks != null && $locks.size() > 0) { + Iterator<TargetLock> iter = $locks.iterator(); + while (iter.hasNext()) { + TargetLock lock = iter.next(); + // + // Ensure we release the lock + // + PolicyGuard.unlockTarget(lock); + // + // + // + retract(lock); + } + } +end 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 new file mode 100644 index 000000000..1562c0ce6 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/ControlLoopXacmlGuardTest.java @@ -0,0 +1,674 @@ +/*- + * ============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<ControlLoopPolicy, String> 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<String, String>(); + 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<String, String>(); + 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<String, String>(); + 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 new file mode 100644 index 000000000..afb1e9b22 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/controlloop/processor/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.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<A, B> { + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } + + public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas"); + System.out.println(contents); + //for(Policy policy : ((ControlLoopPolicy)obj).policies){ + + return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + +} diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_1.xml b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_1.xml new file mode 100644 index 000000000..1a70d0468 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_1.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">APPC</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Restart</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Permit"> + <Description>PERMIT - only if number of operations performed in the past is less than the limit.</Description> + <Target/> + <Condition> + <VariableReference VariableId="isHistoryLessOrEqual"/> + </Condition> + </Rule> + <VariableDefinition VariableId="isHistoryLessOrEqual"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="com:att:research:xacml:test:sql" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">1</AttributeValue> + </Apply> + </VariableDefinition> + <Rule RuleId="urn:com:att:xacml:rule:id:c9a3fb7d-d0b9-48bb-bdca-87eb4957120c" Effect="Deny"> + <Description>DENY - default.</Description> + <Target/> + </Rule> +</Policy> diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_2.xml b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_2.xml new file mode 100644 index 000000000..e7e34feeb --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_2.xml @@ -0,0 +1,52 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">APPC</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Restart</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Permit"> + <Description>PERMIT - only if number of operations performed in the past is less than the limit.</Description> + + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-equal"> + + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:boolean-bag-size"> + + <Apply FunctionId="urn:oasis:names:tc:xacml:3.0:function:map"> + + <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:dateTime-less-than-or-equal"/> + + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:dateTime-subtract-dayTimeDuration"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:dateTime-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-dateTime" DataType="http://www.w3.org/2001/XMLSchema#dateTime" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#dayTimeDuration">PT10M</AttributeValue> + </Apply> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:starttimebag" DataType="http://www.w3.org/2001/XMLSchema#dateTime" Issuer="com:att:research:xacml:test:sql" MustBePresent="false"/> + </Apply> + </Apply> + + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">22</AttributeValue> + + </Apply> + </Condition> + </Rule> + + + <Rule RuleId="urn:com:att:xacml:rule:id:c9a3fb7d-d0b9-48bb-bdca-87eb4957120c" Effect="Deny"> + <Description>DENY - default.</Description> + <Target/> + </Rule> + +</Policy> diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_3.xml b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_3.xml new file mode 100644 index 000000000..c171968d2 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_3.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">APPC</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Restart</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Permit"> + <Description>PERMIT - only if number of operations performed in the past is less than the limit.</Description> + <Target/> + <Condition> + <VariableReference VariableId="isHistoryLessOrEqual"/> + </Condition> + </Rule> + <VariableDefinition VariableId="isHistoryLessOrEqual"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="com:att:research:xacml:test:sql:tw10min" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">1</AttributeValue> + </Apply> + </VariableDefinition> + <Rule RuleId="urn:com:att:xacml:rule:id:c9a3fb7d-d0b9-48bb-bdca-87eb4957120c" Effect="Deny"> + <Description>DENY - default.</Description> + <Target/> + </Rule> +</Policy> diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_4.xml b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_4.xml new file mode 100644 index 000000000..53e83d9cd --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/frequency_limiter_4.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:att:xacml:policy:id:25e12b06-11d5-4895-b2a2-6f6c594de069" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"> + <Description>Policy for frequency limiter.</Description> + <Target> + <AnyOf> + <AllOf> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">APPC</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="urn:oasis:names:tc:xacml:1.0:actor:actor-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal"> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Restart</AttributeValue> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:operation:operation-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/> + </Match> + </AllOf> + </AnyOf> + </Target> + <Rule RuleId="urn:com:att:xacml:rule:id:e1e8c5c0-e2ba-47d5-9289-6c015305ed21" Effect="Permit"> + <Description>PERMIT - only if number of operations performed in the past is less than the limit.</Description> + <Target/> + <Condition> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or"> + <VariableReference VariableId="isGuardNotActive"/> + <VariableReference VariableId="isHistoryLessOrEqual"/> + </Apply> + </Condition> + </Rule> + <VariableDefinition VariableId="isGuardNotActive"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not"> + <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"> + <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">05:00:00-05:00</AttributeValue> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">23:59:59-05:00</AttributeValue> + </Apply> + </Apply> + </VariableDefinition> + <VariableDefinition VariableId="isHistoryLessOrEqual"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal"> + <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"> + <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="com:att:research:xacml:test:sql:resource:operations:count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="com:att:research:xacml:test:sql:tw10min" MustBePresent="false"/> + </Apply> + <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">1</AttributeValue> + </Apply> + </VariableDefinition> + <Rule RuleId="urn:com:att:xacml:rule:id:c9a3fb7d-d0b9-48bb-bdca-87eb4957120c" Effect="Deny"> + <Description>DENY - default.</Description> + <Target/> + </Rule> +</Policy> diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml.properties b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml.properties new file mode 100644 index 000000000..e51f038e9 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml.properties @@ -0,0 +1,119 @@ +# +# +# This is test set that tests configurable SQL PIP engine. It uses sample data from MySQL world database +# +# http://dev.mysql.com/doc/world-setup/en/index.html +# +# The Policy was created using the PAP Admin Tool. +# +# + +# +# 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. +# + +# Policies to load +# +xacml.rootPolicies=sql +sql.file=src/test/resources/xacml/frequency_limiter_1.xml + +# PIP Engine Definition +# +xacml.pip.engines=sql1 + +sql1.classname=com.att.research.xacml.std.pip.engines.jdbc.JDBCEngine +sql1.name=World +sql1.description=World Database from MySQL website. Copyright Statistics Finland, http://www.stat.fi/worldinfigures. +# This will be the default issuer for the resolvers. NOTE: Issuer only used for attributes provided by the engine. +sql1.issuer=com:att:research:xacml:test:sql +# +# This is the configuration for JDBC. You will have to setup the database and run the data\world*.sql script to +# create the tables and load the data. +# +sql1.type=jdbc + +# Postgres DB +#sql1.jdbc.driver=org.postgresql.Driver +#sql1.jdbc.url=jdbc:postgresql://localhost:7778/postgres +#sql1.jdbc.conn.user=postgres +#sql1.jdbc.conn.password= + +# MariaDB +sql1.jdbc.driver=org.mariadb.jdbc.Driver +sql1.jdbc.url=jdbc:mariadb://localhost:7779/policy +sql1.jdbc.conn.user=root +sql1.jdbc.conn.password=lmpg + +# +# This is the configuration for JNDI datasource. +# +#sql1.type=jndi +#sql1.datasource=jdbc/xacml + +sql1.resolvers=langer + +sql1.resolver.langer.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver +sql1.resolver.langer.name=Language +sql1.resolver.langer.description=This returns the number of previous operations within the given time window + +# Query for Postgres DB +#sql1.resolver.langer.select=select count(*) from operationshistory where actor=? and operation=? and target=? and endtime between now()::timestamp with time zone - (interval '1000000000s') and now()::timestamp with time zone + +# Query for MariaDB +#sql1.resolver.langer.select=select count(*) as count from operationshistory where actor=? and operation=? and target=? and convert_tz(endtime,@@session.time_zone,'-05:00') between date_sub(convert_tz(now(),@@session.time_zone,'-05:00'),interval 100 hour) and convert_tz(now(),@@session.time_zone,'-05:00') +sql1.resolver.langer.select=select count(*) as count from operationshistory9 where actor=? and operation=? and target=? and endtime between date_sub(now(),interval 100 hour) and now() + +sql1.resolver.langer.fields=count +sql1.resolver.langer.field.count.id=com:att:research:xacml:test:sql:resource:operations:count +sql1.resolver.langer.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer +sql1.resolver.langer.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource + + +#You can override the default issuer that is set in the JDBCEngine definition if you want. +#sql1.resolver.langer.field.language.issuer=com:att:research:xacml:test:sql +sql1.resolver.langer.parameters=actor,operation,target + +sql1.resolver.langer.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id +sql1.resolver.langer.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + +sql1.resolver.langer.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id +sql1.resolver.langer.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action + +sql1.resolver.langer.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id +sql1.resolver.langer.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource + +# +# These properties are for an attribute generator to build into requests. +# +xacml.attribute.generator=generate_subjectid + +xacml.attribute.generator.generate_subjectid.file=generate.data +xacml.attribute.generator.generate_subjectid.attributes=city + +xacml.attribute.generator.generate_subjectid.attributes.city.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource +xacml.attribute.generator.generate_subjectid.attributes.city.datatype=http://www.w3.org/2001/XMLSchema#string +xacml.attribute.generator.generate_subjectid.attributes.city.id=urn:oasis:names:tc:xacml:1.0:resource:resource-id +xacml.attribute.generator.generate_subjectid.attributes.city.field=0 + diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml2.properties b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml2.properties new file mode 100644 index 000000000..2d1276b51 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml2.properties @@ -0,0 +1,120 @@ +# +# +# This is test set that tests configurable SQL PIP engine. It uses sample data from MySQL world database +# +# http://dev.mysql.com/doc/world-setup/en/index.html +# +# The Policy was created using the PAP Admin Tool. +# +# + +# +# 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. +# + +# Policies to load +# +xacml.rootPolicies=sql +sql.file=src/test/resources/xacml/frequency_limiter_2.xml + +# PIP Engine Definition +# +xacml.pip.engines=sql1 + +sql1.classname=com.att.research.xacml.std.pip.engines.jdbc.JDBCEngine +sql1.name=World +sql1.description=World Database from MySQL website. Copyright Statistics Finland, http://www.stat.fi/worldinfigures. +# This will be the default issuer for the resolvers. NOTE: Issuer only used for attributes provided by the engine. +sql1.issuer=com:att:research:xacml:test:sql +# +# This is the configuration for JDBC. You will have to setup the database and run the data\world*.sql script to +# create the tables and load the data. +# +sql1.type=jdbc + +# Postgres DB +#sql1.jdbc.driver=org.postgresql.Driver +#sql1.jdbc.url=jdbc:postgresql://localhost:7778/postgres +#sql1.jdbc.conn.user=postgres +#sql1.jdbc.conn.password= + +# MariaDB +sql1.jdbc.driver=org.mariadb.jdbc.Driver +sql1.jdbc.url=jdbc:mariadb://localhost:7779/policy +sql1.jdbc.conn.user=root +sql1.jdbc.conn.password=lmpg + +# +# This is the configuration for JNDI datasource. +# +#sql1.type=jndi +#sql1.datasource=jdbc/xacml + +sql1.resolvers=langer + +sql1.resolver.langer.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver +sql1.resolver.langer.name=Language +sql1.resolver.langer.description=This returns the number of previous operations within the given time window + +# Query for Postgres DB +#sql1.resolver.langer.select=select count(*) from operationshistory where actor=? and operation=? and target=? and endtime between now()::timestamp with time zone - (interval '1000000000s') and now()::timestamp with time zone + +# Query for MariaDB +#sql1.resolver.langer.select=select count(*) as count from operationshistory where actor=? and operation=? and target=? and convert_tz(endtime,@@session.time_zone,'-05:00') between date_sub(convert_tz(now(),@@session.time_zone,'-05:00'),interval 100 hour) and convert_tz(now(),@@session.time_zone,'-05:00') +sql1.resolver.langer.select=select starttime as starttimebag from operationshistory9 where actor=? and operation=? and target=? and endtime between date_sub(now(),interval 100 hour) and now() + +#sql1.resolver.langer.fields=count +sql1.resolver.langer.fields=starttimebag +sql1.resolver.langer.field.starttimebag.id=com:att:research:xacml:test:sql:resource:operations:starttimebag +sql1.resolver.langer.field.starttimebag.datatype=http://www.w3.org/2001/XMLSchema#dateTime +sql1.resolver.langer.field.starttimebag.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource + + +#You can override the default issuer that is set in the JDBCEngine definition if you want. +#sql1.resolver.langer.field.language.issuer=com:att:research:xacml:test:sql +sql1.resolver.langer.parameters=actor,operation,target + +sql1.resolver.langer.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id +sql1.resolver.langer.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + +sql1.resolver.langer.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id +sql1.resolver.langer.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action + +sql1.resolver.langer.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id +sql1.resolver.langer.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.langer.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource + +# +# These properties are for an attribute generator to build into requests. +# +xacml.attribute.generator=generate_subjectid + +xacml.attribute.generator.generate_subjectid.file=generate.data +xacml.attribute.generator.generate_subjectid.attributes=city + +xacml.attribute.generator.generate_subjectid.attributes.city.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource +xacml.attribute.generator.generate_subjectid.attributes.city.datatype=http://www.w3.org/2001/XMLSchema#string +xacml.attribute.generator.generate_subjectid.attributes.city.id=urn:oasis:names:tc:xacml:1.0:resource:resource-id +xacml.attribute.generator.generate_subjectid.attributes.city.field=0 + diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml3.properties b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml3.properties new file mode 100644 index 000000000..a3e6f2f44 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/old/xacml3.properties @@ -0,0 +1,123 @@ +# +# +# This is test set that tests configurable SQL PIP engine. It uses sample data from MySQL world database +# +# http://dev.mysql.com/doc/world-setup/en/index.html +# +# The Policy was created using the PAP Admin Tool. +# +# + +# +# 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. +# + +# Policies to load +# +xacml.rootPolicies=sql +sql.file=src/test/resources/xacml/frequency_limiter_3.xml + +# PIP Engine Definition +# +xacml.pip.engines=sql1 + +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.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=tw10min,tw1h,tw100h + +############################################## +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.tw1h.select=select count(*) as count from operationshistory10 where 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.tw100h.select=select count(*) as count from operationshistory10 where actor=? and operation=? and target=? and endtime between date_sub(now(),interval 100 hour) and now() +sql1.resolver.tw100h.field.count.issuer=com:att:research:xacml:test:sql:tw100h + +sql1.resolver.tw100h.classname=com.att.research.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver +sql1.resolver.tw100h.name=OperationsCount +sql1.resolver.tw100h.description=This returns the number of previous operations within the given time window +sql1.resolver.tw100h.fields=count +sql1.resolver.tw100h.field.count.id=com:att:research:xacml:test:sql:resource:operations:count +sql1.resolver.tw100h.field.count.datatype=http://www.w3.org/2001/XMLSchema#integer +sql1.resolver.tw100h.field.count.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource +sql1.resolver.tw100h.parameters=actor,operation,target +sql1.resolver.tw100h.parameter.actor.id=urn:oasis:names:tc:xacml:1.0:actor:actor-id +sql1.resolver.tw100h.parameter.actor.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.tw100h.parameter.actor.category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject +sql1.resolver.tw100h.parameter.operation.id=urn:oasis:names:tc:xacml:1.0:operation:operation-id +sql1.resolver.tw100h.parameter.operation.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.tw100h.parameter.operation.category=urn:oasis:names:tc:xacml:3.0:attribute-category:action +sql1.resolver.tw100h.parameter.target.id=urn:oasis:names:tc:xacml:1.0:target:target-id +sql1.resolver.tw100h.parameter.target.datatype=http://www.w3.org/2001/XMLSchema#string +sql1.resolver.tw100h.parameter.target.category=urn:oasis:names:tc:xacml:3.0:attribute-category:resource + + diff --git a/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard.properties b/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard.properties new file mode 100644 index 000000000..070258642 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard.properties @@ -0,0 +1,52 @@ +# +# +# 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,p5 +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 + + +# PIP Engine Definition +# +xacml.pip.engines=historydb +historydb.classname=org.onap.policy.guard.PIPEngineGetHistory +historydb.issuer=com:att:research:xacml:guard:historydb + 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 new file mode 100644 index 000000000..0f858da8d --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/xacml/xacml_guard_old.properties @@ -0,0 +1,277 @@ +# +# +# 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_vUSP_1707.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml new file mode 100644 index 000000000..62bf986bd --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_ControlLoop_vUSP_1707.yaml @@ -0,0 +1,68 @@ +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_vUSP_1707_appc_migrate.yaml b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml new file mode 100644 index 000000000..333895b2e --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_migrate.yaml @@ -0,0 +1,24 @@ +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 new file mode 100644 index 000000000..865915f82 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild.yaml @@ -0,0 +1,24 @@ +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 new file mode 100644 index 000000000..6905d733f --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_rebuild_1.yaml @@ -0,0 +1,24 @@ +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 new file mode 100644 index 000000000..b44ff00df --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart.yaml @@ -0,0 +1,24 @@ +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 new file mode 100644 index 000000000..50af17af6 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/resources/yaml/policy_guard_vUSP_1707_appc_restart_blacklist.yaml @@ -0,0 +1,26 @@ +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 |