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 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());
110 * Start the kie session
113 kieSession = startSession(
114 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
115 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
116 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
117 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
118 } catch (IOException e) {
120 logger.debug("Could not create kieSession");
121 fail("Could not create kieSession");
126 public static void tearDownSimulator() {
128 * Gracefully shut down the kie session
130 kieSession.dispose();
132 PolicyEngine.manager.stop();
133 HttpServletServer.factory.destroy();
134 PolicyController.factory.shutdown();
135 TopicEndpoint.manager.shutdown();
139 public void successTest() {
142 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
143 * to be pulled from the queue
145 for (TopicSink sink : noopTopics) {
146 assertTrue(sink.start());
151 * Create a unique requestId
153 requestID = UUID.randomUUID();
156 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
159 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
161 kieSession.fireUntilHalt();
164 * The only fact in memory should be Params
166 assertEquals(1, kieSession.getFactCount());
169 * Print what's left in memory
171 dumpFacts(kieSession);
175 public void aaiGetFailTest() {
178 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
179 * to be pulled from the queue
181 for (TopicSink sink : noopTopics) {
182 assertTrue(sink.start());
187 * Create a unique requestId
189 requestID = UUID.randomUUID();
192 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
195 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false);
198 kieSession.fireUntilHalt();
201 * The only fact in memory should be Params
203 assertEquals(1, kieSession.getFactCount());
206 * Print what's left in memory
208 dumpFacts(kieSession);
213 * This method will start a kie session and instantiate the Policy Engine.
215 * @param droolsTemplate the DRL rules file
216 * @param yamlFile the yaml file containing the policies
217 * @param policyScope scope for policy
218 * @param policyName name of the policy
219 * @param policyVersion version of the policy
220 * @return the kieSession to be used to insert facts
221 * @throws IOException
223 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
224 String policyName, String policyVersion) throws IOException {
227 * Load policies from yaml
229 pair = Util.loadYaml(yamlFile);
231 assertNotNull(pair.a);
232 assertNotNull(pair.a.getControlLoop());
233 assertNotNull(pair.a.getControlLoop().getControlLoopName());
234 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
237 * Construct a kie session
239 final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(),
240 policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8"));
243 * Retrieve the Policy Engine
246 logger.debug("============");
247 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
248 logger.debug("============");
256 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
259 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
261 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
265 if ("POLICY-CL-MGT".equals(topic)) {
266 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
267 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
268 } else if ("APPC-LCM-READ".equals(topic)) {
269 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
270 org.onap.policy.appclcm.LcmRequestWrapper.class);
273 if (obj instanceof VirtualControlLoopNotification) {
274 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
275 String policyName = notification.getPolicyName();
276 if (policyName.endsWith("EVENT")) {
277 logger.debug("Rule Fired: " + notification.getPolicyName());
278 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
279 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
280 logger.debug("Rule Fired: " + notification.getPolicyName());
281 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
282 assertNotNull(notification.getMessage());
283 assertTrue(notification.getMessage().startsWith("Sending guard query"));
284 } else if (policyName.endsWith("GUARD.RESPONSE")) {
285 logger.debug("Rule Fired: " + notification.getPolicyName());
286 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
287 assertNotNull(notification.getMessage());
288 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
289 } else if (policyName.endsWith("GUARD_PERMITTED")) {
290 logger.debug("Rule Fired: " + notification.getPolicyName());
291 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
292 assertNotNull(notification.getMessage());
293 assertTrue(notification.getMessage().startsWith("actor=APPC"));
294 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
295 logger.debug("Rule Fired: " + notification.getPolicyName());
297 logger.debug("The operation timed out");
298 fail("Operation Timed Out");
299 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
300 logger.debug("Rule Fired: " + notification.getPolicyName());
301 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
302 assertNotNull(notification.getMessage());
303 assertTrue(notification.getMessage().startsWith("actor=APPC"));
304 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
305 } else if (policyName.endsWith("EVENT.MANAGER")) {
306 logger.debug("Rule Fired: " + notification.getPolicyName());
307 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
308 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
311 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
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"));
327 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
329 logger.debug("\n============ APPC received the request!!! ===========\n");
332 * Simulate a success response from APPC and insert the response into the working memory
334 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
335 LcmResponse appcResponse = new LcmResponse(appcRequest);
336 appcResponse.getStatus().setCode(400);
337 appcResponse.getStatus().setMessage("AppC success");
338 dmaapResponse.setBody(appcResponse);
339 kieSession.insert(dmaapResponse);
344 * This method is used to simulate event messages from DCAE that start the control loop (onset
345 * message) or end the control loop (abatement message).
347 * @param policy the controlLoopName comes from the policy
348 * @param requestID the requestId for this event
349 * @param status could be onset or abated
351 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
352 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
353 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
354 event.setRequestId(requestID);
355 event.setTarget("generic-vnf.vnf-name");
356 event.setClosedLoopAlarmStart(Instant.now());
357 event.setAai(new HashMap<>());
358 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
359 event.setClosedLoopEventStatus(status);
360 kieSession.insert(event);
363 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfName,
364 boolean isEnriched) {
365 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
366 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
367 event.setRequestId(requestID);
368 event.setTarget("generic-vnf.vnf-name");
369 event.setTargetType(ControlLoopTargetType.VNF);
370 event.setClosedLoopAlarmStart(Instant.now());
371 event.setAai(new HashMap<>());
372 event.getAai().put("generic-vnf.vnf-name", vnfName);
374 event.getAai().put("generic-vnf.in-maint", "false");
375 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
376 event.getAai().put("generic-vnf.orchestration-status", "Created");
377 event.getAai().put("generic-vnf.prov-status", "PREPROV");
378 event.getAai().put("generic-vnf.resource-version", "1");
379 event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
380 event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
381 event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
383 event.setClosedLoopEventStatus(status);
384 kieSession.insert(event);
388 * This method will dump all the facts in the working memory.
390 * @param kieSession the session containing the facts
392 public void dumpFacts(KieSession kieSession) {
393 logger.debug("Fact Count: {}", kieSession.getFactCount());
394 for (FactHandle handle : kieSession.getFactHandles()) {
395 logger.debug("FACT: {}", handle);