2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.appclcm.LcmRequest;
42 import org.onap.policy.appclcm.LcmRequestWrapper;
43 import org.onap.policy.appclcm.LcmResponse;
44 import org.onap.policy.appclcm.LcmResponseWrapper;
45 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
46 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
47 import org.onap.policy.common.endpoints.event.comm.TopicListener;
48 import org.onap.policy.common.endpoints.event.comm.TopicSink;
49 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
50 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
51 import org.onap.policy.controlloop.ControlLoopEventStatus;
52 import org.onap.policy.controlloop.ControlLoopNotificationType;
53 import org.onap.policy.controlloop.VirtualControlLoopEvent;
54 import org.onap.policy.controlloop.VirtualControlLoopNotification;
55 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
56 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
57 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
58 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
59 import org.onap.policy.drools.system.PolicyController;
60 import org.onap.policy.drools.system.PolicyEngine;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class ControlLoopFailureTest implements TopicListener {
66 private static final Logger logger = LoggerFactory.getLogger(ControlLoopFailureTest.class);
68 private static List<? extends TopicSink> noopTopics;
70 private static KieSession kieSession;
71 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
72 private UUID requestId;
73 private UUID requestId2;
74 private UUID requestId3;
75 private int eventCount;
78 /* Set environment properties */
79 SupportUtil.setAaiProps();
80 SupportUtil.setGuardProps();
81 SupportUtil.setPuProp();
88 public static void setUpSimulator() {
89 PolicyEngine.manager.configure(new Properties());
90 assertTrue(PolicyEngine.manager.start());
91 Properties noopSinkProperties = new Properties();
92 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
93 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
94 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
95 "org.onap.policy.appclcm.util.Serialization,gson");
96 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
97 "org.onap.policy.controlloop.VirtualControlLoopNotification");
98 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
99 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
100 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
102 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
103 .groupId("junit.groupId")
104 .artifactId("junit.artifactId")
105 .topic("POLICY-CL-MGT")
106 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
107 .protocolFilter(new JsonProtocolFilter())
108 .customGsonCoder(null)
109 .customJacksonCoder(null)
110 .modelClassLoaderHash(1111));
111 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
112 .groupId("junit.groupId")
113 .artifactId("junit.artifactId")
114 .topic("APPC-LCM-READ")
115 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
116 .protocolFilter(new JsonProtocolFilter())
117 .customGsonCoder(null)
118 .customJacksonCoder(null)
119 .modelClassLoaderHash(1111));
121 SupportUtil.buildAaiSim();
122 SupportUtil.buildGuardSim();
123 } catch (Exception e) {
124 fail(e.getMessage());
128 * Start the kie session
131 kieSession = startSession(
132 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
133 + "/src/main/resources/__closedLoopControlName__.drl",
134 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
135 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
136 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
137 } catch (IOException e) {
139 logger.debug("Could not create kieSession");
140 fail("Could not create kieSession");
145 * Tear down simulator.
148 public static void tearDownSimulator() {
150 * Gracefully shut down the kie session
152 kieSession.dispose();
154 PolicyEngine.manager.stop();
155 HttpServletServer.factory.destroy();
156 PolicyController.factory.shutdown();
157 TopicEndpoint.manager.shutdown();
161 * This test case tests the scenario where 3 events occur and 2 of the requests refer to the
162 * same target entity while the 3rd is for another entity. The expected result is that the event
163 * with the duplicate target entity will have a final success result for one of the events, and
164 * a rejected message for the one that was unable to obtain the lock. The event that is
165 * referring to a different target entity should be able to obtain a lock since it is a
166 * different target. After processing of all events there should only be the params object left
170 public void targetLockedTest() {
173 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
174 * to be pulled from the queue
176 for (TopicSink sink : noopTopics) {
177 assertTrue(sink.start());
182 * Create a unique requestId
184 requestId = UUID.randomUUID();
187 * This will be a unique request for another target entity
189 requestId2 = UUID.randomUUID();
192 * This will be a request duplicating the target entity of the first request
194 requestId3 = UUID.randomUUID();
197 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
200 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01");
203 * Send a second event requesting an action for a different target entity
205 sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
208 * Send a second event for a different target to ensure there are no problems with obtaining
209 * a lock for a different
211 kieSession.fireUntilHalt();
213 // allow object clean-up
214 kieSession.fireAllRules();
217 * The only fact in memory should be Params
219 assertEquals(1, kieSession.getFactCount());
222 * Print what's left in memory
224 dumpFacts(kieSession);
229 * This method will start a kie session and instantiate the Policy Engine.
231 * @param droolsTemplate the DRL rules file
232 * @param yamlFile the yaml file containing the policies
233 * @param policyScope scope for policy
234 * @param policyName name of the policy
235 * @param policyVersion version of the policy
236 * @return the kieSession to be used to insert facts
237 * @throws IOException throws IO exception
239 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
240 String policyName, String policyVersion) throws IOException {
243 * Load policies from yaml
245 pair = SupportUtil.loadYaml(yamlFile);
247 assertNotNull(pair.first);
248 assertNotNull(pair.first.getControlLoop());
249 assertNotNull(pair.first.getControlLoop().getControlLoopName());
250 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
253 * Construct a kie session
255 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
256 pair.first.getControlLoop().getControlLoopName(),
257 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
260 * Retrieve the Policy Engine
263 logger.debug("============");
264 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
265 logger.debug("============");
273 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
276 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
278 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
282 if ("POLICY-CL-MGT".equals(topic)) {
283 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
284 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
285 } else if ("APPC-LCM-READ".equals(topic)) {
286 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
287 org.onap.policy.appclcm.LcmRequestWrapper.class);
290 if (obj instanceof VirtualControlLoopNotification) {
291 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
292 String policyName = notification.getPolicyName();
293 if (policyName.endsWith("EVENT")) {
294 logger.debug("Rule Fired: " + notification.getPolicyName());
295 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
296 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
297 logger.debug("Rule Fired: " + notification.getPolicyName());
298 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299 assertNotNull(notification.getMessage());
300 assertTrue(notification.getMessage().startsWith("Sending guard query"));
301 } else if (policyName.endsWith("GUARD.RESPONSE")) {
302 logger.debug("Rule Fired: " + notification.getPolicyName());
303 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
304 assertNotNull(notification.getMessage());
305 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
306 } else if (policyName.endsWith("GUARD_PERMITTED")) {
307 logger.debug("Rule Fired: " + notification.getPolicyName());
308 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
309 assertNotNull(notification.getMessage());
310 assertTrue(notification.getMessage().startsWith("actor=APPC"));
311 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
312 logger.debug("Rule Fired: " + notification.getPolicyName());
314 logger.debug("The operation timed out");
315 fail("Operation Timed Out");
316 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
317 logger.debug("Rule Fired: " + notification.getPolicyName());
318 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
319 assertNotNull(notification.getMessage());
320 assertTrue(notification.getMessage().startsWith("actor=APPC"));
321 if (requestId.equals(notification.getRequestId())) {
322 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED, "vnf01");
323 } else if (requestId2.equals(notification.getRequestId())) {
324 sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
326 } else if (policyName.endsWith("EVENT.MANAGER")) {
327 logger.debug("Rule Fired: " + notification.getPolicyName());
328 if (requestId3.equals(notification.getRequestId())) {
330 * The event with the duplicate target should be rejected
332 assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.getNotification()));
334 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
336 if (++eventCount == 3) {
339 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
340 logger.debug("Rule Fired: " + notification.getPolicyName());
342 logger.debug("The control loop timed out");
343 fail("Control Loop Timed Out");
345 } else if (obj instanceof LcmRequestWrapper) {
347 * The request should be of type LCMRequestWrapper and the subrequestid should be 1
349 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
350 LcmRequest appcRequest = dmaapRequest.getBody();
351 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
353 logger.debug("\n============ APPC received the request!!! ===========\n");
356 * Simulate a success response from APPC and insert the response into the working memory
358 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
359 LcmResponse appcResponse = new LcmResponse(appcRequest);
360 appcResponse.getStatus().setCode(400);
361 appcResponse.getStatus().setMessage("AppC success");
362 dmaapResponse.setBody(appcResponse);
365 * Interrupting with a different request for the same target entity to check if lock
368 if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
369 sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
371 kieSession.insert(dmaapResponse);
376 * This method is used to simulate event messages from DCAE that start the control loop (onset
377 * message) or end the control loop (abatement message).
379 * @param policy the controlLoopName comes from the policy
380 * @param requestId the requestId for this event
381 * @param status could be onset or abated
382 * @param target the target entity to take an action on
384 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) {
385 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
386 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
387 event.setRequestId(requestId);
388 event.setTarget("generic-vnf.vnf-id");
389 event.setClosedLoopAlarmStart(Instant.now());
390 event.setAai(new HashMap<>());
391 event.getAai().put("generic-vnf.vnf-id", target);
392 event.setClosedLoopEventStatus(status);
393 kieSession.insert(event);
397 * This method will dump all the facts in the working memory.
399 * @param kieSession the session containing the facts
401 public void dumpFacts(KieSession kieSession) {
402 logger.debug("Fact Count: {}", kieSession.getFactCount());
403 for (FactHandle handle : kieSession.getFactHandles()) {
404 logger.debug("FACT: {}", handle);