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