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