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.ControlLoopTargetType;
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.onap.policy.drools.utils.logging.LoggerUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public class VcpeControlLoopTest implements TopicListener {
67 private static final Logger logger = LoggerFactory.getLogger(VcpeControlLoopTest.class);
69 private static List<? extends TopicSink> noopTopics;
71 private static KieSession kieSession;
72 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
73 private UUID requestId;
76 /* Set environment properties */
77 SupportUtil.setAaiProps();
78 SupportUtil.setGuardProps();
79 SupportUtil.setPuProp();
80 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
84 * Setup the simulator.
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());
122 * Start the kie session
125 kieSession = startSession(
126 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
127 + "/src/main/resources/__closedLoopControlName__.drl",
128 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
129 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
130 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
131 } catch (IOException e) {
133 logger.debug("Could not create kieSession");
134 fail("Could not create kieSession");
139 * Tear down the simulator.
142 public static void tearDownSimulator() {
144 * Gracefully shut down the kie session
146 kieSession.dispose();
148 PolicyEngine.manager.stop();
149 HttpServletServerFactoryInstance.getServerFactory().destroy();
150 PolicyController.factory.shutdown();
151 TopicEndpointManager.getManager().shutdown();
155 public void successTest() {
158 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
159 * to be pulled from the queue
161 for (TopicSink sink : noopTopics) {
162 assertTrue(sink.start());
167 * Create a unique requestId
169 requestId = UUID.randomUUID();
172 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
175 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
177 kieSession.fireUntilHalt();
179 // allow object clean-up
180 kieSession.fireAllRules();
183 * The only fact in memory should be Params
185 assertEquals(1, kieSession.getFactCount());
188 * Print what's left in memory
190 dumpFacts(kieSession);
194 public void aaiGetFailTest() {
197 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
198 * to be pulled from the queue
200 for (TopicSink sink : noopTopics) {
201 assertTrue(sink.start());
206 * Create a unique requestId
208 requestId = UUID.randomUUID();
211 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
214 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false);
217 kieSession.fireUntilHalt();
219 // allow object clean-up
220 kieSession.fireAllRules();
223 * The only fact in memory should be Params
225 assertEquals(1, kieSession.getFactCount());
228 * Print what's left in memory
230 dumpFacts(kieSession);
235 * This method will start a kie session and instantiate the Policy Engine.
237 * @param droolsTemplate the DRL rules file
238 * @param yamlFile the yaml file containing the policies
239 * @param policyScope scope for policy
240 * @param policyName name of the policy
241 * @param policyVersion version of the policy
242 * @return the kieSession to be used to insert facts
243 * @throws IOException IO exception
245 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
246 String policyName, String policyVersion) throws IOException {
249 * Load policies from yaml
251 pair = SupportUtil.loadYaml(yamlFile);
253 assertNotNull(pair.first);
254 assertNotNull(pair.first.getControlLoop());
255 assertNotNull(pair.first.getControlLoop().getControlLoopName());
256 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
259 * Construct a kie session
261 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
262 pair.first.getControlLoop().getControlLoopName(),
263 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
266 * Retrieve the Policy Engine
269 logger.debug("============");
270 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
271 logger.debug("============");
279 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
282 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
284 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
288 if ("POLICY-CL-MGT".equals(topic)) {
289 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
290 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
291 } else if ("APPC-LCM-READ".equals(topic)) {
292 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
293 org.onap.policy.appclcm.LcmRequestWrapper.class);
296 if (obj instanceof VirtualControlLoopNotification) {
297 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
298 String policyName = notification.getPolicyName();
299 if (policyName.endsWith("EVENT")) {
300 logger.debug("Rule Fired: " + notification.getPolicyName());
301 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
302 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
303 logger.debug("Rule Fired: " + notification.getPolicyName());
304 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
305 assertNotNull(notification.getMessage());
306 assertTrue(notification.getMessage().startsWith("Sending guard query"));
307 } else if (policyName.endsWith("GUARD.RESPONSE")) {
308 logger.debug("Rule Fired: " + notification.getPolicyName());
309 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
310 assertNotNull(notification.getMessage());
311 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
312 } else if (policyName.endsWith("GUARD_PERMITTED")) {
313 logger.debug("Rule Fired: " + notification.getPolicyName());
314 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
315 assertNotNull(notification.getMessage());
316 assertTrue(notification.getMessage().startsWith("actor=APPC"));
317 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
318 logger.debug("Rule Fired: " + notification.getPolicyName());
320 logger.debug("The operation timed out");
321 fail("Operation Timed Out");
322 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
323 logger.debug("Rule Fired: " + notification.getPolicyName());
324 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
325 assertNotNull(notification.getMessage());
326 assertTrue(notification.getMessage().startsWith("actor=APPC"));
327 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
328 } else if (policyName.endsWith("EVENT.MANAGER")) {
329 logger.debug("Rule Fired: " + notification.getPolicyName());
330 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
331 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
334 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
337 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
338 logger.debug("Rule Fired: " + notification.getPolicyName());
340 logger.debug("The control loop timed out");
341 fail("Control Loop Timed Out");
343 } else if (obj instanceof LcmRequestWrapper) {
345 * The request should be of type LcmRequestWrapper and the subrequestid should be 1
347 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
348 LcmRequest appcRequest = dmaapRequest.getBody();
349 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
350 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
352 logger.debug("\n============ APPC received the request!!! ===========\n");
355 * Simulate a success response from APPC and insert the response into the working memory
357 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
358 LcmResponse appcResponse = new LcmResponse(appcRequest);
359 appcResponse.getStatus().setCode(400);
360 appcResponse.getStatus().setMessage("AppC success");
361 dmaapResponse.setBody(appcResponse);
362 kieSession.insert(dmaapResponse);
367 * This method is used to simulate event messages from DCAE that start the control loop (onset
368 * message) or end the control loop (abatement message).
370 * @param policy the controlLoopName comes from the policy
371 * @param requestId the requestId for this event
372 * @param status could be onset or abated
374 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
375 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
376 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
377 event.setRequestId(requestId);
378 event.setTarget("generic-vnf.vnf-name");
379 event.setClosedLoopAlarmStart(Instant.now());
380 event.setAai(new HashMap<>());
381 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
382 event.setClosedLoopEventStatus(status);
383 kieSession.insert(event);
386 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName,
387 boolean isEnriched) {
388 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
389 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
390 event.setRequestId(requestId);
391 event.setTarget("generic-vnf.vnf-name");
392 event.setTargetType(ControlLoopTargetType.VNF);
393 event.setClosedLoopAlarmStart(Instant.now());
394 event.setAai(new HashMap<>());
395 event.getAai().put("generic-vnf.vnf-name", vnfName);
397 event.getAai().put("generic-vnf.in-maint", "false");
398 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
399 event.getAai().put("generic-vnf.orchestration-status", "Created");
400 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
401 event.getAai().put("generic-vnf.resource-version", "1");
402 event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
403 event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
404 event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
406 event.setClosedLoopEventStatus(status);
407 kieSession.insert(event);
411 * This method will dump all the facts in the working memory.
413 * @param kieSession the session containing the facts
415 public void dumpFacts(KieSession kieSession) {
416 logger.debug("Fact Count: {}", kieSession.getFactCount());
417 for (FactHandle handle : kieSession.getFactHandles()) {
418 logger.debug("FACT: {}", handle);