2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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;
35 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.appclcm.LcmRequest;
41 import org.onap.policy.appclcm.LcmRequestWrapper;
42 import org.onap.policy.appclcm.LcmResponse;
43 import org.onap.policy.appclcm.LcmResponseWrapper;
44 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
45 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
46 import org.onap.policy.common.endpoints.event.comm.TopicListener;
47 import org.onap.policy.common.endpoints.event.comm.TopicSink;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
50 import org.onap.policy.controlloop.ControlLoopEventStatus;
51 import org.onap.policy.controlloop.ControlLoopNotificationType;
52 import org.onap.policy.controlloop.VirtualControlLoopEvent;
53 import org.onap.policy.controlloop.VirtualControlLoopNotification;
54 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
55 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
56 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
57 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
58 import org.onap.policy.drools.system.PolicyController;
59 import org.onap.policy.drools.system.PolicyEngine;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class ControlLoopFailureTest implements TopicListener {
65 private static final Logger logger = LoggerFactory.getLogger(ControlLoopFailureTest.class);
67 private static List<? extends TopicSink> noopTopics;
69 private static KieSession kieSession;
70 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
71 private UUID requestId;
72 private UUID requestId2;
73 private UUID requestId3;
74 private int eventCount;
77 /* Set environment properties */
78 SupportUtil.setAaiProps();
79 SupportUtil.setGuardProps();
80 SupportUtil.setPuProp();
87 public static void setUpSimulator() {
88 PolicyEngine.manager.configure(new Properties());
89 assertTrue(PolicyEngine.manager.start());
90 Properties noopSinkProperties = new Properties();
91 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
92 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
93 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
94 "org.onap.policy.appclcm.util.Serialization,gson");
95 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
96 "org.onap.policy.controlloop.VirtualControlLoopNotification");
97 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
98 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
99 noopTopics = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
101 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
102 .groupId("junit.groupId")
103 .artifactId("junit.artifactId")
104 .topic("POLICY-CL-MGT")
105 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
106 .protocolFilter(new JsonProtocolFilter())
107 .modelClassLoaderHash(1111));
108 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
109 .groupId("junit.groupId")
110 .artifactId("junit.artifactId")
111 .topic("APPC-LCM-READ")
112 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
113 .protocolFilter(new JsonProtocolFilter())
114 .modelClassLoaderHash(1111));
116 SupportUtil.buildAaiSim();
117 SupportUtil.buildGuardSim();
118 } catch (Exception e) {
119 fail(e.getMessage());
123 * Start the kie session
126 kieSession = startSession(
127 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
128 + "/src/main/resources/__closedLoopControlName__.drl",
129 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
130 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
131 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
132 } catch (IOException e) {
134 logger.debug("Could not create kieSession");
135 fail("Could not create kieSession");
140 * Tear down simulator.
143 public static void tearDownSimulator() {
145 * Gracefully shut down the kie session
147 kieSession.dispose();
149 PolicyEngine.manager.stop();
150 HttpServletServerFactoryInstance.getServerFactory().destroy();
151 PolicyController.factory.shutdown();
152 TopicEndpointManager.getManager().shutdown();
156 * This test case tests the scenario where 3 events occur and 2 of the requests refer to the
157 * same target entity while the 3rd is for another entity. The expected result is that the event
158 * with the duplicate target entity will have a final success result for one of the events, and
159 * a rejected message for the one that was unable to obtain the lock. The event that is
160 * referring to a different target entity should be able to obtain a lock since it is a
161 * different target. After processing of all events there should only be the params object left
165 public void targetLockedTest() {
168 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
169 * to be pulled from the queue
171 for (TopicSink sink : noopTopics) {
172 assertTrue(sink.start());
177 * Create a unique requestId
179 requestId = UUID.randomUUID();
182 * This will be a unique request for another target entity
184 requestId2 = UUID.randomUUID();
187 * This will be a request duplicating the target entity of the first request
189 requestId3 = UUID.randomUUID();
192 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
195 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01");
198 * Send a second event requesting an action for a different target entity
200 sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
203 * Send a second event for a different target to ensure there are no problems with obtaining
204 * a lock for a different
206 kieSession.fireUntilHalt();
208 // allow object clean-up
209 kieSession.fireAllRules();
212 * The only fact in memory should be Params
214 assertEquals(1, kieSession.getFactCount());
217 * Print what's left in memory
219 dumpFacts(kieSession);
224 * This method will start a kie session and instantiate the Policy Engine.
226 * @param droolsTemplate the DRL rules file
227 * @param yamlFile the yaml file containing the policies
228 * @param policyScope scope for policy
229 * @param policyName name of the policy
230 * @param policyVersion version of the policy
231 * @return the kieSession to be used to insert facts
232 * @throws IOException throws IO exception
234 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
235 String policyName, String policyVersion) throws IOException {
238 * Load policies from yaml
240 pair = SupportUtil.loadYaml(yamlFile);
242 assertNotNull(pair.first);
243 assertNotNull(pair.first.getControlLoop());
244 assertNotNull(pair.first.getControlLoop().getControlLoopName());
245 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
248 * Construct a kie session
250 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
251 pair.first.getControlLoop().getControlLoopName(),
252 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
255 * Retrieve the Policy Engine
258 logger.debug("============");
259 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
260 logger.debug("============");
268 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
271 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
273 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
277 if ("POLICY-CL-MGT".equals(topic)) {
278 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
279 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
280 } else if ("APPC-LCM-READ".equals(topic)) {
281 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
282 org.onap.policy.appclcm.LcmRequestWrapper.class);
285 if (obj instanceof VirtualControlLoopNotification) {
286 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
287 String policyName = notification.getPolicyName();
288 if (policyName.endsWith("EVENT")) {
289 logger.debug("Rule Fired: " + notification.getPolicyName());
290 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
291 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
292 logger.debug("Rule Fired: " + notification.getPolicyName());
293 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
294 assertNotNull(notification.getMessage());
295 assertTrue(notification.getMessage().startsWith("Sending guard query"));
296 } else if (policyName.endsWith("GUARD.RESPONSE")) {
297 logger.debug("Rule Fired: " + notification.getPolicyName());
298 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299 assertNotNull(notification.getMessage());
300 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
301 } else if (policyName.endsWith("GUARD_PERMITTED")) {
302 logger.debug("Rule Fired: " + notification.getPolicyName());
303 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
304 assertNotNull(notification.getMessage());
305 assertTrue(notification.getMessage().startsWith("actor=APPC"));
306 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
307 logger.debug("Rule Fired: " + notification.getPolicyName());
309 logger.debug("The operation timed out");
310 fail("Operation Timed Out");
311 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
312 logger.debug("Rule Fired: " + notification.getPolicyName());
313 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
314 assertNotNull(notification.getMessage());
315 assertTrue(notification.getMessage().startsWith("actor=APPC"));
316 if (requestId.equals(notification.getRequestId())) {
317 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED, "vnf01");
318 } else if (requestId2.equals(notification.getRequestId())) {
319 sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
321 } else if (policyName.endsWith("EVENT.MANAGER")) {
322 logger.debug("Rule Fired: " + notification.getPolicyName());
323 if (requestId3.equals(notification.getRequestId())) {
325 * The event with the duplicate target should be rejected
327 assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.getNotification()));
329 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
331 if (++eventCount == 3) {
334 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
335 logger.debug("Rule Fired: " + notification.getPolicyName());
337 logger.debug("The control loop timed out");
338 fail("Control Loop Timed Out");
340 } else if (obj instanceof LcmRequestWrapper) {
342 * The request should be of type LCMRequestWrapper and the subrequestid should be 1
344 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
345 LcmRequest appcRequest = dmaapRequest.getBody();
346 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
348 logger.debug("\n============ APPC received the request!!! ===========\n");
351 * Simulate a success response from APPC and insert the response into the working memory
353 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
354 LcmResponse appcResponse = new LcmResponse(appcRequest);
355 appcResponse.getStatus().setCode(400);
356 appcResponse.getStatus().setMessage("AppC success");
357 dmaapResponse.setBody(appcResponse);
360 * Interrupting with a different request for the same target entity to check if lock
363 if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
364 sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
366 kieSession.insert(dmaapResponse);
371 * This method is used to simulate event messages from DCAE that start the control loop (onset
372 * message) or end the control loop (abatement message).
374 * @param policy the controlLoopName comes from the policy
375 * @param requestId the requestId for this event
376 * @param status could be onset or abated
377 * @param target the target entity to take an action on
379 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) {
380 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
382 event.setRequestId(requestId);
383 event.setTarget("generic-vnf.vnf-id");
384 event.setClosedLoopAlarmStart(Instant.now());
385 event.setAai(new HashMap<>());
386 event.getAai().put("generic-vnf.vnf-id", target);
387 event.setClosedLoopEventStatus(status);
388 kieSession.insert(event);
392 * This method will dump all the facts in the working memory.
394 * @param kieSession the session containing the facts
396 public void dumpFacts(KieSession kieSession) {
397 logger.debug("Fact Count: {}", kieSession.getFactCount());
398 for (FactHandle handle : kieSession.getFactHandles()) {
399 logger.debug("FACT: {}", handle);