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