ae8bcb4e4d29c2c070670b5f9d22ba11d23afdbe
[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.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.drools.event.comm.TopicEndpoint;
49 import org.onap.policy.drools.event.comm.TopicListener;
50 import org.onap.policy.drools.event.comm.TopicSink;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.properties.PolicyProperties;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class VCPEControlLoopTest implements TopicListener {
60
61     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
62     
63     private static List<? extends TopicSink> noopTopics;
64     
65     private KieSession kieSession;
66     private Util.Pair<ControlLoopPolicy, String> pair;
67     private UUID requestID;
68     
69     static {
70         /* Set environment properties */
71         Util.setAAIProps();
72         Util.setGuardProps();
73         Util.setPUProp();
74     }
75     
76     @BeforeClass
77     public static void setUpSimulator() {
78         PolicyEngine.manager.configure(new Properties());
79         assertTrue(PolicyEngine.manager.start());
80         Properties noopSinkProperties = new Properties();
81         noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
82         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
83         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
84         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
85         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
86         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
87         
88         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
89         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
90         try {
91             Util.buildAaiSim();
92             Util.buildGuardSim();
93         } catch (Exception e) {
94             fail(e.getMessage());
95         }
96     }
97
98     @AfterClass
99     public static void tearDownSimulator() {
100         HttpServletServer.factory.destroy();
101         PolicyEngine.manager.shutdown();
102     }
103     
104     @Test
105     public void successTest() {
106         /*
107          * Start the kie session
108          */
109         try {
110             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
111                         "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
112                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
113                         "CL_vCPE", 
114                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
115         } catch (IOException e) {
116             e.printStackTrace();
117             logger.debug("Could not create kieSession");
118             fail("Could not create kieSession");
119         }
120         
121         /*
122          * Allows the PolicyEngine to callback to this object to
123          * notify that there is an event ready to be pulled 
124          * from the queue
125          */
126         for (TopicSink sink : noopTopics) {
127             assertTrue(sink.start());
128             sink.register(this);
129         }
130         
131         /*
132          * Create a unique requestId
133          */
134         requestID = UUID.randomUUID();
135         
136         /* 
137          * Simulate an onset event the policy engine will 
138          * receive from DCAE to kick off processing through
139          * the rules
140          */
141         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
142
143         
144         kieSession.fireUntilHalt();
145         
146         /*
147          * The only fact in memory should be Params
148          */
149         assertEquals(1, kieSession.getFactCount());
150         
151         /*
152          * Print what's left in memory
153          */
154         dumpFacts(kieSession);
155         
156         /*
157          * Gracefully shut down the kie session
158          */
159         kieSession.dispose();
160     }
161
162     /**
163      * This method will start a kie session and instantiate 
164      * the Policy Engine.
165      * 
166      * @param droolsTemplate
167      *          the DRL rules file
168      * @param yamlFile
169      *          the yaml file containing the policies
170      * @param policyScope
171      *          scope for policy
172      * @param policyName
173      *          name of the policy
174      * @param policyVersion
175      *          version of the policy          
176      * @return the kieSession to be used to insert facts 
177      * @throws IOException
178      */
179     private KieSession startSession(String droolsTemplate, 
180             String yamlFile, 
181             String policyScope, 
182             String policyName, 
183             String policyVersion) throws IOException {
184         
185         /*
186          * Load policies from yaml
187          */
188         pair = Util.loadYaml(yamlFile);
189         assertNotNull(pair);
190         assertNotNull(pair.a);
191         assertNotNull(pair.a.getControlLoop());
192         assertNotNull(pair.a.getControlLoop().getControlLoopName());
193         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
194         
195         /* 
196          * Construct a kie session
197          */
198         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
199                 pair.a.getControlLoop().getControlLoopName(), 
200                 policyScope, 
201                 policyName, 
202                 policyVersion, 
203                 URLEncoder.encode(pair.b, "UTF-8"));
204         
205         /*
206          * Retrieve the Policy Engine
207          */
208         
209         logger.debug("============");
210         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
211         logger.debug("============");
212         
213         return kieSession;
214     }
215     
216     /*
217      * (non-Javadoc)
218      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
219      */
220     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
221         /*
222          * Pull the object that was sent out to DMAAP and make
223          * sure it is a ControlLoopNoticiation of type active
224          */
225         Object obj = null;
226         if ("POLICY-CL-MGT".equals(topic)) {
227                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
228         }
229         else if ("APPC-LCM-READ".equals(topic))
230                 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
231         assertNotNull(obj);
232         if (obj instanceof VirtualControlLoopNotification) {
233             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
234             String policyName = notification.policyName;
235             if (policyName.endsWith("EVENT")) {
236                 logger.debug("Rule Fired: " + notification.policyName);
237                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
238             }
239             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
240                 logger.debug("Rule Fired: " + notification.policyName);
241                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
242                 assertNotNull(notification.message);
243                 assertTrue(notification.message.startsWith("Sending guard query"));
244             }
245             else if (policyName.endsWith("GUARD.RESPONSE")) {
246                 logger.debug("Rule Fired: " + notification.policyName);
247                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
248                 assertNotNull(notification.message);
249                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
250             }
251             else if (policyName.endsWith("GUARD_PERMITTED")) {
252                 logger.debug("Rule Fired: " + notification.policyName);
253                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
254                 assertNotNull(notification.message);
255                 assertTrue(notification.message.startsWith("actor=APPC"));
256             }
257             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
258                 logger.debug("Rule Fired: " + notification.policyName);
259                 kieSession.halt();
260                 logger.debug("The operation timed out");
261                 fail("Operation Timed Out");
262             }
263             else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
264                 logger.debug("Rule Fired: " + notification.policyName);
265                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
266                 assertNotNull(notification.message);
267                 assertTrue(notification.message.startsWith("actor=APPC"));
268                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
269             }
270             else if (policyName.endsWith("EVENT.MANAGER")) {
271                 logger.debug("Rule Fired: " + notification.policyName);
272                 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
273                 kieSession.halt();
274             }
275             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
276                 logger.debug("Rule Fired: " + notification.policyName);
277                 kieSession.halt();
278                 logger.debug("The control loop timed out");
279                 fail("Control Loop Timed Out");
280             }
281         }
282         else if (obj instanceof LCMRequestWrapper) {
283             /*
284              * The request should be of type LCMRequestWrapper
285              * and the subrequestid should be 1
286              */
287             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
288             LCMRequest appcRequest = dmaapRequest.getBody();
289             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
290             
291             logger.debug("\n============ APPC received the request!!! ===========\n");
292             
293             /*
294              * Simulate a success response from APPC and insert
295              * the response into the working memory
296              */
297             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
298             LCMResponse appcResponse = new LCMResponse(appcRequest);
299             appcResponse.getStatus().setCode(400);
300             appcResponse.getStatus().setMessage("AppC success");
301             dmaapResponse.setBody(appcResponse);
302             kieSession.insert(dmaapResponse);
303         }        
304     }
305     
306     /**
307      * This method is used to simulate event messages from DCAE
308      * that start the control loop (onset message) or end the
309      * control loop (abatement message).
310      * 
311      * @param policy the controlLoopName comes from the policy 
312      * @param requestID the requestId for this event
313      * @param status could be onset or abated
314      */
315     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
316         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
317         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
318         event.requestID = requestID;
319         event.target = "generic-vnf.vnf-id";
320         event.closedLoopAlarmStart = Instant.now();
321         event.AAI = new HashMap<>();
322         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
323         event.closedLoopEventStatus = status;
324         kieSession.insert(event);
325     }
326     
327     /**
328      * This method will dump all the facts in the working memory.
329      * 
330      * @param kieSession the session containing the facts
331      */
332     public void dumpFacts(KieSession kieSession) {
333         logger.debug("Fact Count: {}", kieSession.getFactCount());
334         for (FactHandle handle : kieSession.getFactHandles()) {
335             logger.debug("FACT: {}", handle);
336         }
337     }
338     
339 }