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