cef39b5e8aa0978167832a5bae0ad503cf5662d6
[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 KieSession kieSession;
68     private 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     @AfterClass
102     public static void tearDownSimulator() {
103         HttpServletServer.factory.destroy();
104         PolicyEngine.manager.shutdown();
105     }
106     
107     @Test
108     public void successTest() {
109         
110         /*
111          * Start the kie session
112          */
113         try {
114             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
115                         "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
116                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
117                         "CL_vFW", 
118                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
119         } catch (IOException e) {
120             e.printStackTrace();
121             logger.debug("Could not create kieSession");
122             fail("Could not create kieSession");
123         }
124         
125         /*
126          * Allows the PolicyEngine to callback to this object to
127          * notify that there is an event ready to be pulled 
128          * from the queue
129          */
130         for (TopicSink sink : noopTopics) {
131             assertTrue(sink.start());
132             sink.register(this);
133         }
134         
135         /*
136          * Create a unique requestId
137          */
138         requestID = UUID.randomUUID();
139         
140         /* 
141          * Simulate an onset event the policy engine will 
142          * receive from DCAE to kick off processing through
143          * the rules
144          */
145         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
146         
147         try {
148                 kieSession.fireUntilHalt();
149         }
150         catch (Exception e) {
151                 e.printStackTrace();
152                 logger.warn(e.toString());
153                 fail("fail");
154         }
155         
156         
157         /*
158          * The only fact in memory should be Params
159          */
160         assertEquals(1, kieSession.getFactCount());
161         
162         /*
163          * Print what's left in memory
164          */
165         dumpFacts(kieSession);
166         
167         /*
168          * Gracefully shut down the kie session
169          */
170         kieSession.dispose();
171     }
172     
173     /**
174      * This method will start a kie session and instantiate 
175      * the Policy Engine.
176      * 
177      * @param droolsTemplate
178      *          the DRL rules file
179      * @param yamlFile
180      *          the yaml file containing the policies
181      * @param policyScope
182      *          scope for policy
183      * @param policyName
184      *          name of the policy
185      * @param policyVersion
186      *          version of the policy          
187      * @return the kieSession to be used to insert facts 
188      * @throws IOException
189      */
190     private KieSession startSession(String droolsTemplate, 
191             String yamlFile, 
192             String policyScope, 
193             String policyName, 
194             String policyVersion) throws IOException {
195         
196         /*
197          * Load policies from yaml
198          */
199         pair = Util.loadYaml(yamlFile);
200         assertNotNull(pair);
201         assertNotNull(pair.a);
202         assertNotNull(pair.a.getControlLoop());
203         assertNotNull(pair.a.getControlLoop().getControlLoopName());
204         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
205         
206         /* 
207          * Construct a kie session
208          */
209         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
210                 pair.a.getControlLoop().getControlLoopName(), 
211                 policyScope, 
212                 policyName, 
213                 policyVersion, 
214                 URLEncoder.encode(pair.b, "UTF-8"));
215         
216         /*
217          * Retrieve the Policy Engine
218          */
219         
220         logger.debug("============");
221         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
222         logger.debug("============");
223         
224         return kieSession;
225     }
226     
227     /*
228      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
229      */
230     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
231         /*
232          * Pull the object that was sent out to DMAAP and make
233          * sure it is a ControlLoopNoticiation of type active
234          */
235         Object obj = null;
236         if ("POLICY-CL-MGT".equals(topic)) {
237                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
238         }
239         else if ("APPC-CL".equals(topic))
240                 obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, org.onap.policy.appc.Request.class);
241         assertNotNull(obj);
242         if (obj instanceof VirtualControlLoopNotification) {
243             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
244             String policyName = notification.policyName;
245             if (policyName.endsWith("EVENT")) {
246                 logger.debug("Rule Fired: " + notification.policyName);
247                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
248             }
249             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
250                 logger.debug("Rule Fired: " + notification.policyName);
251                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
252                 assertNotNull(notification.message);
253                 assertTrue(notification.message.startsWith("Sending guard query"));
254             }
255             else if (policyName.endsWith("GUARD.RESPONSE")) {
256                 logger.debug("Rule Fired: " + notification.policyName);
257                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
258                 assertNotNull(notification.message);
259                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
260             }
261             else if (policyName.endsWith("GUARD_PERMITTED")) {
262                 logger.debug("Rule Fired: " + notification.policyName);
263                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
264                 assertNotNull(notification.message);
265                 assertTrue(notification.message.startsWith("actor=APPC"));
266             }
267             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
268                 logger.debug("Rule Fired: " + notification.policyName);
269                 kieSession.halt();
270                 logger.debug("The operation timed out");
271                 fail("Operation Timed Out");
272             }
273             else if (policyName.endsWith("APPC.RESPONSE")) {
274                 logger.debug("Rule Fired: " + notification.policyName);
275                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
276                 assertNotNull(notification.message);
277                 assertTrue(notification.message.startsWith("actor=APPC"));
278                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
279             }
280             else if (policyName.endsWith("EVENT.MANAGER")) {
281                 logger.debug("Rule Fired: " + notification.policyName);
282                 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
283                 kieSession.halt();
284             }
285             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
286                 logger.debug("Rule Fired: " + notification.policyName);
287                 kieSession.halt();
288                 logger.debug("The control loop timed out");
289                 fail("Control Loop Timed Out");
290             }
291         }
292         else if (obj instanceof Request) {
293             assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
294             
295             logger.debug("\n============ APPC received the request!!! ===========\n");
296             
297             /*
298              * Simulate a success response from APPC and insert
299              * the response into the working memory
300              */
301             Response appcResponse = new Response((Request)obj);
302             appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
303             appcResponse.getStatus().Value = "SUCCESS";
304             kieSession.insert(appcResponse);
305         }        
306     }
307     
308     /**
309      * This method is used to simulate event messages from DCAE
310      * that start the control loop (onset message) or end the
311      * control loop (abatement message).
312      * 
313      * @param policy the controlLoopName comes from the policy 
314      * @param requestID the requestId for this event
315      * @param status could be onset or abated
316      */
317     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
318         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
319         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
320         event.requestID = requestID;
321         event.target = "generic-vnf.vnf-id";
322         event.closedLoopAlarmStart = Instant.now();
323         event.AAI = new HashMap<>();
324         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
325         event.closedLoopEventStatus = status;
326         kieSession.insert(event);
327     }
328     
329     /**
330      * This method will dump all the facts in the working memory.
331      * 
332      * @param kieSession the session containing the facts
333      */
334     public void dumpFacts(KieSession kieSession) {
335         logger.debug("Fact Count: {}", kieSession.getFactCount());
336         for (FactHandle handle : kieSession.getFactHandles()) {
337             logger.debug("FACT: {}", handle);
338         }
339     }
340 }