327a1b4dc7e08471ea6cb8bd0d67e250eb0ad09e
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017-2019 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 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.appc.Request;
41 import org.onap.policy.appc.Response;
42 import org.onap.policy.appc.ResponseCode;
43 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
44 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
45 import org.onap.policy.common.endpoints.event.comm.TopicListener;
46 import org.onap.policy.common.endpoints.event.comm.TopicSink;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
48 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
49 import org.onap.policy.controlloop.ControlLoopEventStatus;
50 import org.onap.policy.controlloop.ControlLoopNotificationType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
55 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.system.PolicyController;
58 import org.onap.policy.drools.system.PolicyEngine;
59 import org.onap.policy.drools.utils.logging.LoggerUtil;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class VfwControlLoopTest implements TopicListener {
64
65     private static final Logger logger = LoggerFactory.getLogger(VfwControlLoopTest.class);
66
67     private static List<? extends TopicSink> noopTopics;
68
69     private static KieSession kieSession;
70     private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
71     private UUID requestId;
72
73     static {
74         /* Set environment properties */
75         SupportUtil.setAaiProps();
76         SupportUtil.setGuardProps();
77         SupportUtil.setPuProp();
78         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
79     }
80
81     /**
82      * Setup the simulator.
83      */
84     @BeforeClass
85     public static void setUpSimulator() {
86         PolicyEngine.manager.configure(new Properties());
87         assertTrue(PolicyEngine.manager.start());
88         Properties noopSinkProperties = new Properties();
89         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
90         noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
91         noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
92                 "org.onap.policy.appc.util.Serialization,gsonPretty");
93         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
94                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
95         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
96                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
97         noopTopics = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
98
99         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
100                 .groupId("junit.groupId")
101                 .artifactId("junit.artifactId")
102                 .topic("POLICY-CL-MGT")
103                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
104                 .protocolFilter(new JsonProtocolFilter())
105                 .modelClassLoaderHash(1111));
106         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
107                 .groupId("junit.groupId")
108                 .artifactId("junit.artifactId")
109                 .topic("APPC-CL")
110                 .eventClass("org.onap.policy.appc.Request")
111                 .protocolFilter(new JsonProtocolFilter())
112                 .modelClassLoaderHash(1111));
113
114         try {
115             SupportUtil.buildAaiSim();
116             SupportUtil.buildGuardSim();
117         } catch (Exception e) {
118             fail(e.getMessage());
119         }
120
121         /*
122          * Start the kie session
123          */
124         try {
125             kieSession = startSession(
126                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/"
127                     + "main/resources/__closedLoopControlName__.drl",
128                     "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
129                     "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW",
130                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
131         } catch (IOException e) {
132             e.printStackTrace();
133             logger.debug("Could not create kieSession");
134             fail("Could not create kieSession");
135         }
136     }
137
138     /**
139      * Tear down the simulator.
140      */
141     @AfterClass
142     public static void tearDownSimulator() {
143         /*
144          * Gracefully shut down the kie session
145          */
146         kieSession.dispose();
147
148         PolicyEngine.manager.stop();
149         HttpServletServerFactoryInstance.getServerFactory().destroy();
150         PolicyController.factory.shutdown();
151         TopicEndpointManager.getManager().shutdown();
152     }
153
154     @Test
155     public void successTest() {
156
157         /*
158          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
159          * to be pulled from the queue
160          */
161         for (TopicSink sink : noopTopics) {
162             assertTrue(sink.start());
163             sink.register(this);
164         }
165
166         /*
167          * Create a unique requestId
168          */
169         requestId = UUID.randomUUID();
170
171         /*
172          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
173          * through the rules
174          */
175         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
176
177         try {
178             kieSession.fireUntilHalt();
179
180             // allow object clean-up
181             kieSession.fireAllRules();
182
183         } catch (Exception e) {
184             e.printStackTrace();
185             logger.warn(e.toString());
186             fail("fail");
187         }
188
189
190         /*
191          * The only fact in memory should be Params
192          */
193         assertEquals(1, kieSession.getFactCount());
194
195         /*
196          * Print what's left in memory
197          */
198         dumpFacts(kieSession);
199     }
200
201     @Test
202     public void aaiFailTests() {
203
204         /*
205          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
206          * to be pulled from the queue
207          */
208         for (TopicSink sink : noopTopics) {
209             assertTrue(sink.start());
210             sink.register(this);
211         }
212
213         /*
214          * Create a unique requestId
215          */
216         requestId = UUID.randomUUID();
217
218         /*
219          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
220          * through the rules
221          */
222         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
223         try {
224             kieSession.fireUntilHalt();
225
226             // allow object clean-up
227             kieSession.fireAllRules();
228
229         } catch (Exception e) {
230             e.printStackTrace();
231             logger.warn(e.toString());
232             fail(e.getMessage());
233         }
234
235         /*
236          * The only fact in memory should be Params
237          */
238         assertEquals(1, kieSession.getFactCount());
239
240         /*
241          * Print what's left in memory
242          */
243         dumpFacts(kieSession);
244
245         /*
246          * Create a unique requestId
247          */
248         requestId = UUID.randomUUID();
249
250         /*
251          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
252          * through the rules
253          */
254
255         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
256
257         try {
258             kieSession.fireUntilHalt();
259
260             // allow object clean-up
261             kieSession.fireAllRules();
262
263         } catch (Exception e) {
264             e.printStackTrace();
265             logger.warn(e.toString());
266             fail(e.getMessage());
267         }
268
269         /*
270          * The only fact in memory should be Params
271          */
272         assertEquals(1, kieSession.getFactCount());
273
274         /*
275          * Print what's left in memory
276          */
277         dumpFacts(kieSession);
278     }
279
280     /**
281      * This method will start a kie session and instantiate the Policy Engine.
282      *
283      * @param droolsTemplate the DRL rules file
284      * @param yamlFile the yaml file containing the policies
285      * @param policyScope scope for policy
286      * @param policyName name of the policy
287      * @param policyVersion version of the policy
288      * @return the kieSession to be used to insert facts
289      * @throws IOException IO Exception
290      */
291     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
292             String policyName, String policyVersion) throws IOException {
293
294         /*
295          * Load policies from yaml
296          */
297         pair = SupportUtil.loadYaml(yamlFile);
298         assertNotNull(pair);
299         assertNotNull(pair.first);
300         assertNotNull(pair.first.getControlLoop());
301         assertNotNull(pair.first.getControlLoop().getControlLoopName());
302         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
303
304         /*
305          * Construct a kie session
306          */
307         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
308                 pair.first.getControlLoop().getControlLoopName(),
309                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
310
311         /*
312          * Retrieve the Policy Engine
313          */
314
315         logger.debug("============");
316         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
317         logger.debug("============");
318
319         return kieSession;
320     }
321
322     /*
323      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
324      */
325     @Override
326     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
327         /*
328          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
329          * of type active
330          */
331         Object obj = null;
332         if ("POLICY-CL-MGT".equals(topic)) {
333             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
334                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
335         } else if ("APPC-CL".equals(topic)) {
336             obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event,
337                     org.onap.policy.appc.Request.class);
338         }
339         assertNotNull(obj);
340         if (obj instanceof VirtualControlLoopNotification) {
341             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
342             String policyName = notification.getPolicyName();
343             if (policyName.endsWith("EVENT")) {
344                 logger.debug("Rule Fired: " + notification.getPolicyName());
345                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
346             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
347                 logger.debug("Rule Fired: " + notification.getPolicyName());
348                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
349                 assertNotNull(notification.getMessage());
350                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
351             } else if (policyName.endsWith("GUARD.RESPONSE")) {
352                 logger.debug("Rule Fired: " + notification.getPolicyName());
353                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
354                 assertNotNull(notification.getMessage());
355                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
356             } else if (policyName.endsWith("GUARD_PERMITTED")) {
357                 logger.debug("Rule Fired: " + notification.getPolicyName());
358                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
359                 assertNotNull(notification.getMessage());
360                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
361             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
362                 logger.debug("Rule Fired: " + notification.getPolicyName());
363                 kieSession.halt();
364                 logger.debug("The operation timed out");
365                 fail("Operation Timed Out");
366             } else if (policyName.endsWith("APPC.RESPONSE")) {
367                 logger.debug("Rule Fired: " + notification.getPolicyName());
368                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
369                 assertNotNull(notification.getMessage());
370                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
371                 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
372             } else if (policyName.endsWith("EVENT.MANAGER")) {
373                 logger.debug("Rule Fired: " + notification.getPolicyName());
374                 if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
375                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
376                     assertEquals("Target vnf-id could not be found", notification.getMessage());
377                 } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
378                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
379                 } else {
380                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
381                 }
382                 kieSession.halt();
383             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
384                 logger.debug("Rule Fired: " + notification.getPolicyName());
385                 kieSession.halt();
386                 logger.debug("The control loop timed out");
387                 fail("Control Loop Timed Out");
388             }
389         } else if (obj instanceof Request) {
390             assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1"));
391             assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id"));
392
393             logger.debug("\n============ APPC received the request!!! ===========\n");
394
395             /*
396              * Simulate a success response from APPC and insert the response into the working memory
397              */
398             Response appcResponse = new Response((Request) obj);
399             appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
400             appcResponse.getStatus().setValue("SUCCESS");
401             kieSession.insert(appcResponse);
402         }
403     }
404
405     /**
406      * This method is used to simulate event messages from DCAE that start the control loop (onset
407      * message) or end the control loop (abatement message).
408      *
409      * @param policy the controlLoopName comes from the policy
410      * @param requestId the requestId for this event
411      * @param status could be onset or abated
412      */
413     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
414         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
415         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
416         event.setRequestId(requestId);
417         event.setTarget("generic-vnf.vnf-name");
418         event.setClosedLoopAlarmStart(Instant.now());
419         event.setAai(new HashMap<>());
420         event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
421         event.setClosedLoopEventStatus(status);
422         kieSession.insert(event);
423     }
424
425     /**
426      * This method is used to simulate event messages from DCAE that start the control loop (onset
427      * message) or end the control loop (abatement message).
428      *
429      * @param policy the controlLoopName comes from the policy
430      * @param requestId the requestId for this event
431      * @param status could be onset or abated
432      */
433     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) {
434         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
435         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
436         event.setRequestId(requestId);
437         event.setTarget("generic-vnf.vnf-name");
438         event.setClosedLoopAlarmStart(Instant.now());
439         event.setAai(new HashMap<>());
440         event.getAai().put("generic-vnf.vnf-name", vnfId);
441         event.setClosedLoopEventStatus(status);
442         kieSession.insert(event);
443     }
444
445     /**
446      * This method will dump all the facts in the working memory.
447      *
448      * @param kieSession the session containing the facts
449      */
450     public void dumpFacts(KieSession kieSession) {
451         logger.debug("Fact Count: {}", kieSession.getFactCount());
452         for (FactHandle handle : kieSession.getFactHandles()) {
453             logger.debug("FACT: {}", handle);
454         }
455     }
456 }