2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 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.clc;
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 com.google.gson.Gson;
30 import java.io.IOException;
31 import java.lang.StringBuilder;
32 import java.net.URLEncoder;
33 import java.time.Instant;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Properties;
37 import java.util.UUID;
39 import org.junit.AfterClass;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
43 import org.kie.api.runtime.KieSession;
44 import org.kie.api.runtime.rule.FactHandle;
46 import org.onap.policy.appclcm.LcmRequest;
47 import org.onap.policy.appclcm.LcmRequestWrapper;
48 import org.onap.policy.appclcm.LcmResponse;
49 import org.onap.policy.appclcm.LcmResponseWrapper;
50 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
51 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
52 import org.onap.policy.common.endpoints.event.comm.TopicListener;
53 import org.onap.policy.common.endpoints.event.comm.TopicSink;
54 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
55 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
56 import org.onap.policy.controlloop.ControlLoopEventStatus;
57 import org.onap.policy.controlloop.ControlLoopNotificationType;
58 import org.onap.policy.controlloop.ControlLoopTargetType;
59 import org.onap.policy.controlloop.VirtualControlLoopEvent;
60 import org.onap.policy.controlloop.VirtualControlLoopNotification;
61 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
62 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
63 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
64 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
65 import org.onap.policy.drools.system.PolicyController;
66 import org.onap.policy.drools.system.PolicyEngine;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 public class ControlLoopCoordinationTest implements TopicListener {
73 private static final Logger logger = LoggerFactory.getLogger(ControlLoopCoordinationTest.class);
75 private static List<? extends TopicSink> noopTopics;
77 private static KieSession kieSession1;
78 private static KieSession kieSession2;
79 private static StringBuilder controlLoopOneName = new StringBuilder();
80 private static StringBuilder controlLoopTwoName = new StringBuilder();
81 private static String expectedDecision;
84 /* Set environment properties */
86 Util.setGuardPropsEmbedded();
94 public static void setUpSimulator() {
95 PolicyEngine.manager.configure(new Properties());
96 assertTrue(PolicyEngine.manager.start());
97 Properties noopSinkProperties = new Properties();
98 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
99 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
100 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
101 "org.onap.policy.appclcm.util.Serialization,gson");
102 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
103 "org.onap.policy.controlloop.VirtualControlLoopNotification");
104 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
105 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
106 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
108 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
109 .groupId("junit.groupId")
110 .artifactId("junit.artifactId")
111 .topic("POLICY-CL-MGT")
112 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
113 .protocolFilter(new JsonProtocolFilter())
114 .customGsonCoder(null)
115 .customJacksonCoder(null)
116 .modelClassLoaderHash(1111));
117 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
118 .groupId("junit.groupId")
119 .artifactId("junit.artifactId")
120 .topic("APPC-LCM-READ")
121 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
122 .protocolFilter(new JsonProtocolFilter())
123 .customGsonCoder(null)
124 .customJacksonCoder(null)
125 .modelClassLoaderHash(1111));
128 } catch (Exception e) {
129 fail(e.getMessage());
133 * Start the kie sessions
136 kieSession1 = startSession(
138 "src/main/resources/__closedLoopControlName__.drl",
139 "src/test/resources/yaml/policy_ControlLoop_SyntheticOne.yaml",
140 "service=ServiceDemo;resource=Res1Demo;type=operational",
141 "SyntheticControlLoopOnePolicy",
142 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
143 kieSession2 = startSession(
145 "src/main/resources/__closedLoopControlName__.drl",
146 "src/test/resources/yaml/policy_ControlLoop_SyntheticTwo.yaml",
147 "service=ServiceDemo;resource=Res1Demo;type=operational",
148 "SyntheticControlLoopTwoPolicy",
149 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
150 } catch (IOException e) {
151 logger.debug("Could not create kieSession, exception {}", e.getMessage());
152 fail("Could not create kieSession");
157 * Tear down simulator.
160 public static void tearDownSimulator() {
162 * Gracefully shut down the kie session
164 kieSession1.dispose();
165 kieSession2.dispose();
167 PolicyEngine.manager.stop();
168 HttpServletServer.factory.destroy();
169 PolicyController.factory.shutdown();
170 TopicEndpoint.manager.shutdown();
174 * Set expected decision.
176 * @param ed the expected decision ("PERMIT" or "DENY")
178 public void expectedDecisionIs(String ed) {
179 expectedDecision = ed;
180 logger.info("Expected decision is {}", ed);
184 * This method is used to simulate event messages from DCAE
185 * that start the control loop (onset message) or end the
186 * control loop (abatement message).
188 * @param controlLoopName the control loop name
189 * @param requestId the requestId for this event
190 * @param status could be onset or abated
191 * @param target the target name
192 * @param kieSession the kieSession to which this event is being sent
194 protected void sendEvent(String controlLoopName,
196 ControlLoopEventStatus status,
198 KieSession kieSession) {
199 logger.debug("sendEvent controlLoopName={}", controlLoopName);
200 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
201 event.setClosedLoopControlName(controlLoopName);
202 event.setRequestId(requestId);
203 event.setTarget("generic-vnf.vnf-name");
204 event.setTargetType(ControlLoopTargetType.VNF);
205 event.setClosedLoopAlarmStart(Instant.now());
206 event.setAai(new HashMap<>());
207 event.getAai().put("generic-vnf.vnf-name", target);
208 event.setClosedLoopEventStatus(status);
210 Gson gson = new Gson();
211 String json = gson.toJson(event);
212 logger.debug("sendEvent {}", json);
214 kieSession.insert(event);
219 * Simulate an event by inserting into kieSession and firing rules as needed.
221 * @param cles the ControlLoopEventStatus
222 * @param rid the request ID
223 * @param controlLoopName the control loop name
224 * @param kieSession the kieSession to which this event is being sent
225 * @param expectedDecision the expected decision
227 protected void simulateEvent(ControlLoopEventStatus cles,
229 String controlLoopName,
231 KieSession kieSession,
232 String expectedDecision) {
234 // if onset, set expected decision
236 if (cles == ControlLoopEventStatus.ONSET) {
237 expectedDecisionIs(expectedDecision);
240 // simulate sending event
242 sendEvent(controlLoopName, rid, cles, target, kieSession);
243 kieSession.fireUntilHalt();
245 // get dump of database entries and log
247 List<?> entries = Util.dumpDb();
248 assertNotNull(entries);
249 logger.debug("dumpDB, {} entries", entries.size());
250 for (Object entry : entries) {
251 logger.debug("{}", entry);
256 logger.info("simulateEvent: done");
260 * Simulate an onset event.
262 * @param rid the request ID
263 * @param controlLoopName the control loop name
264 * @param kieSession the kieSession to which this event is being sent
265 * @param expectedDecision the expected decision
267 public void simulateOnset(UUID rid,
268 String controlLoopName,
270 KieSession kieSession,
271 String expectedDecision) {
272 simulateEvent(ControlLoopEventStatus.ONSET, rid, controlLoopName, target, kieSession, expectedDecision);
276 * Simulate an abated event.
278 * @param rid the request ID
279 * @param controlLoopName the control loop name
280 * @param kieSession the kieSession to which this event is being sent
282 public void simulateAbatement(UUID rid,
283 String controlLoopName,
285 KieSession kieSession) {
286 simulateEvent(ControlLoopEventStatus.ABATED, rid, controlLoopName, target, kieSession, null);
290 * This method will start a kie session and instantiate the Policy Engine.
292 * @param droolsTemplate the DRL rules file
293 * @param yamlFile the yaml file containing the policies
294 * @param policyScope scope for policy
295 * @param policyName name of the policy
296 * @param policyVersion version of the policy
297 * @return the kieSession to be used to insert facts
298 * @throws IOException throws IO exception
300 private static KieSession startSession(StringBuilder controlLoopName,
301 String droolsTemplate,
305 String policyVersion) throws IOException {
308 * Load policies from yaml
310 Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yamlFile);
312 assertNotNull(pair.first);
313 assertNotNull(pair.first.getControlLoop());
314 assertNotNull(pair.first.getControlLoop().getControlLoopName());
315 assertTrue(!pair.first.getControlLoop().getControlLoopName().isEmpty());
317 controlLoopName.append(pair.first.getControlLoop().getControlLoopName());
318 String yamlContents = pair.second;
321 * Construct a kie session
323 final KieSession kieSession = Util.buildContainer(droolsTemplate,
324 controlLoopName.toString(),
328 URLEncoder.encode(yamlContents, "UTF-8"));
331 * Retrieve the Policy Engine
334 logger.debug("============");
335 logger.debug(URLEncoder.encode(yamlContents, "UTF-8"));
336 logger.debug("============");
344 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
347 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
349 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
353 if ("POLICY-CL-MGT".equals(topic)) {
354 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
355 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
356 } else if ("APPC-LCM-READ".equals(topic)) {
357 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
358 org.onap.policy.appclcm.LcmRequestWrapper.class);
361 if (obj instanceof VirtualControlLoopNotification) {
362 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
363 String policyName = notification.getPolicyName();
364 if (policyName.endsWith("EVENT")) {
365 logger.debug("Rule Fired: " + notification.getPolicyName());
366 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
367 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
368 logger.debug("Rule Fired: " + notification.getPolicyName());
369 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
370 assertNotNull(notification.getMessage());
371 assertTrue(notification.getMessage().startsWith("Sending guard query"));
372 } else if (policyName.endsWith("GUARD.RESPONSE")) {
373 logger.debug("Rule Fired: " + notification.getPolicyName());
374 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
375 assertNotNull(notification.getMessage());
376 // THESE ARE THE MOST CRITICAL ASSERTS
377 // TEST IF GUARD.RESPONSE IS CORRECT
378 logger.debug("Testing whether decision was {} as expected", expectedDecision);
379 assertTrue(notification.getMessage().toUpperCase().endsWith(expectedDecision));
380 } else if (policyName.endsWith("GUARD_PERMITTED")) {
381 logger.debug("Rule Fired: " + notification.getPolicyName());
382 assertEquals(ControlLoopNotificationType.OPERATION,notification.getNotification());
383 assertNotNull(notification.getMessage());
384 assertTrue(notification.getMessage().startsWith("actor=APPC"));
385 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
386 logger.debug("Rule Fired: " + notification.getPolicyName());
389 logger.debug("The operation timed out");
390 fail("Operation Timed Out");
391 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
392 logger.debug("Rule Fired: " + notification.getPolicyName());
393 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
394 assertNotNull(notification.getMessage());
395 assertTrue(notification.getMessage().startsWith("actor=APPC"));
396 } else if (policyName.endsWith("EVENT.MANAGER")) {
397 logger.debug("Rule Fired: " + notification.getPolicyName());
398 if (notification.getMessage().endsWith("Closing the control loop.")
399 || notification.getMessage().equals("Waiting for abatement")) {
400 if (policyName.startsWith(controlLoopOneName.toString())) {
401 logger.debug("Halting kieSession1");
403 } else if (policyName.startsWith(controlLoopTwoName.toString())) {
404 logger.debug("Halting kieSession2");
407 fail("Unknown ControlLoop");
410 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
411 logger.debug("Rule Fired: " + notification.getPolicyName());
414 logger.debug("The control loop timed out");
415 fail("Control Loop Timed Out");
417 } else if (obj instanceof LcmRequestWrapper) {
419 * The request should be of type LCMRequestWrapper and the subrequestid should be 1
421 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
422 LcmRequest appcRequest = dmaapRequest.getBody();
423 assertEquals(appcRequest.getCommonHeader().getSubRequestId(),"1");
425 logger.debug("\n============ APPC received the request!!! ===========\n");
428 * Simulate a success response from APPC and insert the response into the working memory
430 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
431 LcmResponse appcResponse = new LcmResponse(appcRequest);
432 appcResponse.getStatus().setCode(400);
433 appcResponse.getStatus().setMessage("AppC success");
434 dmaapResponse.setBody(appcResponse);
435 kieSession1.insert(dmaapResponse);
436 kieSession2.insert(dmaapResponse);
441 * This method will dump all the facts in the working memory.
443 * @param kieSession the session containing the facts
445 public void dumpFacts(KieSession kieSession) {
446 logger.debug("Fact Count: {}", kieSession.getFactCount());
447 for (FactHandle handle : kieSession.getFactHandles()) {
448 logger.debug("FACT: {}", handle);
453 * Test that SyntheticControlLoopOne blocks SyntheticControlLoopTwo
454 * is enforced correctly.
457 public void testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo() throws InterruptedException {
458 logger.info("Beginning testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo");
460 * Allows the PolicyEngine to callback to this object to
461 * notify that there is an event ready to be pulled
464 for (TopicSink sink : noopTopics) {
465 assertTrue(sink.start());
470 * Create unique requestIds
472 final UUID requestId1 = UUID.randomUUID();
473 final UUID requestId2 = UUID.randomUUID();
474 final UUID requestId3 = UUID.randomUUID();
475 final UUID requestId4 = UUID.randomUUID();
476 final UUID requestId5 = UUID.randomUUID();
477 final String cl1 = controlLoopOneName.toString();
478 final String cl2 = controlLoopTwoName.toString();
479 final String t1 = "TARGET_1";
480 final String t2 = "TARGET_2";
482 logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@");
483 simulateOnset(requestId1, cl2, t1, kieSession2,"PERMIT");
484 logger.info("@@@@@@@@@@ cl1 ONSET t1 @@@@@@@@@@");
485 simulateOnset(requestId2, cl1, t1, kieSession1,"PERMIT");
486 logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@");
487 simulateAbatement(requestId1, cl2, t1, kieSession2);
488 logger.info("@@@@@@@@@@ cl2 ONSET t1 (Fail) @@@@@@@@@@");
489 simulateOnset(requestId3, cl2, t1, kieSession2,"DENY");
490 logger.info("@@@@@@@@@@ cl2 ONSET t2 (Success) @@@@@@@@@@");
491 simulateOnset(requestId4, cl2, t2, kieSession2,"PERMIT");
492 logger.info("@@@@@@@@@@ cl2 ABATED t2 @@@@@@@@@@");
493 simulateAbatement(requestId4, cl2, t2, kieSession2);
494 logger.info("@@@@@@@@@@ cl1 ABATED t1 @@@@@@@@@@");
495 simulateAbatement(requestId2, cl1, t1, kieSession1);
496 logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@");
497 simulateOnset(requestId5, cl2, t1, kieSession2,"PERMIT");
498 logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@");
499 simulateAbatement(requestId5, cl2, t1, kieSession2);
502 * Print what's left in memory
504 dumpFacts(kieSession1);
505 dumpFacts(kieSession2);