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