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