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