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.*;
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Properties;
31 import java.util.UUID;
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.kie.api.runtime.KieSession;
37 import org.kie.api.runtime.rule.FactHandle;
38 import org.onap.policy.appclcm.LCMRequest;
39 import org.onap.policy.appclcm.LCMRequestWrapper;
40 import org.onap.policy.appclcm.LCMResponse;
41 import org.onap.policy.appclcm.LCMResponseWrapper;
42 import org.onap.policy.controlloop.ControlLoopEventStatus;
43 import org.onap.policy.controlloop.ControlLoopNotificationType;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.drools.event.comm.TopicEndpoint;
49 import org.onap.policy.drools.event.comm.TopicListener;
50 import org.onap.policy.drools.event.comm.TopicSink;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.properties.PolicyProperties;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public class VCPEControlLoopTest implements TopicListener {
61 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
63 private static List<? extends TopicSink> noopTopics;
65 private KieSession kieSession;
66 private Util.Pair<ControlLoopPolicy, String> pair;
67 private UUID requestID;
70 /* Set environment properties */
77 public static void setUpSimulator() {
78 PolicyEngine.manager.configure(new Properties());
79 assertTrue(PolicyEngine.manager.start());
80 Properties noopSinkProperties = new Properties();
81 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
82 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
83 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
84 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
85 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
86 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
88 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
89 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
93 } catch (Exception e) {
99 public static void tearDownSimulator() {
100 HttpServletServer.factory.destroy();
101 PolicyEngine.manager.shutdown();
105 public void successTest() {
107 * Start the kie session
110 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
111 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
112 "service=ServiceDemo;resource=Res1Demo;type=operational",
114 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
115 } catch (IOException e) {
117 logger.debug("Could not create kieSession");
118 fail("Could not create kieSession");
122 * Allows the PolicyEngine to callback to this object to
123 * notify that there is an event ready to be pulled
126 for (TopicSink sink : noopTopics) {
127 assertTrue(sink.start());
132 * Create a unique requestId
134 requestID = UUID.randomUUID();
137 * Simulate an onset event the policy engine will
138 * receive from DCAE to kick off processing through
141 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
144 kieSession.fireUntilHalt();
147 * The only fact in memory should be Params
149 assertEquals(1, kieSession.getFactCount());
152 * Print what's left in memory
154 dumpFacts(kieSession);
157 * Gracefully shut down the kie session
159 kieSession.dispose();
163 * This method will start a kie session and instantiate
166 * @param droolsTemplate
169 * the yaml file containing the policies
174 * @param policyVersion
175 * version of the policy
176 * @return the kieSession to be used to insert facts
177 * @throws IOException
179 private KieSession startSession(String droolsTemplate,
183 String policyVersion) throws IOException {
186 * Load policies from yaml
188 pair = Util.loadYaml(yamlFile);
190 assertNotNull(pair.a);
191 assertNotNull(pair.a.getControlLoop());
192 assertNotNull(pair.a.getControlLoop().getControlLoopName());
193 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
196 * Construct a kie session
198 final KieSession kieSession = Util.buildContainer(droolsTemplate,
199 pair.a.getControlLoop().getControlLoopName(),
203 URLEncoder.encode(pair.b, "UTF-8"));
206 * Retrieve the Policy Engine
209 logger.debug("============");
210 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
211 logger.debug("============");
218 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
220 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
222 * Pull the object that was sent out to DMAAP and make
223 * sure it is a ControlLoopNoticiation of type active
226 if ("POLICY-CL-MGT".equals(topic)) {
227 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
229 else if ("APPC-LCM-READ".equals(topic))
230 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
232 if (obj instanceof VirtualControlLoopNotification) {
233 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
234 String policyName = notification.policyName;
235 if (policyName.endsWith("EVENT")) {
236 logger.debug("Rule Fired: " + notification.policyName);
237 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
239 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
240 logger.debug("Rule Fired: " + notification.policyName);
241 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
242 assertNotNull(notification.message);
243 assertTrue(notification.message.startsWith("Sending guard query"));
245 else if (policyName.endsWith("GUARD.RESPONSE")) {
246 logger.debug("Rule Fired: " + notification.policyName);
247 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
248 assertNotNull(notification.message);
249 assertTrue(notification.message.toLowerCase().endsWith("permit"));
251 else if (policyName.endsWith("GUARD_PERMITTED")) {
252 logger.debug("Rule Fired: " + notification.policyName);
253 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
254 assertNotNull(notification.message);
255 assertTrue(notification.message.startsWith("actor=APPC"));
257 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
258 logger.debug("Rule Fired: " + notification.policyName);
260 logger.debug("The operation timed out");
261 fail("Operation Timed Out");
263 else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
264 logger.debug("Rule Fired: " + notification.policyName);
265 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
266 assertNotNull(notification.message);
267 assertTrue(notification.message.startsWith("actor=APPC"));
268 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
270 else if (policyName.endsWith("EVENT.MANAGER")) {
271 logger.debug("Rule Fired: " + notification.policyName);
272 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
275 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
276 logger.debug("Rule Fired: " + notification.policyName);
278 logger.debug("The control loop timed out");
279 fail("Control Loop Timed Out");
282 else if (obj instanceof LCMRequestWrapper) {
284 * The request should be of type LCMRequestWrapper
285 * and the subrequestid should be 1
287 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
288 LCMRequest appcRequest = dmaapRequest.getBody();
289 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
291 logger.debug("\n============ APPC received the request!!! ===========\n");
294 * Simulate a success response from APPC and insert
295 * the response into the working memory
297 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
298 LCMResponse appcResponse = new LCMResponse(appcRequest);
299 appcResponse.getStatus().setCode(400);
300 appcResponse.getStatus().setMessage("AppC success");
301 dmaapResponse.setBody(appcResponse);
302 kieSession.insert(dmaapResponse);
307 * This method is used to simulate event messages from DCAE
308 * that start the control loop (onset message) or end the
309 * control loop (abatement message).
311 * @param policy the controlLoopName comes from the policy
312 * @param requestID the requestId for this event
313 * @param status could be onset or abated
315 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
316 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
317 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
318 event.requestID = requestID;
319 event.target = "generic-vnf.vnf-id";
320 event.closedLoopAlarmStart = Instant.now();
321 event.AAI = new HashMap<>();
322 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
323 event.closedLoopEventStatus = status;
324 kieSession.insert(event);
328 * This method will dump all the facts in the working memory.
330 * @param kieSession the session containing the facts
332 public void dumpFacts(KieSession kieSession) {
333 logger.debug("Fact Count: {}", kieSession.getFactCount());
334 for (FactHandle handle : kieSession.getFactHandles()) {
335 logger.debug("FACT: {}", handle);