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.ControlLoopTargetType;
54 import org.onap.policy.controlloop.VirtualControlLoopEvent;
55 import org.onap.policy.controlloop.VirtualControlLoopNotification;
56 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
57 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
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 Util.Pair<ControlLoopPolicy, String> pair;
73 private UUID requestId;
76 /* Set environment properties */
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 = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
101 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
102 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
104 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
105 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
108 Util.buildGuardSim();
109 } catch (Exception e) {
110 fail(e.getMessage());
113 * Start the kie session
116 kieSession = startSession(
117 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
118 + "/src/main/resources/__closedLoopControlName__.drl",
119 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
120 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
121 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
122 } catch (IOException e) {
124 logger.debug("Could not create kieSession");
125 fail("Could not create kieSession");
130 * Tear down the simulator.
133 public static void tearDownSimulator() {
135 * Gracefully shut down the kie session
137 kieSession.dispose();
139 PolicyEngine.manager.stop();
140 HttpServletServer.factory.destroy();
141 PolicyController.factory.shutdown();
142 TopicEndpoint.manager.shutdown();
146 public void successTest() {
149 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
150 * to be pulled from the queue
152 for (TopicSink sink : noopTopics) {
153 assertTrue(sink.start());
158 * Create a unique requestId
160 requestId = UUID.randomUUID();
163 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
166 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
168 kieSession.fireUntilHalt();
170 // allow object clean-up
171 kieSession.fireAllRules();
174 * The only fact in memory should be Params
176 assertEquals(1, kieSession.getFactCount());
179 * Print what's left in memory
181 dumpFacts(kieSession);
185 public void aaiGetFailTest() {
188 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
189 * to be pulled from the queue
191 for (TopicSink sink : noopTopics) {
192 assertTrue(sink.start());
197 * Create a unique requestId
199 requestId = UUID.randomUUID();
202 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
205 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false);
208 kieSession.fireUntilHalt();
210 // allow object clean-up
211 kieSession.fireAllRules();
214 * The only fact in memory should be Params
216 assertEquals(1, kieSession.getFactCount());
219 * Print what's left in memory
221 dumpFacts(kieSession);
226 * This method will start a kie session and instantiate the Policy Engine.
228 * @param droolsTemplate the DRL rules file
229 * @param yamlFile the yaml file containing the policies
230 * @param policyScope scope for policy
231 * @param policyName name of the policy
232 * @param policyVersion version of the policy
233 * @return the kieSession to be used to insert facts
234 * @throws IOException IO exception
236 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
237 String policyName, String policyVersion) throws IOException {
240 * Load policies from yaml
242 pair = Util.loadYaml(yamlFile);
244 assertNotNull(pair.first);
245 assertNotNull(pair.first.getControlLoop());
246 assertNotNull(pair.first.getControlLoop().getControlLoopName());
247 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
250 * Construct a kie session
252 final KieSession kieSession = Util.buildContainer(droolsTemplate,
253 pair.first.getControlLoop().getControlLoopName(),
254 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
257 * Retrieve the Policy Engine
260 logger.debug("============");
261 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
262 logger.debug("============");
270 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
273 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
275 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
279 if ("POLICY-CL-MGT".equals(topic)) {
280 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
281 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
282 } else if ("APPC-LCM-READ".equals(topic)) {
283 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
284 org.onap.policy.appclcm.LcmRequestWrapper.class);
287 if (obj instanceof VirtualControlLoopNotification) {
288 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
289 String policyName = notification.getPolicyName();
290 if (policyName.endsWith("EVENT")) {
291 logger.debug("Rule Fired: " + notification.getPolicyName());
292 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
293 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
294 logger.debug("Rule Fired: " + notification.getPolicyName());
295 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
296 assertNotNull(notification.getMessage());
297 assertTrue(notification.getMessage().startsWith("Sending guard query"));
298 } else if (policyName.endsWith("GUARD.RESPONSE")) {
299 logger.debug("Rule Fired: " + notification.getPolicyName());
300 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
301 assertNotNull(notification.getMessage());
302 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
303 } else if (policyName.endsWith("GUARD_PERMITTED")) {
304 logger.debug("Rule Fired: " + notification.getPolicyName());
305 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
306 assertNotNull(notification.getMessage());
307 assertTrue(notification.getMessage().startsWith("actor=APPC"));
308 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
309 logger.debug("Rule Fired: " + notification.getPolicyName());
311 logger.debug("The operation timed out");
312 fail("Operation Timed Out");
313 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
314 logger.debug("Rule Fired: " + notification.getPolicyName());
315 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
316 assertNotNull(notification.getMessage());
317 assertTrue(notification.getMessage().startsWith("actor=APPC"));
318 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
319 } else if (policyName.endsWith("EVENT.MANAGER")) {
320 logger.debug("Rule Fired: " + notification.getPolicyName());
321 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
322 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
325 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
328 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
329 logger.debug("Rule Fired: " + notification.getPolicyName());
331 logger.debug("The control loop timed out");
332 fail("Control Loop Timed Out");
334 } else if (obj instanceof LcmRequestWrapper) {
336 * The request should be of type LcmRequestWrapper and the subrequestid should be 1
338 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
339 LcmRequest appcRequest = dmaapRequest.getBody();
340 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
341 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
343 logger.debug("\n============ APPC received the request!!! ===========\n");
346 * Simulate a success response from APPC and insert the response into the working memory
348 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
349 LcmResponse appcResponse = new LcmResponse(appcRequest);
350 appcResponse.getStatus().setCode(400);
351 appcResponse.getStatus().setMessage("AppC success");
352 dmaapResponse.setBody(appcResponse);
353 kieSession.insert(dmaapResponse);
358 * This method is used to simulate event messages from DCAE that start the control loop (onset
359 * message) or end the control loop (abatement message).
361 * @param policy the controlLoopName comes from the policy
362 * @param requestID the requestId for this event
363 * @param status could be onset or abated
365 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
366 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
367 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
368 event.setRequestId(requestId);
369 event.setTarget("generic-vnf.vnf-name");
370 event.setClosedLoopAlarmStart(Instant.now());
371 event.setAai(new HashMap<>());
372 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
373 event.setClosedLoopEventStatus(status);
374 kieSession.insert(event);
377 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName,
378 boolean isEnriched) {
379 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
380 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
381 event.setRequestId(requestId);
382 event.setTarget("generic-vnf.vnf-name");
383 event.setTargetType(ControlLoopTargetType.VNF);
384 event.setClosedLoopAlarmStart(Instant.now());
385 event.setAai(new HashMap<>());
386 event.getAai().put("generic-vnf.vnf-name", vnfName);
388 event.getAai().put("generic-vnf.in-maint", "false");
389 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
390 event.getAai().put("generic-vnf.orchestration-status", "Created");
391 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
392 event.getAai().put("generic-vnf.resource-version", "1");
393 event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
394 event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
395 event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
397 event.setClosedLoopEventStatus(status);
398 kieSession.insert(event);
402 * This method will dump all the facts in the working memory.
404 * @param kieSession the session containing the facts
406 public void dumpFacts(KieSession kieSession) {
407 logger.debug("Fact Count: {}", kieSession.getFactCount());
408 for (FactHandle handle : kieSession.getFactHandles()) {
409 logger.debug("FACT: {}", handle);