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