4d8fca83b384139d058d6a0849b20f6893817784
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2018-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.clc;
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 com.google.gson.Gson;
29
30 import java.io.IOException;
31 import java.lang.StringBuilder;
32 import java.net.URLEncoder;
33 import java.time.Instant;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Properties;
37 import java.util.UUID;
38
39 import org.junit.AfterClass;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42
43 import org.kie.api.runtime.KieSession;
44 import org.kie.api.runtime.rule.FactHandle;
45
46 import org.onap.policy.appclcm.LcmRequest;
47 import org.onap.policy.appclcm.LcmRequestWrapper;
48 import org.onap.policy.appclcm.LcmResponse;
49 import org.onap.policy.appclcm.LcmResponseWrapper;
50 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
51 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
52 import org.onap.policy.common.endpoints.event.comm.TopicListener;
53 import org.onap.policy.common.endpoints.event.comm.TopicSink;
54 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
55 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
56 import org.onap.policy.controlloop.ControlLoopEventStatus;
57 import org.onap.policy.controlloop.ControlLoopNotificationType;
58 import org.onap.policy.controlloop.ControlLoopTargetType;
59 import org.onap.policy.controlloop.VirtualControlLoopEvent;
60 import org.onap.policy.controlloop.VirtualControlLoopNotification;
61 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
62 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
63 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
64 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
65 import org.onap.policy.drools.system.PolicyController;
66 import org.onap.policy.drools.system.PolicyEngine;
67
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 public class ControlLoopCoordinationTest implements TopicListener {
72
73     private static final Logger logger = LoggerFactory.getLogger(ControlLoopCoordinationTest.class);
74
75     private static List<? extends TopicSink> noopTopics;
76
77     private static KieSession kieSession1;
78     private static KieSession kieSession2;
79     private static StringBuilder controlLoopOneName = new StringBuilder();
80     private static StringBuilder controlLoopTwoName = new StringBuilder();
81     private static String expectedDecision;
82
83     static {
84         /* Set environment properties */
85         SupportUtil.setAaiProps();
86         SupportUtil.setGuardPropsEmbedded();
87         SupportUtil.setPuProp();
88     }
89
90     /**
91      * Setup simulator.
92      */
93     @BeforeClass
94     public static void setUpSimulator() {
95         PolicyEngine.manager.configure(new Properties());
96         assertTrue(PolicyEngine.manager.start());
97         Properties noopSinkProperties = new Properties();
98         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
99         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
100         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
101                 "org.onap.policy.appclcm.util.Serialization,gson");
102         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
103                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
104         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
105                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
106         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
107
108         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
109                 .groupId("junit.groupId")
110                 .artifactId("junit.artifactId")
111                 .topic("POLICY-CL-MGT")
112                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
113                 .protocolFilter(new JsonProtocolFilter())
114                 .modelClassLoaderHash(1111));
115         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
116                 .groupId("junit.groupId")
117                 .artifactId("junit.artifactId")
118                 .topic("APPC-LCM-READ")
119                 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
120                 .protocolFilter(new JsonProtocolFilter())
121                 .modelClassLoaderHash(1111));
122         try {
123             SupportUtil.buildAaiSim();
124         } catch (Exception e) {
125             fail(e.getMessage());
126         }
127
128         /*
129          * Start the kie sessions
130          */
131         try {
132             kieSession1 = startSession(
133                     controlLoopOneName,
134                     "src/main/resources/__closedLoopControlName__.drl",
135                     "src/test/resources/yaml/policy_ControlLoop_SyntheticOne.yaml",
136                     "service=ServiceDemo;resource=Res1Demo;type=operational",
137                     "SyntheticControlLoopOnePolicy",
138                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
139             kieSession2 = startSession(
140                     controlLoopTwoName,
141                     "src/main/resources/__closedLoopControlName__.drl",
142                     "src/test/resources/yaml/policy_ControlLoop_SyntheticTwo.yaml",
143                     "service=ServiceDemo;resource=Res1Demo;type=operational",
144                     "SyntheticControlLoopTwoPolicy",
145                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
146         } catch (IOException e) {
147             logger.debug("Could not create kieSession, exception {}", e.getMessage());
148             fail("Could not create kieSession");
149         }
150     }
151
152     /**
153      * Tear down simulator.
154      */
155     @AfterClass
156     public static void tearDownSimulator() {
157         /*
158          * Gracefully shut down the kie session
159          */
160         kieSession1.dispose();
161         kieSession2.dispose();
162
163         PolicyEngine.manager.stop();
164         HttpServletServer.factory.destroy();
165         PolicyController.factory.shutdown();
166         TopicEndpoint.manager.shutdown();
167     }
168
169     /**
170      * Set expected decision.
171      * 
172      * @param ed the expected decision ("PERMIT" or "DENY")
173      */
174     public void expectedDecisionIs(String ed) {
175         expectedDecision = ed;
176         logger.info("Expected decision is {}", ed);
177     }
178
179     /**
180      * This method is used to simulate event messages from DCAE
181      * that start the control loop (onset message) or end the
182      * control loop (abatement message).
183      * 
184      * @param controlLoopName the control loop name
185      * @param requestId the requestId for this event
186      * @param status could be onset or abated
187      * @param target the target name
188      * @param kieSession the kieSession to which this event is being sent
189      */
190     protected void sendEvent(String controlLoopName,
191                              UUID requestId, 
192                              ControlLoopEventStatus status,
193                              String target,
194                              KieSession kieSession) {
195         logger.debug("sendEvent controlLoopName={}", controlLoopName);
196         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
197         event.setClosedLoopControlName(controlLoopName);
198         event.setRequestId(requestId);
199         event.setTarget("generic-vnf.vnf-name");
200         event.setTargetType(ControlLoopTargetType.VNF);
201         event.setClosedLoopAlarmStart(Instant.now());
202         event.setAai(new HashMap<>());
203         event.getAai().put("generic-vnf.vnf-name", target);
204         event.setClosedLoopEventStatus(status);
205
206         Gson gson = new Gson();
207         String json = gson.toJson(event);
208         logger.debug("sendEvent {}", json);
209         
210         kieSession.insert(event);
211     }
212
213     
214     /**
215      * Simulate an event by inserting into kieSession and firing rules as needed.
216      * 
217      * @param cles the ControlLoopEventStatus
218      * @param rid the request ID
219      * @param controlLoopName the control loop name
220      * @param kieSession the kieSession to which this event is being sent
221      * @param expectedDecision the expected decision
222      */
223     protected void simulateEvent(ControlLoopEventStatus cles,
224                                  UUID rid,
225                                  String controlLoopName,
226                                  String target,
227                                  KieSession kieSession,
228                                  String expectedDecision) {
229         //
230         // if onset, set expected decision
231         //
232         if (cles == ControlLoopEventStatus.ONSET) {
233             expectedDecisionIs(expectedDecision);
234         }
235         //
236         // simulate sending event
237         // 
238         sendEvent(controlLoopName, rid, cles, target, kieSession);
239         kieSession.fireUntilHalt();
240         //
241         // get dump of database entries and log
242         // 
243         List<?> entries = SupportUtil.dumpDb();
244         assertNotNull(entries);
245         logger.debug("dumpDB, {} entries", entries.size());
246         for (Object entry : entries) {
247             logger.debug("{}", entry);
248         }
249         //
250         // we are done
251         // 
252         logger.info("simulateEvent: done");
253     }
254
255     /**
256      * Simulate an onset event.
257      * 
258      * @param rid the request ID
259      * @param controlLoopName the control loop name
260      * @param kieSession the kieSession to which this event is being sent
261      * @param expectedDecision the expected decision 
262      */
263     public void simulateOnset(UUID rid,
264                               String controlLoopName,
265                               String target,
266                               KieSession kieSession,
267                               String expectedDecision) {
268         simulateEvent(ControlLoopEventStatus.ONSET, rid, controlLoopName, target, kieSession, expectedDecision);
269     }
270
271     /**
272      * Simulate an abated event.
273      * 
274      * @param rid the request ID
275      * @param controlLoopName the control loop name
276      * @param kieSession the kieSession to which this event is being sent
277      */
278     public void simulateAbatement(UUID rid,
279                                   String controlLoopName,
280                                   String target,
281                                   KieSession kieSession) {
282         simulateEvent(ControlLoopEventStatus.ABATED, rid, controlLoopName, target, kieSession, null);
283     }
284    
285     /**
286      * This method will start a kie session and instantiate the Policy Engine.
287      * 
288      * @param droolsTemplate the DRL rules file
289      * @param yamlFile the yaml file containing the policies
290      * @param policyScope scope for policy
291      * @param policyName name of the policy
292      * @param policyVersion version of the policy
293      * @return the kieSession to be used to insert facts
294      * @throws IOException throws IO exception
295      */
296     private static KieSession startSession(StringBuilder controlLoopName,
297                                            String droolsTemplate,
298                                            String yamlFile,
299                                            String policyScope,
300                                            String policyName,
301                                            String policyVersion) throws IOException {
302
303         /*
304          * Load policies from yaml
305          */
306         SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(yamlFile);
307         assertNotNull(pair);
308         assertNotNull(pair.first);
309         assertNotNull(pair.first.getControlLoop());
310         assertNotNull(pair.first.getControlLoop().getControlLoopName());
311         assertTrue(!pair.first.getControlLoop().getControlLoopName().isEmpty());
312
313         controlLoopName.append(pair.first.getControlLoop().getControlLoopName());
314         String yamlContents = pair.second;
315         
316         /*
317          * Construct a kie session
318          */
319         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate, 
320                                                           controlLoopName.toString(),
321                                                           policyScope,
322                                                           policyName,
323                                                           policyVersion,
324                                                           URLEncoder.encode(yamlContents, "UTF-8"));
325
326         /*
327          * Retrieve the Policy Engine
328          */
329
330         logger.debug("============");
331         logger.debug(URLEncoder.encode(yamlContents, "UTF-8"));
332         logger.debug("============");
333
334         return kieSession;
335     }
336
337     /*
338      * (non-Javadoc)
339      * 
340      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
341      */
342     @Override
343     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
344         /*
345          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
346          * of type active
347          */
348         Object obj = null;
349         if ("POLICY-CL-MGT".equals(topic)) {
350             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
351                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
352         } else if ("APPC-LCM-READ".equals(topic)) {
353             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
354                     org.onap.policy.appclcm.LcmRequestWrapper.class);
355         }
356         assertNotNull(obj);
357         if (obj instanceof VirtualControlLoopNotification) {
358             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
359             String policyName = notification.getPolicyName();
360             if (policyName.endsWith("EVENT")) {
361                 logger.debug("Rule Fired: " + notification.getPolicyName());
362                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
363             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
364                 logger.debug("Rule Fired: " + notification.getPolicyName());
365                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
366                 assertNotNull(notification.getMessage());
367                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
368             } else if (policyName.endsWith("GUARD.RESPONSE")) {
369                 logger.debug("Rule Fired: " + notification.getPolicyName());
370                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
371                 assertNotNull(notification.getMessage());
372                 // THESE ARE THE MOST CRITICAL ASSERTS
373                 // TEST IF GUARD.RESPONSE IS CORRECT
374                 logger.debug("Testing whether decision was {} as expected", expectedDecision);
375                 assertTrue(notification.getMessage().toUpperCase().endsWith(expectedDecision));
376             } else if (policyName.endsWith("GUARD_PERMITTED")) {
377                 logger.debug("Rule Fired: " + notification.getPolicyName());
378                 assertEquals(ControlLoopNotificationType.OPERATION,notification.getNotification());
379                 assertNotNull(notification.getMessage());
380                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
381             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
382                 logger.debug("Rule Fired: " + notification.getPolicyName());
383                 kieSession1.halt();
384                 kieSession2.halt();
385                 logger.debug("The operation timed out");
386                 fail("Operation Timed Out");
387             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
388                 logger.debug("Rule Fired: " + notification.getPolicyName());
389                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
390                 assertNotNull(notification.getMessage());
391                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
392             } else if (policyName.endsWith("EVENT.MANAGER")) {
393                 logger.debug("Rule Fired: " + notification.getPolicyName());
394                 if (notification.getMessage().endsWith("Closing the control loop.")
395                     || notification.getMessage().equals("Waiting for abatement")) {
396                     if (policyName.startsWith(controlLoopOneName.toString())) {
397                         logger.debug("Halting kieSession1");
398                         kieSession1.halt();
399                     } else if (policyName.startsWith(controlLoopTwoName.toString())) {
400                         logger.debug("Halting kieSession2");
401                         kieSession2.halt();
402                     } else {
403                         fail("Unknown ControlLoop"); 
404                     }
405                 }
406             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
407                 logger.debug("Rule Fired: " + notification.getPolicyName());
408                 kieSession1.halt();
409                 kieSession2.halt();
410                 logger.debug("The control loop timed out");
411                 fail("Control Loop Timed Out");
412             }
413         } else if (obj instanceof LcmRequestWrapper) {
414             /*
415              * The request should be of type LCMRequestWrapper and the subrequestid should be 1
416              */
417             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
418             LcmRequest appcRequest = dmaapRequest.getBody();
419             assertEquals(appcRequest.getCommonHeader().getSubRequestId(),"1");
420
421             logger.debug("\n============ APPC received the request!!! ===========\n");
422
423             /*
424              * Simulate a success response from APPC and insert the response into the working memory
425              */
426             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
427             LcmResponse appcResponse = new LcmResponse(appcRequest);
428             appcResponse.getStatus().setCode(400);
429             appcResponse.getStatus().setMessage("AppC success");
430             dmaapResponse.setBody(appcResponse);
431             kieSession1.insert(dmaapResponse);
432             kieSession2.insert(dmaapResponse);
433         }
434     }
435
436     /**
437      * This method will dump all the facts in the working memory.
438      * 
439      * @param kieSession the session containing the facts
440      */
441     public void dumpFacts(KieSession kieSession) {
442         logger.debug("Fact Count: {}", kieSession.getFactCount());
443         for (FactHandle handle : kieSession.getFactHandles()) {
444             logger.debug("FACT: {}", handle);
445         }
446     }
447
448     /**
449      * Test that SyntheticControlLoopOne blocks SyntheticControlLoopTwo
450      * is enforced correctly.
451      */
452     @Test
453     public void testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo() throws InterruptedException {
454         logger.info("Beginning testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo");
455         /*
456          * Allows the PolicyEngine to callback to this object to
457          * notify that there is an event ready to be pulled 
458          * from the queue
459          */
460         for (TopicSink sink : noopTopics) {
461             assertTrue(sink.start());
462             sink.register(this);
463         }
464                 
465         /*
466          * Create unique requestIds
467          */
468         final UUID requestId1 = UUID.randomUUID();
469         final UUID requestId2 = UUID.randomUUID();
470         final UUID requestId3 = UUID.randomUUID();
471         final UUID requestId4 = UUID.randomUUID();
472         final UUID requestId5 = UUID.randomUUID();
473         final String cl1 = controlLoopOneName.toString();
474         final String cl2 = controlLoopTwoName.toString();
475         final String t1 = "TARGET_1";
476         final String t2 = "TARGET_2";
477
478         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
479         simulateOnset(requestId1, cl2, t1, kieSession2,"PERMIT");
480         logger.info("@@@@@@@@@@ cl1 ONSET t1 @@@@@@@@@@"); 
481         simulateOnset(requestId2, cl1, t1, kieSession1,"PERMIT");
482         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
483         simulateAbatement(requestId1, cl2, t1, kieSession2);
484         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Fail) @@@@@@@@@@"); 
485         simulateOnset(requestId3, cl2, t1, kieSession2,"DENY");
486         logger.info("@@@@@@@@@@ cl2 ONSET t2 (Success) @@@@@@@@@@");
487         simulateOnset(requestId4, cl2, t2, kieSession2,"PERMIT");
488         logger.info("@@@@@@@@@@ cl2 ABATED t2 @@@@@@@@@@"); 
489         simulateAbatement(requestId4, cl2, t2, kieSession2);
490         logger.info("@@@@@@@@@@ cl1 ABATED t1  @@@@@@@@@@"); 
491         simulateAbatement(requestId2, cl1, t1, kieSession1);
492         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
493         simulateOnset(requestId5, cl2, t1, kieSession2,"PERMIT");
494         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
495         simulateAbatement(requestId5, cl2, t1, kieSession2);
496         
497         /*
498          * Print what's left in memory
499          */
500         dumpFacts(kieSession1);
501         dumpFacts(kieSession2);
502     }
503 }
504