2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Properties;
34 import java.util.UUID;
36 import org.junit.AfterClass;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.kie.api.runtime.KieSession;
40 import org.kie.api.runtime.rule.FactHandle;
41 import org.onap.policy.appc.Request;
42 import org.onap.policy.appc.Response;
43 import org.onap.policy.appc.ResponseCode;
44 import org.onap.policy.controlloop.ControlLoopEventStatus;
45 import org.onap.policy.controlloop.ControlLoopNotificationType;
46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
47 import org.onap.policy.controlloop.VirtualControlLoopNotification;
48 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
49 import org.onap.policy.drools.event.comm.TopicEndpoint;
50 import org.onap.policy.drools.event.comm.TopicListener;
51 import org.onap.policy.drools.event.comm.TopicSink;
52 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
53 import org.onap.policy.drools.http.server.HttpServletServer;
54 import org.onap.policy.drools.properties.PolicyProperties;
55 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.system.PolicyEngine;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public class VFWControlLoopTest implements TopicListener {
63 private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
65 private static List<? extends TopicSink> noopTopics;
67 private KieSession kieSession;
68 private Util.Pair<ControlLoopPolicy, String> pair;
69 private UUID requestID;
72 /* Set environment properties */
79 public static void setUpSimulator() {
80 PolicyEngine.manager.configure(new Properties());
81 assertTrue(PolicyEngine.manager.start());
82 Properties noopSinkProperties = new Properties();
83 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
84 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
85 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", "org.onap.policy.appc.util.Serialization,gsonPretty");
86 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
87 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
88 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
90 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
91 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111);
96 } catch (Exception e) {
102 public static void tearDownSimulator() {
103 HttpServletServer.factory.destroy();
104 PolicyEngine.manager.shutdown();
108 public void successTest() {
111 * Start the kie session
114 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
115 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
116 "service=ServiceDemo;resource=Res1Demo;type=operational",
118 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
119 } catch (IOException e) {
121 logger.debug("Could not create kieSession");
122 fail("Could not create kieSession");
126 * Allows the PolicyEngine to callback to this object to
127 * notify that there is an event ready to be pulled
130 for (TopicSink sink : noopTopics) {
131 assertTrue(sink.start());
136 * Create a unique requestId
138 requestID = UUID.randomUUID();
141 * Simulate an onset event the policy engine will
142 * receive from DCAE to kick off processing through
145 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
148 kieSession.fireUntilHalt();
150 catch (Exception e) {
152 logger.warn(e.toString());
158 * The only fact in memory should be Params
160 assertEquals(1, kieSession.getFactCount());
163 * Print what's left in memory
165 dumpFacts(kieSession);
168 * Gracefully shut down the kie session
170 kieSession.dispose();
174 * This method will start a kie session and instantiate
177 * @param droolsTemplate
180 * the yaml file containing the policies
185 * @param policyVersion
186 * version of the policy
187 * @return the kieSession to be used to insert facts
188 * @throws IOException
190 private KieSession startSession(String droolsTemplate,
194 String policyVersion) throws IOException {
197 * Load policies from yaml
199 pair = Util.loadYaml(yamlFile);
201 assertNotNull(pair.a);
202 assertNotNull(pair.a.getControlLoop());
203 assertNotNull(pair.a.getControlLoop().getControlLoopName());
204 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
207 * Construct a kie session
209 final KieSession kieSession = Util.buildContainer(droolsTemplate,
210 pair.a.getControlLoop().getControlLoopName(),
214 URLEncoder.encode(pair.b, "UTF-8"));
217 * Retrieve the Policy Engine
220 logger.debug("============");
221 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
222 logger.debug("============");
228 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
230 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
232 * Pull the object that was sent out to DMAAP and make
233 * sure it is a ControlLoopNoticiation of type active
236 if ("POLICY-CL-MGT".equals(topic)) {
237 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
239 else if ("APPC-CL".equals(topic))
240 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
242 if (obj instanceof VirtualControlLoopNotification) {
243 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
244 String policyName = notification.policyName;
245 if (policyName.endsWith("EVENT")) {
246 logger.debug("Rule Fired: " + notification.policyName);
247 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
249 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
250 logger.debug("Rule Fired: " + notification.policyName);
251 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
252 assertNotNull(notification.message);
253 assertTrue(notification.message.startsWith("Sending guard query"));
255 else if (policyName.endsWith("GUARD.RESPONSE")) {
256 logger.debug("Rule Fired: " + notification.policyName);
257 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
258 assertNotNull(notification.message);
259 assertTrue(notification.message.toLowerCase().endsWith("permit"));
261 else if (policyName.endsWith("GUARD_PERMITTED")) {
262 logger.debug("Rule Fired: " + notification.policyName);
263 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
264 assertNotNull(notification.message);
265 assertTrue(notification.message.startsWith("actor=APPC"));
267 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
268 logger.debug("Rule Fired: " + notification.policyName);
270 logger.debug("The operation timed out");
271 fail("Operation Timed Out");
273 else if (policyName.endsWith("APPC.RESPONSE")) {
274 logger.debug("Rule Fired: " + notification.policyName);
275 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
276 assertNotNull(notification.message);
277 assertTrue(notification.message.startsWith("actor=APPC"));
278 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
280 else if (policyName.endsWith("EVENT.MANAGER")) {
281 logger.debug("Rule Fired: " + notification.policyName);
282 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
285 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
286 logger.debug("Rule Fired: " + notification.policyName);
288 logger.debug("The control loop timed out");
289 fail("Control Loop Timed Out");
292 else if (obj instanceof Request) {
293 assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
295 logger.debug("\n============ APPC received the request!!! ===========\n");
298 * Simulate a success response from APPC and insert
299 * the response into the working memory
301 Response appcResponse = new Response((Request)obj);
302 appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
303 appcResponse.getStatus().Value = "SUCCESS";
304 kieSession.insert(appcResponse);
309 * This method is used to simulate event messages from DCAE
310 * that start the control loop (onset message) or end the
311 * control loop (abatement message).
313 * @param policy the controlLoopName comes from the policy
314 * @param requestID the requestId for this event
315 * @param status could be onset or abated
317 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
318 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
319 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
320 event.requestID = requestID;
321 event.target = "generic-vnf.vnf-id";
322 event.closedLoopAlarmStart = Instant.now();
323 event.AAI = new HashMap<>();
324 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
325 event.closedLoopEventStatus = status;
326 kieSession.insert(event);
330 * This method will dump all the facts in the working memory.
332 * @param kieSession the session containing the facts
334 public void dumpFacts(KieSession kieSession) {
335 logger.debug("Fact Count: {}", kieSession.getFactCount());
336 for (FactHandle handle : kieSession.getFactHandles()) {
337 logger.debug("FACT: {}", handle);