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