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.EventProtocolParams;
59 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
60 import org.onap.policy.drools.system.PolicyController;
61 import org.onap.policy.drools.system.PolicyEngine;
62 import org.onap.policy.drools.utils.logging.LoggerUtil;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 public class VcpeControlLoopTest implements TopicListener {
68 private static final Logger logger = LoggerFactory.getLogger(VcpeControlLoopTest.class);
70 private static List<? extends TopicSink> noopTopics;
72 private static KieSession kieSession;
73 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
74 private UUID requestId;
77 /* Set environment properties */
78 SupportUtil.setAaiProps();
79 SupportUtil.setGuardProps();
80 SupportUtil.setPuProp();
81 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
85 * Setup the simulator.
88 public static void setUpSimulator() {
89 PolicyEngine.manager.configure(new Properties());
90 assertTrue(PolicyEngine.manager.start());
91 Properties noopSinkProperties = new Properties();
92 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
93 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
94 noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
95 "org.onap.policy.appclcm.util.Serialization,gson");
96 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
97 "org.onap.policy.controlloop.VirtualControlLoopNotification");
98 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
99 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
100 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
102 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
103 .groupId("junit.groupId")
104 .artifactId("junit.artifactId")
105 .topic("POLICY-CL-MGT")
106 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
107 .protocolFilter(new JsonProtocolFilter())
108 .customGsonCoder(null)
109 .customJacksonCoder(null)
110 .modelClassLoaderHash(1111));
111 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
112 .groupId("junit.groupId")
113 .artifactId("junit.artifactId")
114 .topic("APPC-LCM-READ")
115 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
116 .protocolFilter(new JsonProtocolFilter())
117 .customGsonCoder(null)
118 .customJacksonCoder(null)
119 .modelClassLoaderHash(1111));
121 SupportUtil.buildAaiSim();
122 SupportUtil.buildGuardSim();
123 } catch (Exception e) {
124 fail(e.getMessage());
127 * Start the kie session
130 kieSession = startSession(
131 "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
132 + "/src/main/resources/__closedLoopControlName__.drl",
133 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
134 "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
135 "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
136 } catch (IOException e) {
138 logger.debug("Could not create kieSession");
139 fail("Could not create kieSession");
144 * Tear down the simulator.
147 public static void tearDownSimulator() {
149 * Gracefully shut down the kie session
151 kieSession.dispose();
153 PolicyEngine.manager.stop();
154 HttpServletServer.factory.destroy();
155 PolicyController.factory.shutdown();
156 TopicEndpoint.manager.shutdown();
160 public void successTest() {
163 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
164 * to be pulled from the queue
166 for (TopicSink sink : noopTopics) {
167 assertTrue(sink.start());
172 * Create a unique requestId
174 requestId = UUID.randomUUID();
177 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
180 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
182 kieSession.fireUntilHalt();
184 // allow object clean-up
185 kieSession.fireAllRules();
188 * The only fact in memory should be Params
190 assertEquals(1, kieSession.getFactCount());
193 * Print what's left in memory
195 dumpFacts(kieSession);
199 public void aaiGetFailTest() {
202 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
203 * to be pulled from the queue
205 for (TopicSink sink : noopTopics) {
206 assertTrue(sink.start());
211 * Create a unique requestId
213 requestId = UUID.randomUUID();
216 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
219 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false);
222 kieSession.fireUntilHalt();
224 // allow object clean-up
225 kieSession.fireAllRules();
228 * The only fact in memory should be Params
230 assertEquals(1, kieSession.getFactCount());
233 * Print what's left in memory
235 dumpFacts(kieSession);
240 * This method will start a kie session and instantiate the Policy Engine.
242 * @param droolsTemplate the DRL rules file
243 * @param yamlFile the yaml file containing the policies
244 * @param policyScope scope for policy
245 * @param policyName name of the policy
246 * @param policyVersion version of the policy
247 * @return the kieSession to be used to insert facts
248 * @throws IOException IO exception
250 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
251 String policyName, String policyVersion) throws IOException {
254 * Load policies from yaml
256 pair = SupportUtil.loadYaml(yamlFile);
258 assertNotNull(pair.first);
259 assertNotNull(pair.first.getControlLoop());
260 assertNotNull(pair.first.getControlLoop().getControlLoopName());
261 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
264 * Construct a kie session
266 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
267 pair.first.getControlLoop().getControlLoopName(),
268 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
271 * Retrieve the Policy Engine
274 logger.debug("============");
275 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
276 logger.debug("============");
284 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
287 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
289 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
293 if ("POLICY-CL-MGT".equals(topic)) {
294 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
295 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
296 } else if ("APPC-LCM-READ".equals(topic)) {
297 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
298 org.onap.policy.appclcm.LcmRequestWrapper.class);
301 if (obj instanceof VirtualControlLoopNotification) {
302 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
303 String policyName = notification.getPolicyName();
304 if (policyName.endsWith("EVENT")) {
305 logger.debug("Rule Fired: " + notification.getPolicyName());
306 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
307 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
308 logger.debug("Rule Fired: " + notification.getPolicyName());
309 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
310 assertNotNull(notification.getMessage());
311 assertTrue(notification.getMessage().startsWith("Sending guard query"));
312 } else if (policyName.endsWith("GUARD.RESPONSE")) {
313 logger.debug("Rule Fired: " + notification.getPolicyName());
314 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
315 assertNotNull(notification.getMessage());
316 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
317 } else if (policyName.endsWith("GUARD_PERMITTED")) {
318 logger.debug("Rule Fired: " + notification.getPolicyName());
319 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
320 assertNotNull(notification.getMessage());
321 assertTrue(notification.getMessage().startsWith("actor=APPC"));
322 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
323 logger.debug("Rule Fired: " + notification.getPolicyName());
325 logger.debug("The operation timed out");
326 fail("Operation Timed Out");
327 } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
328 logger.debug("Rule Fired: " + notification.getPolicyName());
329 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
330 assertNotNull(notification.getMessage());
331 assertTrue(notification.getMessage().startsWith("actor=APPC"));
332 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
333 } else if (policyName.endsWith("EVENT.MANAGER")) {
334 logger.debug("Rule Fired: " + notification.getPolicyName());
335 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
336 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
339 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
342 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
343 logger.debug("Rule Fired: " + notification.getPolicyName());
345 logger.debug("The control loop timed out");
346 fail("Control Loop Timed Out");
348 } else if (obj instanceof LcmRequestWrapper) {
350 * The request should be of type LcmRequestWrapper and the subrequestid should be 1
352 LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
353 LcmRequest appcRequest = dmaapRequest.getBody();
354 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
355 assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
357 logger.debug("\n============ APPC received the request!!! ===========\n");
360 * Simulate a success response from APPC and insert the response into the working memory
362 LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
363 LcmResponse appcResponse = new LcmResponse(appcRequest);
364 appcResponse.getStatus().setCode(400);
365 appcResponse.getStatus().setMessage("AppC success");
366 dmaapResponse.setBody(appcResponse);
367 kieSession.insert(dmaapResponse);
372 * This method is used to simulate event messages from DCAE that start the control loop (onset
373 * message) or end the control loop (abatement message).
375 * @param policy the controlLoopName comes from the policy
376 * @param requestId the requestId for this event
377 * @param status could be onset or abated
379 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
380 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
382 event.setRequestId(requestId);
383 event.setTarget("generic-vnf.vnf-name");
384 event.setClosedLoopAlarmStart(Instant.now());
385 event.setAai(new HashMap<>());
386 event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName");
387 event.setClosedLoopEventStatus(status);
388 kieSession.insert(event);
391 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName,
392 boolean isEnriched) {
393 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
394 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
395 event.setRequestId(requestId);
396 event.setTarget("generic-vnf.vnf-name");
397 event.setTargetType(ControlLoopTargetType.VNF);
398 event.setClosedLoopAlarmStart(Instant.now());
399 event.setAai(new HashMap<>());
400 event.getAai().put("generic-vnf.vnf-name", vnfName);
402 event.getAai().put("generic-vnf.in-maint", "false");
403 event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
404 event.getAai().put("generic-vnf.orchestration-status", "Created");
405 event.getAai().put("generic-vnf.prov-status", "ACTIVE");
406 event.getAai().put("generic-vnf.resource-version", "1");
407 event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
408 event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
409 event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
411 event.setClosedLoopEventStatus(status);
412 kieSession.insert(event);
416 * This method will dump all the facts in the working memory.
418 * @param kieSession the session containing the facts
420 public void dumpFacts(KieSession kieSession) {
421 logger.debug("Fact Count: {}", kieSession.getFactCount());
422 for (FactHandle handle : kieSession.getFactHandles()) {
423 logger.debug("FACT: {}", handle);