6d1086d87c36db4bfa58e2c7fdcea7edc088df8e
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.template.demo;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Properties;
35 import java.util.UUID;
36
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.kie.api.runtime.KieSession;
41 import org.kie.api.runtime.rule.FactHandle;
42 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
43 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
44 import org.onap.policy.common.endpoints.event.comm.TopicListener;
45 import org.onap.policy.common.endpoints.event.comm.TopicSink;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
48 import org.onap.policy.controlloop.ControlLoopEventStatus;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
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.logging.LoggerUtil;
59 import org.onap.policy.sdnr.PciRequest;
60 import org.onap.policy.sdnr.PciRequestWrapper;
61 import org.onap.policy.sdnr.PciResponse;
62 import org.onap.policy.sdnr.PciResponseWrapper;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public class VpciControlLoopTest implements TopicListener {
67
68     private static final Logger logger = LoggerFactory.getLogger(VpciControlLoopTest.class);
69
70     private static List<? extends TopicSink> noopTopics;
71
72     private static KieSession kieSession;
73     private static Util.Pair<ControlLoopPolicy, String> pair;
74     private UUID requestId;
75
76     static {
77         /* Set environment properties */
78         Util.setAaiProps();
79         Util.setGuardProps();
80         Util.setPuProp();
81         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "DEBUG");
82     }
83
84     /**
85      * Setup the simulator.
86      */
87     @BeforeClass
88     public static void setUpSimulator() {
89         PolicyEngine.manager.configure(new Properties());
90         assertTrue(PolicyEngine.manager.start());
91         Properties noopSinkProperties = new Properties();
92         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "SDNR-CL,POLICY-CL-MGT");
93         noopSinkProperties.put("noop.sink.topics.SDNR-CL.events", "org.onap.policy.sdnr.PciRequestWrapper");
94         noopSinkProperties.put("noop.sink.topics.SDNR-CL.events.custom.gson",
95                 "org.onap.policy.sdnr.util.Serialization,gson");
96         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
97                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
98         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
99                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
100         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
101
102         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
103                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
104                 1111);
105         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "SDNR-CL",
106                 "org.onap.policy.sdnr.PciRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
107         try {
108             Util.buildAaiSim();
109             Util.buildGuardSim();
110         } catch (Exception e) {
111             fail(e.getMessage());
112         }
113         /*
114          * Start the kie session
115          */
116         try {
117             kieSession = startSession(
118                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
119                             + "/src/main/resources/__closedLoopControlName__.drl",
120                     "src/test/resources/yaml/policy_ControlLoop_vPCI.yaml", "type=operational", "CL_vPCI", "v3.0.0");
121         } catch (IOException e) {
122             e.printStackTrace();
123             logger.debug("Could not create kieSession");
124             fail("Could not create kieSession");
125         }
126     }
127
128     /**
129      * Tear down the simulator.
130      */
131     @AfterClass
132     public static void tearDownSimulator() {
133         /*
134          * Gracefully shut down the kie session
135          */
136         kieSession.dispose();
137
138         PolicyEngine.manager.stop();
139         HttpServletServer.factory.destroy();
140         PolicyController.factory.shutdown();
141         TopicEndpoint.manager.shutdown();
142     }
143
144     @Test
145     public void successTest() {
146
147         /*
148          * Allows the PolicyEngine to callback to this object to notify that there is an
149          * event ready to be pulled from the queue
150          */
151         for (TopicSink sink : noopTopics) {
152             assertTrue(sink.start());
153             sink.register(this);
154         }
155
156         /*
157          * Create a unique requestId
158          */
159         requestId = UUID.randomUUID();
160
161         /*
162          * Simulate an onset event the policy engine will receive from DCAE to kick off
163          * processing through the rules
164          */
165         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, true);
166
167         kieSession.fireUntilHalt();
168         
169         // allow object clean-up
170         kieSession.fireAllRules();
171
172         /*
173          * The only fact in memory should be Params
174          */
175         assertEquals(1, kieSession.getFactCount());
176
177         /*
178          * Print what's left in memory
179          */
180         dumpFacts(kieSession);
181
182     }
183
184     @Test
185     public void aaiGetFailTest() {
186
187         /*
188          * Allows the PolicyEngine to callback to this object to notify that there is an
189          * event ready to be pulled from the queue
190          */
191         for (TopicSink sink : noopTopics) {
192             assertTrue(sink.start());
193             sink.register(this);
194         }
195
196         /*
197          * Create a unique requestId
198          */
199         requestId = UUID.randomUUID();
200
201         /*
202          * Simulate an onset event the policy engine will receive from DCAE to kick off
203          * processing through the rules
204          */
205         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
206
207         kieSession.fireUntilHalt();
208         
209         // allow object clean-up
210         kieSession.fireAllRules();
211
212         /*
213          * The only fact in memory should be Params
214          */
215         assertEquals(1, kieSession.getFactCount());
216
217         /*
218          * Print what's left in memory
219          */
220         dumpFacts(kieSession);
221
222     }
223
224     /**
225      * This method will start a kie session and instantiate the Policy Engine.
226      * 
227      * @param droolsTemplate
228      *            the DRL rules file
229      * @param yamlFile
230      *            the yaml file containing the policies
231      * @param policyScope
232      *            scope for policy
233      * @param policyName
234      *            name of the policy
235      * @param policyVersion
236      *            version of the policy
237      * @return the kieSession to be used to insert facts
238      * @throws IOException
239      *             IO exception
240      */
241     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
242             String policyName, String policyVersion) throws IOException {
243
244         /*
245          * Load policies from yaml
246          */
247         pair = Util.loadYaml(yamlFile);
248         assertNotNull(pair);
249         assertNotNull(pair.first);
250         assertNotNull(pair.first.getControlLoop());
251         assertNotNull(pair.first.getControlLoop().getControlLoopName());
252         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
253
254         /*
255          * Construct a kie session
256          */
257         final KieSession kieSession = Util.buildContainer(droolsTemplate,
258                 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
259                 URLEncoder.encode(pair.second, "UTF-8"));
260
261         /*
262          * Retrieve the Policy Engine
263          */
264
265         logger.debug("======controlloop======");
266         logger.debug(((ControlLoopPolicy) pair.first).toString());
267         logger.debug("======policies======");
268         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
269         logger.debug("============");
270
271         return kieSession;
272     }
273
274     /*
275      * (non-Javadoc)
276      * 
277      * @see
278      * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
279      * String)
280      */
281     @Override
282     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
283         logger.debug("\n============ onTopicEvent!!! ===========\n");
284         logger.debug("topic: {}, event: {}", topic, event);
285         /*
286          * Pull the object that was sent out to DMAAP and make sure it is a
287          * ControlLoopNoticiation of type active
288          */
289         Object obj = null;
290         if ("POLICY-CL-MGT".equals(topic)) {
291             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
292                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
293         } else if ("SDNR-CL".equals(topic)) {
294             obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
295                     org.onap.policy.sdnr.PciRequestWrapper.class);
296         }
297         assertNotNull(obj);
298         if (obj instanceof VirtualControlLoopNotification) {
299             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
300             String policyName = notification.getPolicyName();
301             logger.debug("Rule Fired: {}", policyName);
302             if (policyName.endsWith("EVENT")) {
303                 assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
304             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
305                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
306                 assertNotNull(notification.getMessage());
307                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
308             } else if (policyName.endsWith("GUARD.RESPONSE")) {
309                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
310                 assertNotNull(notification.getMessage());
311                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
312             } else if (policyName.endsWith("GUARD_PERMITTED")) {
313                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
314                 assertNotNull(notification.getMessage());
315                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
316             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
317                 kieSession.halt();
318                 logger.debug("The operation timed out");
319                 fail("Operation Timed Out");
320             } else if (policyName.endsWith("SDNR.RESPONSE")) {
321                 assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
322                 assertNotNull(notification.getMessage());
323                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
324             } else if (policyName.endsWith("EVENT.MANAGER")) {
325                 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
326                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
327                     kieSession.halt();
328                 } else {
329                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
330                     kieSession.halt();
331                 }
332             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
333                 kieSession.halt();
334                 logger.debug("The control loop timed out");
335                 fail("Control Loop Timed Out");
336             }
337         } else if (obj instanceof PciRequestWrapper) {
338             /*
339              * The request should be of type PciRequestWrapper and the subrequestid should
340              * be 1
341              */
342             PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
343             PciRequest pciRequest = dmaapRequest.getBody();
344             assertEquals("1", pciRequest.getCommonHeader().getSubRequestId());
345
346             logger.debug("\n============ SDNR received the request!!! ===========\n");
347             logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
348             logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
349
350             /*
351              * Simulate a success response from SDNR and insert the response into the
352              * working memory
353              */
354             PciResponse pciResponse = new PciResponse(pciRequest);
355             pciResponse.getStatus().setCode(200);
356             pciResponse.getStatus().setValue("SUCCESS");
357             StringBuilder sb = new StringBuilder();
358             sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
359                     + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
360                     + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
361                     + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
362
363             pciResponse.setPayload(sb.toString());
364             PciResponseWrapper dmaapResponse = new PciResponseWrapper();
365             dmaapResponse.setBody(pciResponse);
366             dmaapResponse.setType("response");
367             logger.debug("\n============ SDNR sending response!!! ===========\n");
368             logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
369             logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
370             kieSession.insert(dmaapResponse);
371         }
372     }
373
374     /**
375      * This method is used to simulate event messages from DCAE that start the
376      * control loop (onset message).
377      * 
378      * @param policy
379      *            the controlLoopName comes from the policy
380      * @param requestID
381      *            the requestId for this event
382      * @param status
383      *            could be onset
384      */
385     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
386             boolean isEnriched) {
387         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
388         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
389         event.setRequestId(requestId);
390         event.setTarget("generic-vnf.vnf-id");
391         event.setTargetType(ControlLoopTargetType.VNF);
392         event.setClosedLoopAlarmStart(Instant.now());
393         event.setAai(new HashMap<>());
394         if (isEnriched) {
395             event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
396             event.getAai().put("generic-vnf.prov-status", "ACTIVE");
397             event.getAai().put("generic-vnf.vnf-id", "notused");
398         } else {
399             event.getAai().put("generic-vnf.vnf-id", "getFail");
400         }
401         event.setClosedLoopEventStatus(status);
402         StringBuilder sb = new StringBuilder();
403         sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
404                 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
405                 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
406                 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
407
408         event.setPayload(sb.toString());
409         logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
410         logger.debug("\n============ event ===========\n {}", event);
411         kieSession.insert(event);
412     }
413
414     /**
415      * This method will dump all the facts in the working memory.
416      * 
417      * @param kieSession
418      *            the session containing the facts
419      */
420     public void dumpFacts(KieSession kieSession) {
421         logger.debug("Fact Count: {}", kieSession.getFactCount());
422         for (FactHandle handle : kieSession.getFactHandles()) {
423             logger.debug("FACT: {}", handle);
424         }
425     }
426
427 }