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.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(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;
72 private UUID requestId2;
73 private UUID requestId3;
74 private int eventCount;
77 /* Set environment properties */
84 public static void setUpSimulator() {
85 PolicyEngine.manager.configure(new Properties());
86 assertTrue(PolicyEngine.manager.start());
87 Properties noopSinkProperties = new Properties();
88 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
89 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
90 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
91 "org.onap.policy.appclcm.util.Serialization,gson");
92 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
93 "org.onap.policy.controlloop.VirtualControlLoopNotification");
94 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
95 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
96 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
98 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
99 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
101 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
102 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
105 Util.buildGuardSim();
106 } catch (Exception e) {
107 fail(e.getMessage());
111 * Start the kie session
114 kieSession = startSession(
115 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
116 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
117 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
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");
127 public static void tearDownSimulator() {
129 * Gracefully shut down the kie session
131 kieSession.dispose();
133 PolicyEngine.manager.stop();
134 HttpServletServer.factory.destroy();
135 PolicyController.factory.shutdown();
136 TopicEndpoint.manager.shutdown();
140 * This test case tests the scenario where 3 events occur and 2 of the requests refer to the
141 * same target entity while the 3rd is for another entity. The expected result is that the event
142 * with the duplicate target entity will have a final success result for one of the events, and
143 * a rejected message for the one that was unable to obtain the lock. The event that is
144 * referring to a different target entity should be able to obtain a lock since it is a
145 * different target. After processing of all events there should only be the params object left
149 public void targetLockedTest() {
152 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
153 * to be pulled from the queue
155 for (TopicSink sink : noopTopics) {
156 assertTrue(sink.start());
161 * Create a unique requestId
163 requestId = UUID.randomUUID();
166 * This will be a unique request for another target entity
168 requestId2 = UUID.randomUUID();
171 * This will be a request duplicating the target entity of the first request
173 requestId3 = UUID.randomUUID();
176 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
179 sendEvent(pair.a, requestId, ControlLoopEventStatus.ONSET, "vnf01");
182 * Send a second event requesting an action for a different target entity
184 sendEvent(pair.a, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
187 * Send a second event for a different target to ensure there are no problems with obtaining
188 * a lock for a different
190 kieSession.fireUntilHalt();
193 * The only fact in memory should be Params
195 assertEquals(1, kieSession.getFactCount());
198 * Print what's left in memory
200 dumpFacts(kieSession);
205 * This method will start a kie session and instantiate the Policy Engine.
207 * @param droolsTemplate the DRL rules file
208 * @param yamlFile the yaml file containing the policies
209 * @param policyScope scope for policy
210 * @param policyName name of the policy
211 * @param policyVersion version of the policy
212 * @return the kieSession to be used to insert facts
213 * @throws IOException
215 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
216 String policyName, String policyVersion) throws IOException {
219 * Load policies from yaml
221 pair = Util.loadYaml(yamlFile);
223 assertNotNull(pair.a);
224 assertNotNull(pair.a.getControlLoop());
225 assertNotNull(pair.a.getControlLoop().getControlLoopName());
226 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
229 * Construct a kie session
231 final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(),
232 policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8"));
235 * Retrieve the Policy Engine
238 logger.debug("============");
239 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
240 logger.debug("============");
248 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
251 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
253 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
257 if ("POLICY-CL-MGT".equals(topic)) {
258 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
259 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
260 } else if ("APPC-LCM-READ".equals(topic)) {
261 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
262 org.onap.policy.appclcm.LcmRequestWrapper.class);
265 if (obj instanceof VirtualControlLoopNotification) {
266 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
267 String policyName = notification.getPolicyName();
268 if (policyName.endsWith("EVENT")) {
269 logger.debug("Rule Fired: " + notification.getPolicyName());
270 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
271 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
272 logger.debug("Rule Fired: " + notification.getPolicyName());
273 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
274 assertNotNull(notification.getMessage());
275 assertTrue(notification.getMessage().startsWith("Sending guard query"));
276 } else if (policyName.endsWith("GUARD.RESPONSE")) {
277 logger.debug("Rule Fired: " + notification.getPolicyName());
278 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
279 assertNotNull(notification.getMessage());
280 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
281 } else if (policyName.endsWith("GUARD_PERMITTED")) {
282 logger.debug("Rule Fired: " + notification.getPolicyName());
283 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
284 assertNotNull(notification.getMessage());
285 assertTrue(notification.getMessage().startsWith("actor=APPC"));
286 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
287 logger.debug("Rule Fired: " + notification.getPolicyName());
289 logger.debug("The operation timed out");
290 fail("Operation Timed Out");
291 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
292 logger.debug("Rule Fired: " + notification.getPolicyName());
293 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
294 assertNotNull(notification.getMessage());
295 assertTrue(notification.getMessage().startsWith("actor=APPC"));
296 if (requestId.equals(notification.getRequestId())) {
297 sendEvent(pair.a, requestId, ControlLoopEventStatus.ABATED, "vnf01");
298 } else if (requestId2.equals(notification.getRequestId())) {
299 sendEvent(pair.a, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
301 } else if (policyName.endsWith("EVENT.MANAGER")) {
302 logger.debug("Rule Fired: " + notification.getPolicyName());
303 if (requestId3.equals(notification.getRequestId())) {
305 * The event with the duplicate target should be rejected
307 assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.getNotification()));
309 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
311 if (++eventCount == 3) {
314 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
315 logger.debug("Rule Fired: " + notification.getPolicyName());
317 logger.debug("The control loop timed out");
318 fail("Control Loop Timed Out");
320 } else if (obj instanceof LcmRequestWrapper) {
322 * The request should be of type LCMRequestWrapper and the subrequestid should be 1
324 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
325 LcmRequest appcRequest = dmaapRequest.getBody();
326 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
328 logger.debug("\n============ APPC received the request!!! ===========\n");
331 * Simulate a success response from APPC and insert the response into the working memory
333 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
334 LcmResponse appcResponse = new LcmResponse(appcRequest);
335 appcResponse.getStatus().setCode(400);
336 appcResponse.getStatus().setMessage("AppC success");
337 dmaapResponse.setBody(appcResponse);
340 * Interrupting with a different request for the same target entity to check if lock
343 if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
344 sendEvent(pair.a, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
346 kieSession.insert(dmaapResponse);
351 * This method is used to simulate event messages from DCAE that start the control loop (onset
352 * message) or end the control loop (abatement message).
354 * @param policy the controlLoopName comes from the policy
355 * @param requestID the requestId for this event
356 * @param status could be onset or abated
357 * @param target, the target entity to take an action on
359 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String target) {
360 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
361 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
362 event.setRequestId(requestID);
363 event.setTarget("generic-vnf.vnf-id");
364 event.setClosedLoopAlarmStart(Instant.now());
365 event.setAai(new HashMap<>());
366 event.getAai().put("generic-vnf.vnf-id", target);
367 event.setClosedLoopEventStatus(status);
368 kieSession.insert(event);
372 * This method will dump all the facts in the working memory.
374 * @param kieSession the session containing the facts
376 public void dumpFacts(KieSession kieSession) {
377 logger.debug("Fact Count: {}", kieSession.getFactCount());
378 for (FactHandle handle : kieSession.getFactHandles()) {
379 logger.debug("FACT: {}", handle);