c95d558a54b9a3569c7747e133fd930bb33e9436
[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.ControlLoopTargetType;
45 import org.onap.policy.controlloop.VirtualControlLoopEvent;
46 import org.onap.policy.controlloop.VirtualControlLoopNotification;
47 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
48 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
49 import org.onap.policy.drools.event.comm.TopicEndpoint;
50 import org.onap.policy.drools.event.comm.TopicListener;
51 import org.onap.policy.drools.event.comm.TopicSink;
52 import org.onap.policy.drools.http.server.HttpServletServer;
53 import org.onap.policy.drools.properties.PolicyProperties;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
55 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
56 import org.onap.policy.drools.system.PolicyController;
57 import org.onap.policy.drools.system.PolicyEngine;
58 import org.onap.policy.drools.utils.LoggerUtil;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class VCPEControlLoopTest implements TopicListener {
63
64     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
65     
66     private static List<? extends TopicSink> noopTopics;
67     
68     private static KieSession kieSession;
69     private static Util.Pair<ControlLoopPolicy, String> pair;
70     private UUID requestID;
71     
72     static {
73         /* Set environment properties */
74         Util.setAAIProps();
75         Util.setGuardProps();
76         Util.setPUProp();
77         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");       
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          * Start the kie session
102          */
103         try {
104             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
105                         "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
106                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
107                         "CL_vCPE", 
108                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
109         } catch (IOException e) {
110             e.printStackTrace();
111             logger.debug("Could not create kieSession");
112             fail("Could not create kieSession");
113         }
114     }
115
116     @AfterClass
117     public static void tearDownSimulator() {
118         /*
119          * Gracefully shut down the kie session
120          */
121         kieSession.dispose();
122         
123         PolicyEngine.manager.stop();
124         HttpServletServer.factory.destroy();
125         PolicyController.factory.shutdown();
126         TopicEndpoint.manager.shutdown();
127     }
128     
129     @Test
130     public void successTest() {
131         
132         /*
133          * Allows the PolicyEngine to callback to this object to
134          * notify that there is an event ready to be pulled 
135          * from the queue
136          */
137         for (TopicSink sink : noopTopics) {
138             assertTrue(sink.start());
139             sink.register(this);
140         }
141         
142         /*
143          * Create a unique requestId
144          */
145         requestID = UUID.randomUUID();
146         
147         /* 
148          * Simulate an onset event the policy engine will 
149          * receive from DCAE to kick off processing through
150          * the rules
151          */
152         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true);
153         
154         kieSession.fireUntilHalt();
155         
156         /*
157          * The only fact in memory should be Params
158          */
159         assertEquals(1, kieSession.getFactCount());
160         
161         /*
162          * Print what's left in memory
163          */
164         dumpFacts(kieSession);
165     }
166     
167     @Test
168     public void aaiGetFailTest() {
169         
170         /*
171          * Allows the PolicyEngine to callback to this object to
172          * notify that there is an event ready to be pulled 
173          * from the queue
174          */
175         for (TopicSink sink : noopTopics) {
176             assertTrue(sink.start());
177             sink.register(this);
178         }
179         
180         /*
181          * Create a unique requestId
182          */
183         requestID = UUID.randomUUID();
184         
185         /* 
186          * Simulate an onset event the policy engine will 
187          * receive from DCAE to kick off processing through
188          * the rules
189          */
190         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false);
191
192         
193         kieSession.fireUntilHalt();
194         
195         /*
196          * The only fact in memory should be Params
197          */
198         assertEquals(1, kieSession.getFactCount());
199         
200         /*
201          * Print what's left in memory
202          */
203         dumpFacts(kieSession);
204         
205     }
206
207     /**
208      * This method will start a kie session and instantiate 
209      * the Policy Engine.
210      * 
211      * @param droolsTemplate
212      *          the DRL rules file
213      * @param yamlFile
214      *          the yaml file containing the policies
215      * @param policyScope
216      *          scope for policy
217      * @param policyName
218      *          name of the policy
219      * @param policyVersion
220      *          version of the policy          
221      * @return the kieSession to be used to insert facts 
222      * @throws IOException
223      */
224     private static KieSession startSession(String droolsTemplate, 
225             String yamlFile, 
226             String policyScope, 
227             String policyName, 
228             String policyVersion) throws IOException {
229         
230         /*
231          * Load policies from yaml
232          */
233         pair = Util.loadYaml(yamlFile);
234         assertNotNull(pair);
235         assertNotNull(pair.a);
236         assertNotNull(pair.a.getControlLoop());
237         assertNotNull(pair.a.getControlLoop().getControlLoopName());
238         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
239         
240         /* 
241          * Construct a kie session
242          */
243         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
244                 pair.a.getControlLoop().getControlLoopName(), 
245                 policyScope, 
246                 policyName, 
247                 policyVersion, 
248                 URLEncoder.encode(pair.b, "UTF-8"));
249         
250         /*
251          * Retrieve the Policy Engine
252          */
253         
254         logger.debug("============");
255         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
256         logger.debug("============");
257         
258         return kieSession;
259     }
260     
261     /*
262      * (non-Javadoc)
263      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
264      */
265     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
266         /*
267          * Pull the object that was sent out to DMAAP and make
268          * sure it is a ControlLoopNoticiation of type active
269          */
270         Object obj = null;
271         if ("POLICY-CL-MGT".equals(topic)) {
272                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
273         }
274         else if ("APPC-LCM-READ".equals(topic))
275                 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
276         assertNotNull(obj);
277         if (obj instanceof VirtualControlLoopNotification) {
278             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
279             String policyName = notification.policyName;
280             if (policyName.endsWith("EVENT")) {
281                 logger.debug("Rule Fired: " + notification.policyName);
282                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
283             }
284             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
285                 logger.debug("Rule Fired: " + notification.policyName);
286                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
287                 assertNotNull(notification.message);
288                 assertTrue(notification.message.startsWith("Sending guard query"));
289             }
290             else if (policyName.endsWith("GUARD.RESPONSE")) {
291                 logger.debug("Rule Fired: " + notification.policyName);
292                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
293                 assertNotNull(notification.message);
294                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
295             }
296             else if (policyName.endsWith("GUARD_PERMITTED")) {
297                 logger.debug("Rule Fired: " + notification.policyName);
298                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
299                 assertNotNull(notification.message);
300                 assertTrue(notification.message.startsWith("actor=APPC"));
301             }
302             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
303                 logger.debug("Rule Fired: " + notification.policyName);
304                 kieSession.halt();
305                 logger.debug("The operation timed out");
306                 fail("Operation Timed Out");
307             }
308             else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
309                 logger.debug("Rule Fired: " + notification.policyName);
310                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
311                 assertNotNull(notification.message);
312                 assertTrue(notification.message.startsWith("actor=APPC"));
313                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
314             }
315             else if (policyName.endsWith("EVENT.MANAGER")) {
316                 logger.debug("Rule Fired: " + notification.policyName);
317                 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
318                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
319                     kieSession.halt();
320                 }
321                 else {
322                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.notification);
323                     kieSession.halt();
324                 }
325             }
326             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
327                 logger.debug("Rule Fired: " + notification.policyName);
328                 kieSession.halt();
329                 logger.debug("The control loop timed out");
330                 fail("Control Loop Timed Out");
331             }
332         }
333         else if (obj instanceof LCMRequestWrapper) {
334             /*
335              * The request should be of type LCMRequestWrapper
336              * and the subrequestid should be 1
337              */
338             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
339             LCMRequest appcRequest = dmaapRequest.getBody();
340             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
341             assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id"));
342             
343             logger.debug("\n============ APPC received the request!!! ===========\n");
344             
345             /*
346              * Simulate a success response from APPC and insert
347              * the response into the working memory
348              */
349             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
350             LCMResponse appcResponse = new LCMResponse(appcRequest);
351             appcResponse.getStatus().setCode(400);
352             appcResponse.getStatus().setMessage("AppC success");
353             dmaapResponse.setBody(appcResponse);
354             kieSession.insert(dmaapResponse);
355         }        
356     }
357     
358     /**
359      * This method is used to simulate event messages from DCAE
360      * that start the control loop (onset message) or end the
361      * control loop (abatement message).
362      * 
363      * @param policy the controlLoopName comes from the policy 
364      * @param requestID the requestId for this event
365      * @param status could be onset or abated
366      */
367     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
368         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
369         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
370         event.requestID = requestID;
371         event.target = "generic-vnf.vnf-name";
372         event.closedLoopAlarmStart = Instant.now();
373         event.AAI = new HashMap<>();
374         event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName");
375         event.closedLoopEventStatus = status;
376         kieSession.insert(event);
377     }
378     
379     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, 
380             ControlLoopEventStatus status, String vnfName, boolean isEnriched) {
381         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
382         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
383         event.requestID = requestID;
384         event.target = "generic-vnf.vnf-name";
385         event.target_type = ControlLoopTargetType.VNF;
386         event.closedLoopAlarmStart = Instant.now();
387         event.AAI = new HashMap<>();
388         event.AAI.put("generic-vnf.vnf-name", vnfName);
389         if (isEnriched) {
390             event.AAI.put("generic-vnf.in-maint", "false");
391             event.AAI.put("generic-vnf.is-closed-loop-disabled", "false");
392             event.AAI.put("generic-vnf.orchestration-status", "Created");
393             event.AAI.put("generic-vnf.prov-status", "PREPROV");
394             event.AAI.put("generic-vnf.resource-version", "1");
395             event.AAI.put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd");
396             event.AAI.put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9");
397             event.AAI.put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0");
398         }
399         event.closedLoopEventStatus = status;
400         kieSession.insert(event);
401     }
402     
403     /**
404      * This method will dump all the facts in the working memory.
405      * 
406      * @param kieSession the session containing the facts
407      */
408     public void dumpFacts(KieSession kieSession) {
409         logger.debug("Fact Count: {}", kieSession.getFactCount());
410         for (FactHandle handle : kieSession.getFactHandles()) {
411             logger.debug("FACT: {}", handle);
412         }
413     }
414     
415 }