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();
171 * The only fact in memory should be Params
173 assertEquals(1, kieSession.getFactCount());
176 * Print what's left in memory
178 dumpFacts(kieSession);
182 public void aaiGetFailTest() {
185 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
186 * to be pulled from the queue
188 for (TopicSink sink : noopTopics) {
189 assertTrue(sink.start());
194 * Create a unique requestId
196 requestId = UUID.randomUUID();
199 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
202 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false);
205 kieSession.fireUntilHalt();
208 * The only fact in memory should be Params
210 assertEquals(1, kieSession.getFactCount());
213 * Print what's left in memory
215 dumpFacts(kieSession);
220 * This method will start a kie session and instantiate the Policy Engine.
222 * @param droolsTemplate the DRL rules file
223 * @param yamlFile the yaml file containing the policies
224 * @param policyScope scope for policy
225 * @param policyName name of the policy
226 * @param policyVersion version of the policy
227 * @return the kieSession to be used to insert facts
228 * @throws IOException IO exception
230 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
231 String policyName, String policyVersion) throws IOException {
234 * Load policies from yaml
236 pair = Util.loadYaml(yamlFile);
238 assertNotNull(pair.first);
239 assertNotNull(pair.first.getControlLoop());
240 assertNotNull(pair.first.getControlLoop().getControlLoopName());
241 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
244 * Construct a kie session
246 final KieSession kieSession = Util.buildContainer(droolsTemplate,
247 pair.first.getControlLoop().getControlLoopName(),
248 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
251 * Retrieve the Policy Engine
254 logger.debug("============");
255 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
256 logger.debug("============");
264 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
267 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
269 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
273 if ("POLICY-CL-MGT".equals(topic)) {
274 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
275 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
276 } else if ("APPC-LCM-READ".equals(topic)) {
277 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
278 org.onap.policy.appclcm.LcmRequestWrapper.class);
281 if (obj instanceof VirtualControlLoopNotification) {
282 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
283 String policyName = notification.getPolicyName();
284 if (policyName.endsWith("EVENT")) {
285 logger.debug("Rule Fired: " + notification.getPolicyName());
286 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
287 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
288 logger.debug("Rule Fired: " + notification.getPolicyName());
289 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
290 assertNotNull(notification.getMessage());
291 assertTrue(notification.getMessage().startsWith("Sending guard query"));
292 } else if (policyName.endsWith("GUARD.RESPONSE")) {
293 logger.debug("Rule Fired: " + notification.getPolicyName());
294 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
295 assertNotNull(notification.getMessage());
296 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
297 } else if (policyName.endsWith("GUARD_PERMITTED")) {
298 logger.debug("Rule Fired: " + notification.getPolicyName());
299 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
300 assertNotNull(notification.getMessage());
301 assertTrue(notification.getMessage().startsWith("actor=APPC"));
302 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
303 logger.debug("Rule Fired: " + notification.getPolicyName());
305 logger.debug("The operation timed out");
306 fail("Operation Timed Out");
307 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
308 logger.debug("Rule Fired: " + notification.getPolicyName());
309 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
310 assertNotNull(notification.getMessage());
311 assertTrue(notification.getMessage().startsWith("actor=APPC"));
312 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
313 } else if (policyName.endsWith("EVENT.MANAGER")) {
314 logger.debug("Rule Fired: " + notification.getPolicyName());
315 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
316 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
319 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
322 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
323 logger.debug("Rule Fired: " + notification.getPolicyName());
325 logger.debug("The control loop timed out");
326 fail("Control Loop Timed Out");
328 } else if (obj instanceof LcmRequestWrapper) {
330 * The request should be of type LcmRequestWrapper and the subrequestid should be 1
332 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
333 LcmRequest appcRequest = dmaapRequest.getBody();
334 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
335 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
337 logger.debug("\n============ APPC received the request!!! ===========\n");
340 * Simulate a success response from APPC and insert the response into the working memory
342 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
343 LcmResponse appcResponse = new LcmResponse(appcRequest);
344 appcResponse.getStatus().setCode(400);
345 appcResponse.getStatus().setMessage("AppC success");
346 dmaapResponse.setBody(appcResponse);
347 kieSession.insert(dmaapResponse);
352 * This method is used to simulate event messages from DCAE that start the control loop (onset
353 * message) or end the control loop (abatement message).
355 * @param policy the controlLoopName comes from the policy
356 * @param requestID the requestId for this event
357 * @param status could be onset or abated
359 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
360 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
361 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
362 event.setRequestId(requestId);
363 event.setTarget("generic-vnf.vnf-name");
364 event.setClosedLoopAlarmStart(Instant.now());
365 event.setAai(new HashMap<>());
366 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
367 event.setClosedLoopEventStatus(status);
368 kieSession.insert(event);
371 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName,
372 boolean isEnriched) {
373 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
374 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
375 event.setRequestId(requestId);
376 event.setTarget("generic-vnf.vnf-name");
377 event.setTargetType(ControlLoopTargetType.VNF);
378 event.setClosedLoopAlarmStart(Instant.now());
379 event.setAai(new HashMap<>());
380 event.getAai().put("generic-vnf.vnf-name", vnfName);
382 event.getAai().put("generic-vnf.in-maint", "false");
383 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
384 event.getAai().put("generic-vnf.orchestration-status", "Created");
385 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
386 event.getAai().put("generic-vnf.resource-version", "1");
387 event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
388 event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
389 event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
391 event.setClosedLoopEventStatus(status);
392 kieSession.insert(event);
396 * This method will dump all the facts in the working memory.
398 * @param kieSession the session containing the facts
400 public void dumpFacts(KieSession kieSession) {
401 logger.debug("Fact Count: {}", kieSession.getFactCount());
402 for (FactHandle handle : kieSession.getFactHandles()) {
403 logger.debug("FACT: {}", handle);