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;
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.appc.Request;
42 import org.onap.policy.appc.Response;
43 import org.onap.policy.appc.ResponseCode;
44 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
45 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
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.HttpServletServer;
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.onap.policy.drools.utils.logging.LoggerUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class VfwControlLoopTest implements TopicListener {
66 private static final Logger logger = LoggerFactory.getLogger(VfwControlLoopTest.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;
75 /* Set environment properties */
76 SupportUtil.setAaiProps();
77 SupportUtil.setGuardProps();
78 SupportUtil.setPuProp();
79 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
83 * Setup the simulator.
86 public static void setUpSimulator() {
87 PolicyEngine.manager.configure(new Properties());
88 assertTrue(PolicyEngine.manager.start());
89 Properties noopSinkProperties = new Properties();
90 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
91 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
92 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
93 "org.onap.policy.appc.util.Serialization,gsonPretty");
94 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
95 "org.onap.policy.controlloop.VirtualControlLoopNotification");
96 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
97 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
98 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
100 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
101 .groupId("junit.groupId")
102 .artifactId("junit.artifactId")
103 .topic("POLICY-CL-MGT")
104 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
105 .protocolFilter(new JsonProtocolFilter())
106 .modelClassLoaderHash(1111));
107 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
108 .groupId("junit.groupId")
109 .artifactId("junit.artifactId")
111 .eventClass("org.onap.policy.appc.Request")
112 .protocolFilter(new JsonProtocolFilter())
113 .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/src/"
128 + "main/resources/__closedLoopControlName__.drl",
129 "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
130 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW",
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 the simulator.
143 public static void tearDownSimulator() {
145 * Gracefully shut down the kie session
147 kieSession.dispose();
149 PolicyEngine.manager.stop();
150 HttpServletServer.factory.destroy();
151 PolicyController.factory.shutdown();
152 TopicEndpoint.manager.shutdown();
156 public void successTest() {
159 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
160 * to be pulled from the queue
162 for (TopicSink sink : noopTopics) {
163 assertTrue(sink.start());
168 * Create a unique requestId
170 requestId = UUID.randomUUID();
173 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
176 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
179 kieSession.fireUntilHalt();
181 // allow object clean-up
182 kieSession.fireAllRules();
184 } catch (Exception e) {
186 logger.warn(e.toString());
192 * The only fact in memory should be Params
194 assertEquals(1, kieSession.getFactCount());
197 * Print what's left in memory
199 dumpFacts(kieSession);
203 public void aaiFailTests() {
206 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
207 * to be pulled from the queue
209 for (TopicSink sink : noopTopics) {
210 assertTrue(sink.start());
215 * Create a unique requestId
217 requestId = UUID.randomUUID();
220 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
223 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
225 kieSession.fireUntilHalt();
227 // allow object clean-up
228 kieSession.fireAllRules();
230 } catch (Exception e) {
232 logger.warn(e.toString());
233 fail(e.getMessage());
237 * The only fact in memory should be Params
239 assertEquals(1, kieSession.getFactCount());
242 * Print what's left in memory
244 dumpFacts(kieSession);
247 * Create a unique requestId
249 requestId = UUID.randomUUID();
252 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
256 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
259 kieSession.fireUntilHalt();
261 // allow object clean-up
262 kieSession.fireAllRules();
264 } catch (Exception e) {
266 logger.warn(e.toString());
267 fail(e.getMessage());
271 * The only fact in memory should be Params
273 assertEquals(1, kieSession.getFactCount());
276 * Print what's left in memory
278 dumpFacts(kieSession);
282 * This method will start a kie session and instantiate the Policy Engine.
284 * @param droolsTemplate the DRL rules file
285 * @param yamlFile the yaml file containing the policies
286 * @param policyScope scope for policy
287 * @param policyName name of the policy
288 * @param policyVersion version of the policy
289 * @return the kieSession to be used to insert facts
290 * @throws IOException IO Exception
292 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
293 String policyName, String policyVersion) throws IOException {
296 * Load policies from yaml
298 pair = SupportUtil.loadYaml(yamlFile);
300 assertNotNull(pair.first);
301 assertNotNull(pair.first.getControlLoop());
302 assertNotNull(pair.first.getControlLoop().getControlLoopName());
303 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
306 * Construct a kie session
308 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
309 pair.first.getControlLoop().getControlLoopName(),
310 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
313 * Retrieve the Policy Engine
316 logger.debug("============");
317 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
318 logger.debug("============");
324 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
327 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
329 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
333 if ("POLICY-CL-MGT".equals(topic)) {
334 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
335 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
336 } else if ("APPC-CL".equals(topic)) {
337 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event,
338 org.onap.policy.appc.Request.class);
341 if (obj instanceof VirtualControlLoopNotification) {
342 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
343 String policyName = notification.getPolicyName();
344 if (policyName.endsWith("EVENT")) {
345 logger.debug("Rule Fired: " + notification.getPolicyName());
346 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
347 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
348 logger.debug("Rule Fired: " + notification.getPolicyName());
349 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
350 assertNotNull(notification.getMessage());
351 assertTrue(notification.getMessage().startsWith("Sending guard query"));
352 } else if (policyName.endsWith("GUARD.RESPONSE")) {
353 logger.debug("Rule Fired: " + notification.getPolicyName());
354 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
355 assertNotNull(notification.getMessage());
356 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
357 } else if (policyName.endsWith("GUARD_PERMITTED")) {
358 logger.debug("Rule Fired: " + notification.getPolicyName());
359 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
360 assertNotNull(notification.getMessage());
361 assertTrue(notification.getMessage().startsWith("actor=APPC"));
362 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
363 logger.debug("Rule Fired: " + notification.getPolicyName());
365 logger.debug("The operation timed out");
366 fail("Operation Timed Out");
367 } else if (policyName.endsWith("APPC.RESPONSE")) {
368 logger.debug("Rule Fired: " + notification.getPolicyName());
369 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
370 assertNotNull(notification.getMessage());
371 assertTrue(notification.getMessage().startsWith("actor=APPC"));
372 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
373 } else if (policyName.endsWith("EVENT.MANAGER")) {
374 logger.debug("Rule Fired: " + notification.getPolicyName());
375 if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
376 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
377 assertEquals("Target vnf-id could not be found", notification.getMessage());
378 } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
379 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
381 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
384 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
385 logger.debug("Rule Fired: " + notification.getPolicyName());
387 logger.debug("The control loop timed out");
388 fail("Control Loop Timed Out");
390 } else if (obj instanceof Request) {
391 assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1"));
392 assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id"));
394 logger.debug("\n============ APPC received the request!!! ===========\n");
397 * Simulate a success response from APPC and insert the response into the working memory
399 Response appcResponse = new Response((Request) obj);
400 appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
401 appcResponse.getStatus().setValue("SUCCESS");
402 kieSession.insert(appcResponse);
407 * This method is used to simulate event messages from DCAE that start the control loop (onset
408 * message) or end the control loop (abatement message).
410 * @param policy the controlLoopName comes from the policy
411 * @param requestId the requestId for this event
412 * @param status could be onset or abated
414 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
415 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
416 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
417 event.setRequestId(requestId);
418 event.setTarget("generic-vnf.vnf-name");
419 event.setClosedLoopAlarmStart(Instant.now());
420 event.setAai(new HashMap<>());
421 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
422 event.setClosedLoopEventStatus(status);
423 kieSession.insert(event);
427 * This method is used to simulate event messages from DCAE that start the control loop (onset
428 * message) or end the control loop (abatement message).
430 * @param policy the controlLoopName comes from the policy
431 * @param requestId the requestId for this event
432 * @param status could be onset or abated
434 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) {
435 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
436 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
437 event.setRequestId(requestId);
438 event.setTarget("generic-vnf.vnf-name");
439 event.setClosedLoopAlarmStart(Instant.now());
440 event.setAai(new HashMap<>());
441 event.getAai().put("generic-vnf.vnf-name", vnfId);
442 event.setClosedLoopEventStatus(status);
443 kieSession.insert(event);
447 * This method will dump all the facts in the working memory.
449 * @param kieSession the session containing the facts
451 public void dumpFacts(KieSession kieSession) {
452 logger.debug("Fact Count: {}", kieSession.getFactCount());
453 for (FactHandle handle : kieSession.getFactHandles()) {
454 logger.debug("FACT: {}", handle);