19c33ace303cd0780be633e8baaaecbfc061df94
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
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;
27
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
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;
64
65 public class VCPEControlLoopTest implements TopicListener {
66
67     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
68
69     private static List<? extends TopicSink> noopTopics;
70
71     private static KieSession kieSession;
72     private static Util.Pair<ControlLoopPolicy, String> pair;
73     private UUID requestID;
74
75     static {
76         /* Set environment properties */
77         Util.setAAIProps();
78         Util.setGuardProps();
79         Util.setPUProp();
80         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
81     }
82
83     @BeforeClass
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);
97
98         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
99                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
100                 1111);
101         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
102                 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
103         try {
104             Util.buildAaiSim();
105             Util.buildGuardSim();
106         } catch (Exception e) {
107             fail(e.getMessage());
108         }
109         /*
110          * Start the kie session
111          */
112         try {
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) {
119             e.printStackTrace();
120             logger.debug("Could not create kieSession");
121             fail("Could not create kieSession");
122         }
123     }
124
125     @AfterClass
126     public static void tearDownSimulator() {
127         /*
128          * Gracefully shut down the kie session
129          */
130         kieSession.dispose();
131
132         PolicyEngine.manager.stop();
133         HttpServletServer.factory.destroy();
134         PolicyController.factory.shutdown();
135         TopicEndpoint.manager.shutdown();
136     }
137
138     @Test
139     public void successTest() {
140
141         /*
142          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
143          * to be pulled from the queue
144          */
145         for (TopicSink sink : noopTopics) {
146             assertTrue(sink.start());
147             sink.register(this);
148         }
149
150         /*
151          * Create a unique requestId
152          */
153         requestID = UUID.randomUUID();
154
155         /*
156          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
157          * through the rules
158          */
159         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
160
161         kieSession.fireUntilHalt();
162
163         /*
164          * The only fact in memory should be Params
165          */
166         assertEquals(1, kieSession.getFactCount());
167
168         /*
169          * Print what's left in memory
170          */
171         dumpFacts(kieSession);
172     }
173
174     @Test
175     public void aaiGetFailTest() {
176
177         /*
178          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
179          * to be pulled from the queue
180          */
181         for (TopicSink sink : noopTopics) {
182             assertTrue(sink.start());
183             sink.register(this);
184         }
185
186         /*
187          * Create a unique requestId
188          */
189         requestID = UUID.randomUUID();
190
191         /*
192          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
193          * through the rules
194          */
195         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false);
196
197
198         kieSession.fireUntilHalt();
199
200         /*
201          * The only fact in memory should be Params
202          */
203         assertEquals(1, kieSession.getFactCount());
204
205         /*
206          * Print what's left in memory
207          */
208         dumpFacts(kieSession);
209
210     }
211
212     /**
213      * This method will start a kie session and instantiate the Policy Engine.
214      * 
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
222      */
223     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
224             String policyName, String policyVersion) throws IOException {
225
226         /*
227          * Load policies from yaml
228          */
229         pair = Util.loadYaml(yamlFile);
230         assertNotNull(pair);
231         assertNotNull(pair.a);
232         assertNotNull(pair.a.getControlLoop());
233         assertNotNull(pair.a.getControlLoop().getControlLoopName());
234         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
235
236         /*
237          * Construct a kie session
238          */
239         final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(),
240                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8"));
241
242         /*
243          * Retrieve the Policy Engine
244          */
245
246         logger.debug("============");
247         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
248         logger.debug("============");
249
250         return kieSession;
251     }
252
253     /*
254      * (non-Javadoc)
255      * 
256      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
257      */
258     @Override
259     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
260         /*
261          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
262          * of type active
263          */
264         Object obj = null;
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);
271         }
272         assertNotNull(obj);
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());
296                 kieSession.halt();
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());
309                     kieSession.halt();
310                 } else {
311                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
312                     kieSession.halt();
313                 }
314             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
315                 logger.debug("Rule Fired: " + notification.getPolicyName());
316                 kieSession.halt();
317                 logger.debug("The control loop timed out");
318                 fail("Control Loop Timed Out");
319             }
320         } else if (obj instanceof LcmRequestWrapper) {
321             /*
322              * The request should be of type LcmRequestWrapper and the subrequestid should be 1
323              */
324             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
325             LcmRequest appcRequest = dmaapRequest.getBody();
326             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
327             assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
328
329             logger.debug("\n============ APPC received the request!!! ===========\n");
330
331             /*
332              * Simulate a success response from APPC and insert the response into the working memory
333              */
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);
340         }
341     }
342
343     /**
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).
346      * 
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
350      */
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);
361     }
362
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);
373         if (isEnriched) {
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");
382         }
383         event.setClosedLoopEventStatus(status);
384         kieSession.insert(event);
385     }
386
387     /**
388      * This method will dump all the facts in the working memory.
389      * 
390      * @param kieSession the session containing the facts
391      */
392     public void dumpFacts(KieSession kieSession) {
393         logger.debug("Fact Count: {}", kieSession.getFactCount());
394         for (FactHandle handle : kieSession.getFactHandles()) {
395             logger.debug("FACT: {}", handle);
396         }
397     }
398
399 }