9b3fbfe72e64ad77c552b0421c63151f49af00c3
[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.*;
24
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Properties;
31 import java.util.UUID;
32
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.kie.api.runtime.KieSession;
37 import org.kie.api.runtime.rule.FactHandle;
38 import org.onap.policy.appclcm.LCMRequest;
39 import org.onap.policy.appclcm.LCMRequestWrapper;
40 import org.onap.policy.appclcm.LCMResponse;
41 import org.onap.policy.appclcm.LCMResponseWrapper;
42 import org.onap.policy.controlloop.ControlLoopEventStatus;
43 import org.onap.policy.controlloop.ControlLoopNotificationType;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.drools.event.comm.TopicEndpoint;
49 import org.onap.policy.drools.event.comm.TopicListener;
50 import org.onap.policy.drools.event.comm.TopicSink;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.properties.PolicyProperties;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class ControlLoopFailureTest implements TopicListener {
60
61     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
62     
63     private static List<? extends TopicSink> noopTopics;
64     
65     private static KieSession kieSession;
66     private static Util.Pair<ControlLoopPolicy, String> pair;
67     private UUID requestId;
68     private UUID requestId2;
69     private UUID requestId3;
70     private int eventCount;
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-LCM-READ,POLICY-CL-MGT");
85         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
86         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
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-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
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_vCPE.yaml",
106                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
107                         "CL_vCPE", 
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     /**
130      * This test case tests the scenario where 3 events occur
131      * and 2 of the requests refer to the same target entity
132      * while the 3rd is for another entity. The expected result
133      * is that the event with the duplicate target entity will have
134      * a final success result for one of the events, and a rejected
135      * message for the one that was unable to obtain the lock. The
136      * event that is referring to a different target entity should
137      * be able to obtain a lock since it is a different target. After
138      * processing of all events there should only be the params object
139      * left in memory.
140      */
141     @Test
142     public void targetLockedTest() {
143         
144         /*
145          * Allows the PolicyEngine to callback to this object to
146          * notify that there is an event ready to be pulled 
147          * from the queue
148          */
149         for (TopicSink sink : noopTopics) {
150             assertTrue(sink.start());
151             sink.register(this);
152         }
153         
154         /*
155          * Create a unique requestId
156          */
157         requestId = UUID.randomUUID();
158         
159         /*
160          * This will be a unique request for another target entity
161          */
162         requestId2 = UUID.randomUUID();
163         
164         /*
165          * This will be a request duplicating the target entity 
166          * of the first request
167          */
168         requestId3 = UUID.randomUUID();
169         
170         /* 
171          * Simulate an onset event the policy engine will 
172          * receive from DCAE to kick off processing through
173          * the rules
174          */
175         sendEvent(pair.a, requestId, ControlLoopEventStatus.ONSET, "vnf01");
176         
177         /*
178          * Send a second event requesting an action for a different target entity
179          */
180         sendEvent(pair.a, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
181
182         /*
183          * Send a second event for a different target to ensure there
184          * are no problems with obtaining a lock for a different
185          */
186         kieSession.fireUntilHalt();
187         
188         /*
189          * The only fact in memory should be Params
190          */
191         assertEquals(1, kieSession.getFactCount());
192         
193         /*
194          * Print what's left in memory
195          */
196         dumpFacts(kieSession);
197         
198     }
199
200     /**
201      * This method will start a kie session and instantiate 
202      * the Policy Engine.
203      * 
204      * @param droolsTemplate
205      *          the DRL rules file
206      * @param yamlFile
207      *          the yaml file containing the policies
208      * @param policyScope
209      *          scope for policy
210      * @param policyName
211      *          name of the policy
212      * @param policyVersion
213      *          version of the policy          
214      * @return the kieSession to be used to insert facts 
215      * @throws IOException
216      */
217     private static KieSession startSession(String droolsTemplate, 
218             String yamlFile, 
219             String policyScope, 
220             String policyName, 
221             String policyVersion) throws IOException {
222         
223         /*
224          * Load policies from yaml
225          */
226         pair = Util.loadYaml(yamlFile);
227         assertNotNull(pair);
228         assertNotNull(pair.a);
229         assertNotNull(pair.a.getControlLoop());
230         assertNotNull(pair.a.getControlLoop().getControlLoopName());
231         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
232         
233         /* 
234          * Construct a kie session
235          */
236         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
237                 pair.a.getControlLoop().getControlLoopName(), 
238                 policyScope, 
239                 policyName, 
240                 policyVersion, 
241                 URLEncoder.encode(pair.b, "UTF-8"));
242         
243         /*
244          * Retrieve the Policy Engine
245          */
246         
247         logger.debug("============");
248         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
249         logger.debug("============");
250         
251         return kieSession;
252     }
253     
254     /*
255      * (non-Javadoc)
256      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
257      */
258     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
259         /*
260          * Pull the object that was sent out to DMAAP and make
261          * sure it is a ControlLoopNoticiation of type active
262          */
263         Object obj = null;
264         if ("POLICY-CL-MGT".equals(topic)) {
265             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
266         }
267         else if ("APPC-LCM-READ".equals(topic))
268             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
269         assertNotNull(obj);
270         if (obj instanceof VirtualControlLoopNotification) {
271             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
272             String policyName = notification.policyName;
273             if (policyName.endsWith("EVENT")) {
274                 logger.debug("Rule Fired: " + notification.policyName);
275                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
276             }
277             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
278                 logger.debug("Rule Fired: " + notification.policyName);
279                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
280                 assertNotNull(notification.message);
281                 assertTrue(notification.message.startsWith("Sending guard query"));
282             }
283             else if (policyName.endsWith("GUARD.RESPONSE")) {
284                 logger.debug("Rule Fired: " + notification.policyName);
285                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
286                 assertNotNull(notification.message);
287                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
288             }
289             else if (policyName.endsWith("GUARD_PERMITTED")) {
290                 logger.debug("Rule Fired: " + notification.policyName);
291                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
292                 assertNotNull(notification.message);
293                 assertTrue(notification.message.startsWith("actor=APPC"));
294             }
295             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
296                 logger.debug("Rule Fired: " + notification.policyName);
297                 kieSession.halt();
298                 logger.debug("The operation timed out");
299                 fail("Operation Timed Out");
300             }
301             else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
302                 logger.debug("Rule Fired: " + notification.policyName);
303                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
304                 assertNotNull(notification.message);
305                 assertTrue(notification.message.startsWith("actor=APPC"));
306                 if (requestId.equals(notification.requestID)) {
307                     sendEvent(pair.a, requestId, ControlLoopEventStatus.ABATED, "vnf01");
308                 }
309                 else if (requestId2.equals(notification.requestID)) {
310                     sendEvent(pair.a, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
311                 }
312             }
313             else if (policyName.endsWith("EVENT.MANAGER")) {
314                 logger.debug("Rule Fired: " + notification.policyName);
315                 if (requestId3.equals(notification.requestID)) {
316                     /*
317                      * The event with the duplicate target should be rejected
318                      */
319                     assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.notification));
320                 }
321                 else {
322                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
323                 }
324                 if (++eventCount == 3) {
325                     kieSession.halt();
326                 }
327             }
328             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
329                 logger.debug("Rule Fired: " + notification.policyName);
330                 kieSession.halt();
331                 logger.debug("The control loop timed out");
332                 fail("Control Loop Timed Out");
333             }
334         }
335         else if (obj instanceof LCMRequestWrapper) {
336             /*
337              * The request should be of type LCMRequestWrapper
338              * and the subrequestid should be 1
339              */
340             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
341             LCMRequest appcRequest = dmaapRequest.getBody();
342             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
343             
344             logger.debug("\n============ APPC received the request!!! ===========\n");
345             
346             /*
347              * Simulate a success response from APPC and insert
348              * the response into the working memory
349              */
350             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
351             LCMResponse appcResponse = new LCMResponse(appcRequest);
352             appcResponse.getStatus().setCode(400);
353             appcResponse.getStatus().setMessage("AppC success");
354             dmaapResponse.setBody(appcResponse);
355             
356             /*
357              * Interrupting with a different request for the same
358              * target entity to check if lock will be denied
359              */
360             if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
361                 sendEvent(pair.a, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
362             }
363             kieSession.insert(dmaapResponse);
364         }        
365     }
366     
367     /**
368      * This method is used to simulate event messages from DCAE
369      * that start the control loop (onset message) or end the
370      * control loop (abatement message).
371      * 
372      * @param policy the controlLoopName comes from the policy 
373      * @param requestID the requestId for this event
374      * @param status could be onset or abated
375      * @param target, the target entity to take an action on
376      */
377     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, 
378                             ControlLoopEventStatus status, String target) {
379         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
380         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
381         event.requestID = requestID;
382         event.target = "generic-vnf.vnf-id";
383         event.closedLoopAlarmStart = Instant.now();
384         event.AAI = new HashMap<>();
385         event.AAI.put("generic-vnf.vnf-id", target);
386         event.closedLoopEventStatus = status;
387         kieSession.insert(event);
388     }
389     
390     /**
391      * This method will dump all the facts in the working memory.
392      * 
393      * @param kieSession the session containing the facts
394      */
395     public void dumpFacts(KieSession kieSession) {
396         logger.debug("Fact Count: {}", kieSession.getFactCount());
397         for (FactHandle handle : kieSession.getFactHandles()) {
398             logger.debug("FACT: {}", handle);
399         }
400     }
401     
402 }
403