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