01579849154f61342105bfed635b5cc716e86c39
[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.PolicyEngine;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 public class VFWControlLoopTest implements TopicListener {
62
63     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
64     
65     private static List<? extends TopicSink> noopTopics;
66     
67     private static KieSession kieSession;
68     private static Util.Pair<ControlLoopPolicy, String> pair;
69     private UUID requestID;
70     
71     static {
72         /* Set environment properties */
73         Util.setAAIProps();
74         Util.setGuardProps();
75         Util.setPUProp();
76     }
77     
78     @BeforeClass
79     public static void setUpSimulator() {
80         PolicyEngine.manager.configure(new Properties());
81         assertTrue(PolicyEngine.manager.start());
82         Properties noopSinkProperties = new Properties();
83         noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
84         noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
85         noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", "org.onap.policy.appc.util.Serialization,gsonPretty");
86         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
87         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
88         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
89         
90         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
91         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111);
92
93         try {
94             Util.buildAaiSim();
95             Util.buildGuardSim();
96         } catch (Exception e) {
97             fail(e.getMessage());
98         }
99         
100         /*
101          * Start the kie session
102          */
103         try {
104             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
105                         "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
106                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
107                         "CL_vFW", 
108                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
109         } catch (IOException e) {
110             e.printStackTrace();
111             logger.debug("Could not create kieSession");
112             fail("Could not create kieSession");
113         }
114     }
115
116     @AfterClass
117     public static void tearDownSimulator() {
118         /*
119          * Gracefully shut down the kie session
120          */
121         kieSession.dispose();
122         
123         HttpServletServer.factory.destroy();
124         PolicyEngine.manager.shutdown();
125         TopicEndpoint.manager.shutdown();
126         PolicyEngine.manager.stop();
127     }
128     
129     @Test
130     public void successTest() {
131         
132         /*
133          * Allows the PolicyEngine to callback to this object to
134          * notify that there is an event ready to be pulled 
135          * from the queue
136          */
137         for (TopicSink sink : noopTopics) {
138             assertTrue(sink.start());
139             sink.register(this);
140         }
141         
142         /*
143          * Create a unique requestId
144          */
145         requestID = UUID.randomUUID();
146         
147         /* 
148          * Simulate an onset event the policy engine will 
149          * receive from DCAE to kick off processing through
150          * the rules
151          */
152         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
153         
154         try {
155                 kieSession.fireUntilHalt();
156         }
157         catch (Exception e) {
158                 e.printStackTrace();
159                 logger.warn(e.toString());
160                 fail("fail");
161         }
162         
163         
164         /*
165          * The only fact in memory should be Params
166          */
167         assertEquals(1, kieSession.getFactCount());
168         
169         /*
170          * Print what's left in memory
171          */
172         dumpFacts(kieSession);
173     }
174     
175     @Test
176     public void aaiFailTests() {
177         
178         /*
179          * Allows the PolicyEngine to callback to this object to
180          * notify that there is an event ready to be pulled 
181          * from the queue
182          */
183         for (TopicSink sink : noopTopics) {
184             assertTrue(sink.start());
185             sink.register(this);
186         }
187         
188         /*
189          * Create a unique requestId
190          */
191         requestID = UUID.randomUUID();
192         
193         /* 
194          * Simulate an onset event the policy engine will 
195          * receive from DCAE to kick off processing through
196          * the rules
197          */
198         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
199         try {
200                 kieSession.fireUntilHalt();
201         }
202         catch (Exception e) {
203                 e.printStackTrace();
204                 logger.warn(e.toString());
205                 fail(e.getMessage());
206         }
207         
208         /*
209          * The only fact in memory should be Params
210          */
211         assertEquals(1, kieSession.getFactCount());
212         
213         /*
214          * Print what's left in memory
215          */
216         dumpFacts(kieSession);
217         
218         /*
219          * Create a unique requestId
220          */
221         requestID = UUID.randomUUID();
222         
223         /* 
224          * Simulate an onset event the policy engine will 
225          * receive from DCAE to kick off processing through
226          * the rules
227          */
228         
229         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
230         
231         try {
232                 kieSession.fireUntilHalt();
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     /**
252      * This method will start a kie session and instantiate 
253      * the Policy Engine.
254      * 
255      * @param droolsTemplate
256      *          the DRL rules file
257      * @param yamlFile
258      *          the yaml file containing the policies
259      * @param policyScope
260      *          scope for policy
261      * @param policyName
262      *          name of the policy
263      * @param policyVersion
264      *          version of the policy          
265      * @return the kieSession to be used to insert facts 
266      * @throws IOException
267      */
268     private static KieSession startSession(String droolsTemplate, 
269             String yamlFile, 
270             String policyScope, 
271             String policyName, 
272             String policyVersion) throws IOException {
273         
274         /*
275          * Load policies from yaml
276          */
277         pair = Util.loadYaml(yamlFile);
278         assertNotNull(pair);
279         assertNotNull(pair.a);
280         assertNotNull(pair.a.getControlLoop());
281         assertNotNull(pair.a.getControlLoop().getControlLoopName());
282         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
283         
284         /* 
285          * Construct a kie session
286          */
287         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
288                 pair.a.getControlLoop().getControlLoopName(), 
289                 policyScope, 
290                 policyName, 
291                 policyVersion, 
292                 URLEncoder.encode(pair.b, "UTF-8"));
293         
294         /*
295          * Retrieve the Policy Engine
296          */
297         
298         logger.debug("============");
299         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
300         logger.debug("============");
301         
302         return kieSession;
303     }
304     
305     /*
306      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
307      */
308     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
309         /*
310          * Pull the object that was sent out to DMAAP and make
311          * sure it is a ControlLoopNoticiation of type active
312          */
313         Object obj = null;
314         if ("POLICY-CL-MGT".equals(topic)) {
315                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
316         }
317         else if ("APPC-CL".equals(topic))
318                 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
319         assertNotNull(obj);
320         if (obj instanceof VirtualControlLoopNotification) {
321             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
322             String policyName = notification.policyName;
323             if (policyName.endsWith("EVENT")) {
324                 logger.debug("Rule Fired: " + notification.policyName);
325                 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
326                         assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
327                         kieSession.halt();
328                 }
329                 else {
330                     assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
331                 }
332             }
333             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
334                 logger.debug("Rule Fired: " + notification.policyName);
335                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
336                 assertNotNull(notification.message);
337                 assertTrue(notification.message.startsWith("Sending guard query"));
338             }
339             else if (policyName.endsWith("GUARD.RESPONSE")) {
340                 logger.debug("Rule Fired: " + notification.policyName);
341                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
342                 assertNotNull(notification.message);
343                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
344             }
345             else if (policyName.endsWith("GUARD_PERMITTED")) {
346                 logger.debug("Rule Fired: " + notification.policyName);
347                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
348                 assertNotNull(notification.message);
349                 assertTrue(notification.message.startsWith("actor=APPC"));
350             }
351             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
352                 logger.debug("Rule Fired: " + notification.policyName);
353                 kieSession.halt();
354                 logger.debug("The operation timed out");
355                 fail("Operation Timed Out");
356             }
357             else if (policyName.endsWith("APPC.RESPONSE")) {
358                 logger.debug("Rule Fired: " + notification.policyName);
359                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
360                 assertNotNull(notification.message);
361                 assertTrue(notification.message.startsWith("actor=APPC"));
362                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
363             }
364             else if (policyName.endsWith("EVENT.MANAGER")) {
365                 logger.debug("Rule Fired: " + notification.policyName);
366                 if ("error".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
367                         assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
368                         assertEquals("Target vnf-id could not be found", notification.message);
369                 }
370                 else {
371                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
372                 }
373                 kieSession.halt();
374             }
375             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
376                 logger.debug("Rule Fired: " + notification.policyName);
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().SubRequestID.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().Code = ResponseCode.SUCCESS.getValue();
394             appcResponse.getStatus().Value = "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.closedLoopControlName = policy.getControlLoop().getControlLoopName();
411         event.requestID = requestID;
412         event.target = "generic-vnf.vnf-name";
413         event.closedLoopAlarmStart = Instant.now();
414         event.AAI = new HashMap<>();
415         event.AAI.put("generic-vnf.vnf-name", "testGenericVnfID");
416         event.closedLoopEventStatus = 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.closedLoopControlName = policy.getControlLoop().getControlLoopName();
432         event.requestID = requestID;
433         event.target = "generic-vnf.vnf-name";
434         event.closedLoopAlarmStart = Instant.now();
435         event.AAI = new HashMap<>();
436         event.AAI.put("generic-vnf.vnf-name", vnfId);
437         event.closedLoopEventStatus = 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 }