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.ControlLoopTargetType;
45 import org.onap.policy.controlloop.VirtualControlLoopEvent;
46 import org.onap.policy.controlloop.VirtualControlLoopNotification;
47 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
48 import org.onap.policy.controlloop.policy.TargetType;
49 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
50 import org.onap.policy.drools.event.comm.TopicEndpoint;
51 import org.onap.policy.drools.event.comm.TopicListener;
52 import org.onap.policy.drools.event.comm.TopicSink;
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.PolicyController;
58 import org.onap.policy.drools.system.PolicyEngine;
59 import org.onap.policy.drools.utils.LoggerUtil;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class VCPEControlLoopTest implements TopicListener {
65 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
67 private static List<? extends TopicSink> noopTopics;
69 private static KieSession kieSession;
70 private static Util.Pair<ControlLoopPolicy, String> pair;
71 private UUID requestID;
74 /* Set environment properties */
78 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
82 public static void setUpSimulator() {
83 PolicyEngine.manager.configure(new Properties());
84 assertTrue(PolicyEngine.manager.start());
85 Properties noopSinkProperties = new Properties();
86 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
87 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
88 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
89 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
90 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
91 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
93 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
94 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
98 } catch (Exception e) {
102 * Start the kie session
105 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
106 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
107 "service=ServiceDemo;resource=Res1Demo;type=operational",
109 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
110 } catch (IOException e) {
112 logger.debug("Could not create kieSession");
113 fail("Could not create kieSession");
118 public static void tearDownSimulator() {
120 * Gracefully shut down the kie session
122 kieSession.dispose();
124 PolicyEngine.manager.stop();
125 HttpServletServer.factory.destroy();
126 PolicyController.factory.shutdown();
127 TopicEndpoint.manager.shutdown();
131 public void successTest() {
134 * Allows the PolicyEngine to callback to this object to
135 * notify that there is an event ready to be pulled
138 for (TopicSink sink : noopTopics) {
139 assertTrue(sink.start());
144 * Create a unique requestId
146 requestID = UUID.randomUUID();
149 * Simulate an onset event the policy engine will
150 * receive from DCAE to kick off processing through
153 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
155 kieSession.fireUntilHalt();
158 * The only fact in memory should be Params
160 assertEquals(1, kieSession.getFactCount());
163 * Print what's left in memory
165 dumpFacts(kieSession);
169 public void aaiGetFailTest() {
172 * Allows the PolicyEngine to callback to this object to
173 * notify that there is an event ready to be pulled
176 for (TopicSink sink : noopTopics) {
177 assertTrue(sink.start());
182 * Create a unique requestId
184 requestID = UUID.randomUUID();
187 * Simulate an onset event the policy engine will
188 * receive from DCAE to kick off processing through
191 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false);
194 kieSession.fireUntilHalt();
197 * The only fact in memory should be Params
199 assertEquals(1, kieSession.getFactCount());
202 * Print what's left in memory
204 dumpFacts(kieSession);
209 * This method will start a kie session and instantiate
212 * @param droolsTemplate
215 * the yaml file containing the policies
220 * @param policyVersion
221 * version of the policy
222 * @return the kieSession to be used to insert facts
223 * @throws IOException
225 private static KieSession startSession(String droolsTemplate,
229 String policyVersion) throws IOException {
232 * Load policies from yaml
234 pair = Util.loadYaml(yamlFile);
236 assertNotNull(pair.a);
237 assertNotNull(pair.a.getControlLoop());
238 assertNotNull(pair.a.getControlLoop().getControlLoopName());
239 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
242 * Construct a kie session
244 final KieSession kieSession = Util.buildContainer(droolsTemplate,
245 pair.a.getControlLoop().getControlLoopName(),
249 URLEncoder.encode(pair.b, "UTF-8"));
252 * Retrieve the Policy Engine
255 logger.debug("============");
256 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
257 logger.debug("============");
264 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
266 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
268 * Pull the object that was sent out to DMAAP and make
269 * sure it is a ControlLoopNoticiation of type active
272 if ("POLICY-CL-MGT".equals(topic)) {
273 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
275 else if ("APPC-LCM-READ".equals(topic))
276 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
278 if (obj instanceof VirtualControlLoopNotification) {
279 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
280 String policyName = notification.policyName;
281 if (policyName.endsWith("EVENT")) {
282 logger.debug("Rule Fired: " + notification.policyName);
283 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
285 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
286 logger.debug("Rule Fired: " + notification.policyName);
287 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
288 assertNotNull(notification.message);
289 assertTrue(notification.message.startsWith("Sending guard query"));
291 else if (policyName.endsWith("GUARD.RESPONSE")) {
292 logger.debug("Rule Fired: " + notification.policyName);
293 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
294 assertNotNull(notification.message);
295 assertTrue(notification.message.toLowerCase().endsWith("permit"));
297 else if (policyName.endsWith("GUARD_PERMITTED")) {
298 logger.debug("Rule Fired: " + notification.policyName);
299 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
300 assertNotNull(notification.message);
301 assertTrue(notification.message.startsWith("actor=APPC"));
303 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
304 logger.debug("Rule Fired: " + notification.policyName);
306 logger.debug("The operation timed out");
307 fail("Operation Timed Out");
309 else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
310 logger.debug("Rule Fired: " + notification.policyName);
311 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
312 assertNotNull(notification.message);
313 assertTrue(notification.message.startsWith("actor=APPC"));
314 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
316 else if (policyName.endsWith("EVENT.MANAGER")) {
317 logger.debug("Rule Fired: " + notification.policyName);
318 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
319 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
323 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.notification);
327 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
328 logger.debug("Rule Fired: " + notification.policyName);
330 logger.debug("The control loop timed out");
331 fail("Control Loop Timed Out");
334 else if (obj instanceof LCMRequestWrapper) {
336 * The request should be of type LCMRequestWrapper
337 * and the subrequestid should be 1
339 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
340 LCMRequest appcRequest = dmaapRequest.getBody();
341 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
342 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
344 logger.debug("\n============ APPC received the request!!! ===========\n");
347 * Simulate a success response from APPC and insert
348 * the response into the working memory
350 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
351 LCMResponse appcResponse = new LCMResponse(appcRequest);
352 appcResponse.getStatus().setCode(400);
353 appcResponse.getStatus().setMessage("AppC success");
354 dmaapResponse.setBody(appcResponse);
355 kieSession.insert(dmaapResponse);
360 * This method is used to simulate event messages from DCAE
361 * that start the control loop (onset message) or end the
362 * control loop (abatement message).
364 * @param policy the controlLoopName comes from the policy
365 * @param requestID the requestId for this event
366 * @param status could be onset or abated
368 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
369 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
370 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
371 event.requestID = requestID;
372 event.target = "generic-vnf.vnf-name";
373 event.closedLoopAlarmStart = Instant.now();
374 event.AAI = new HashMap<>();
375 event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName");
376 event.closedLoopEventStatus = status;
377 kieSession.insert(event);
380 protected void sendEvent(ControlLoopPolicy policy, UUID requestID,
381 ControlLoopEventStatus status, String vnfName, boolean isEnriched) {
382 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
383 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
384 event.requestID = requestID;
385 event.target = "generic-vnf.vnf-name";
386 event.target_type = ControlLoopTargetType.VNF;
387 event.closedLoopAlarmStart = Instant.now();
388 event.AAI = new HashMap<>();
389 event.AAI.put("generic-vnf.vnf-name", vnfName);
391 event.AAI.put("generic-vnf.in-maint", "false");
392 event.AAI.put("generic-vnf.is-closed-loop-disabled", "false");
393 event.AAI.put("generic-vnf.orchestration-status", "Created");
394 event.AAI.put("generic-vnf.prov-status", "PREPROV");
395 event.AAI.put("generic-vnf.resource-version", "1");
396 event.AAI.put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
397 event.AAI.put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
398 event.AAI.put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
400 event.closedLoopEventStatus = status;
401 kieSession.insert(event);
405 * This method will dump all the facts in the working memory.
407 * @param kieSession the session containing the facts
409 public void dumpFacts(KieSession kieSession) {
410 logger.debug("Fact Count: {}", kieSession.getFactCount());
411 for (FactHandle handle : kieSession.getFactHandles()) {
412 logger.debug("FACT: {}", handle);