06e2aca9b53f8c2578cd22c591fbc706fa3452d9
[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         /*
170          * The only fact in memory should be Params
171          */
172         assertEquals(1, kieSession.getFactCount());
173
174         /*
175          * Print what's left in memory
176          */
177         dumpFacts(kieSession);
178
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
186          * event ready 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
200          * processing through the rules
201          */
202         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
203
204         kieSession.fireUntilHalt();
205
206         /*
207          * The only fact in memory should be Params
208          */
209         assertEquals(1, kieSession.getFactCount());
210
211         /*
212          * Print what's left in memory
213          */
214         dumpFacts(kieSession);
215
216     }
217
218     /**
219      * This method will start a kie session and instantiate the Policy Engine.
220      * 
221      * @param droolsTemplate
222      *            the DRL rules file
223      * @param yamlFile
224      *            the yaml file containing the policies
225      * @param policyScope
226      *            scope for policy
227      * @param policyName
228      *            name of the policy
229      * @param policyVersion
230      *            version of the policy
231      * @return the kieSession to be used to insert facts
232      * @throws IOException
233      *             IO exception
234      */
235     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
236             String policyName, String policyVersion) throws IOException {
237
238         /*
239          * Load policies from yaml
240          */
241         pair = Util.loadYaml(yamlFile);
242         assertNotNull(pair);
243         assertNotNull(pair.first);
244         assertNotNull(pair.first.getControlLoop());
245         assertNotNull(pair.first.getControlLoop().getControlLoopName());
246         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
247
248         /*
249          * Construct a kie session
250          */
251         final KieSession kieSession = Util.buildContainer(droolsTemplate,
252                 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
253                 URLEncoder.encode(pair.second, "UTF-8"));
254
255         /*
256          * Retrieve the Policy Engine
257          */
258
259         logger.debug("======controlloop======");
260         logger.debug(((ControlLoopPolicy) pair.first).toString());
261         logger.debug("======policies======");
262         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
263         logger.debug("============");
264
265         return kieSession;
266     }
267
268     /*
269      * (non-Javadoc)
270      * 
271      * @see
272      * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
273      * String)
274      */
275     @Override
276     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
277         logger.debug("\n============ onTopicEvent!!! ===========\n");
278         logger.debug("topic: {}, event: {}", topic, event);
279         /*
280          * Pull the object that was sent out to DMAAP and make sure it is a
281          * ControlLoopNoticiation of type active
282          */
283         Object obj = null;
284         if ("POLICY-CL-MGT".equals(topic)) {
285             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
286                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
287         } else if ("SDNR-CL".equals(topic)) {
288             obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
289                     org.onap.policy.sdnr.PciRequestWrapper.class);
290         }
291         assertNotNull(obj);
292         if (obj instanceof VirtualControlLoopNotification) {
293             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
294             String policyName = notification.getPolicyName();
295             logger.debug("Rule Fired: {}", policyName);
296             if (policyName.endsWith("EVENT")) {
297                 assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
298             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
299                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
300                 assertNotNull(notification.getMessage());
301                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
302             } else if (policyName.endsWith("GUARD.RESPONSE")) {
303                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
304                 assertNotNull(notification.getMessage());
305                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
306             } else if (policyName.endsWith("GUARD_PERMITTED")) {
307                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
308                 assertNotNull(notification.getMessage());
309                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
310             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
311                 kieSession.halt();
312                 logger.debug("The operation timed out");
313                 fail("Operation Timed Out");
314             } else if (policyName.endsWith("SDNR.RESPONSE")) {
315                 assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
316                 assertNotNull(notification.getMessage());
317                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
318             } else if (policyName.endsWith("EVENT.MANAGER")) {
319                 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
320                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
321                     kieSession.halt();
322                 } else {
323                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
324                     kieSession.halt();
325                 }
326             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
327                 kieSession.halt();
328                 logger.debug("The control loop timed out");
329                 fail("Control Loop Timed Out");
330             }
331         } else if (obj instanceof PciRequestWrapper) {
332             /*
333              * The request should be of type PciRequestWrapper and the subrequestid should
334              * be 1
335              */
336             PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
337             PciRequest pciRequest = dmaapRequest.getBody();
338             assertEquals("1", pciRequest.getCommonHeader().getSubRequestId());
339
340             logger.debug("\n============ SDNR received the request!!! ===========\n");
341             logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
342             logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
343
344             /*
345              * Simulate a success response from SDNR and insert the response into the
346              * working memory
347              */
348             PciResponse pciResponse = new PciResponse(pciRequest);
349             pciResponse.getStatus().setCode(200);
350             pciResponse.getStatus().setValue("SUCCESS");
351             StringBuilder sb = new StringBuilder();
352             sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
353                     + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
354                     + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
355                     + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
356
357             pciResponse.setPayload(sb.toString());
358             PciResponseWrapper dmaapResponse = new PciResponseWrapper();
359             dmaapResponse.setBody(pciResponse);
360             dmaapResponse.setType("response");
361             logger.debug("\n============ SDNR sending response!!! ===========\n");
362             logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
363             logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
364             kieSession.insert(dmaapResponse);
365         }
366     }
367
368     /**
369      * This method is used to simulate event messages from DCAE that start the
370      * control loop (onset message).
371      * 
372      * @param policy
373      *            the controlLoopName comes from the policy
374      * @param requestID
375      *            the requestId for this event
376      * @param status
377      *            could be onset
378      */
379     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
380             boolean isEnriched) {
381         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
382         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
383         event.setRequestId(requestId);
384         event.setTarget("generic-vnf.vnf-id");
385         event.setTargetType(ControlLoopTargetType.VNF);
386         event.setClosedLoopAlarmStart(Instant.now());
387         event.setAai(new HashMap<>());
388         if (isEnriched) {
389             event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
390             event.getAai().put("generic-vnf.prov-status", "ACTIVE");
391             event.getAai().put("generic-vnf.vnf-id", "notused");
392         } else {
393             event.getAai().put("generic-vnf.vnf-id", "getFail");
394         }
395         event.setClosedLoopEventStatus(status);
396         StringBuilder sb = new StringBuilder();
397         sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
398                 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
399                 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
400                 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
401
402         event.setPayload(sb.toString());
403         logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
404         logger.debug("\n============ event ===========\n {}", event);
405         kieSession.insert(event);
406     }
407
408     /**
409      * This method will dump all the facts in the working memory.
410      * 
411      * @param kieSession
412      *            the session containing the facts
413      */
414     public void dumpFacts(KieSession kieSession) {
415         logger.debug("Fact Count: {}", kieSession.getFactCount());
416         for (FactHandle handle : kieSession.getFactHandles()) {
417             logger.debug("FACT: {}", handle);
418         }
419     }
420
421 }