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