37f55dc09ae4ed8625344e569e7e71580338a251
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2018 Wipro Limited 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.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
43 import org.onap.policy.common.endpoints.event.comm.TopicListener;
44 import org.onap.policy.common.endpoints.event.comm.TopicSink;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
46 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopNotificationType;
49 import org.onap.policy.controlloop.ControlLoopTargetType;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.VirtualControlLoopNotification;
52 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
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.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.LoggerUtil;
58 import org.onap.policy.sdnr.PciRequest;
59 import org.onap.policy.sdnr.PciRequestWrapper;
60 import org.onap.policy.sdnr.PciResponse;
61 import org.onap.policy.sdnr.PciResponseWrapper;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 public class VpciControlLoopTest implements TopicListener {
66
67     private static final Logger logger = LoggerFactory.getLogger(VpciControlLoopTest.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, "DEBUG");
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, "SDNR-CL,POLICY-CL-MGT");
92         noopSinkProperties.put("noop.sink.topics.SDNR-CL.events", "org.onap.policy.sdnr.PciRequestWrapper");
93         noopSinkProperties.put("noop.sink.topics.SDNR-CL.events.custom.gson",
94                 "org.onap.policy.sdnr.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", "SDNR-CL",
105                 "org.onap.policy.sdnr.PciRequestWrapper", 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_vPCI.yaml", "type=operational", "CL_vPCI", "v3.0.0");
120         } catch (IOException e) {
121             e.printStackTrace();
122             logger.debug("Could not create kieSession");
123             fail("Could not create kieSession");
124         }
125     }
126
127     /**
128      * Tear down the simulator.
129      */
130     @AfterClass
131     public static void tearDownSimulator() {
132         /*
133          * Gracefully shut down the kie session
134          */
135         kieSession.dispose();
136
137         PolicyEngine.manager.stop();
138         HttpServletServer.factory.destroy();
139         PolicyController.factory.shutdown();
140         TopicEndpoint.manager.shutdown();
141     }
142
143     @Test
144     public void successTest() {
145
146         /*
147          * Allows the PolicyEngine to callback to this object to notify that there is an
148          * event ready to be pulled from the queue
149          */
150         for (TopicSink sink : noopTopics) {
151             assertTrue(sink.start());
152             sink.register(this);
153         }
154
155         /*
156          * Create a unique requestId
157          */
158         requestId = UUID.randomUUID();
159
160         /*
161          * Simulate an onset event the policy engine will receive from DCAE to kick off
162          * processing through the rules
163          */
164         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, true);
165
166         kieSession.fireUntilHalt();
167
168         /*
169          * The only fact in memory should be Params
170          */
171         assertEquals(1, kieSession.getFactCount());
172
173         /*
174          * Print what's left in memory
175          */
176         dumpFacts(kieSession);
177
178     }
179
180     @Test
181     public void aaiGetFailTest() {
182
183         /*
184          * Allows the PolicyEngine to callback to this object to notify that there is an
185          * event ready to be pulled from the queue
186          */
187         for (TopicSink sink : noopTopics) {
188             assertTrue(sink.start());
189             sink.register(this);
190         }
191
192         /*
193          * Create a unique requestId
194          */
195         requestId = UUID.randomUUID();
196
197         /*
198          * Simulate an onset event the policy engine will receive from DCAE to kick off
199          * processing through the rules
200          */
201         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
202
203         kieSession.fireUntilHalt();
204
205         /*
206          * The only fact in memory should be Params
207          */
208         assertEquals(1, kieSession.getFactCount());
209
210         /*
211          * Print what's left in memory
212          */
213         dumpFacts(kieSession);
214
215     }
216
217     /**
218      * This method will start a kie session and instantiate the Policy Engine.
219      * 
220      * @param droolsTemplate
221      *            the DRL rules file
222      * @param yamlFile
223      *            the yaml file containing the policies
224      * @param policyScope
225      *            scope for policy
226      * @param policyName
227      *            name of the policy
228      * @param policyVersion
229      *            version of the policy
230      * @return the kieSession to be used to insert facts
231      * @throws IOException
232      *             IO exception
233      */
234     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
235             String policyName, String policyVersion) throws IOException {
236
237         /*
238          * Load policies from yaml
239          */
240         pair = Util.loadYaml(yamlFile);
241         assertNotNull(pair);
242         assertNotNull(pair.first);
243         assertNotNull(pair.first.getControlLoop());
244         assertNotNull(pair.first.getControlLoop().getControlLoopName());
245         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
246
247         /*
248          * Construct a kie session
249          */
250         final KieSession kieSession = Util.buildContainer(droolsTemplate,
251                 pair.first.getControlLoop().getControlLoopName(), policyScope, policyName, policyVersion,
252                 URLEncoder.encode(pair.second, "UTF-8"));
253
254         /*
255          * Retrieve the Policy Engine
256          */
257
258         logger.debug("======controlloop======");
259         logger.debug(((ControlLoopPolicy) pair.first).toString());
260         logger.debug("======policies======");
261         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
262         logger.debug("============");
263
264         return kieSession;
265     }
266
267     /*
268      * (non-Javadoc)
269      * 
270      * @see
271      * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
272      * String)
273      */
274     @Override
275     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
276         logger.debug("\n============ onTopicEvent!!! ===========\n");
277         logger.debug("topic: {}, event: {}", topic, event);
278         /*
279          * Pull the object that was sent out to DMAAP and make sure it is a
280          * ControlLoopNoticiation of type active
281          */
282         Object obj = null;
283         if ("POLICY-CL-MGT".equals(topic)) {
284             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
285                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
286         } else if ("SDNR-CL".equals(topic)) {
287             obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
288                     org.onap.policy.sdnr.PciRequestWrapper.class);
289         }
290         assertNotNull(obj);
291         if (obj instanceof VirtualControlLoopNotification) {
292             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
293             String policyName = notification.getPolicyName();
294             logger.debug("Rule Fired: {}", policyName);
295             if (policyName.endsWith("EVENT")) {
296                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
297             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
298                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299                 assertNotNull(notification.getMessage());
300                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
301             } else if (policyName.endsWith("GUARD.RESPONSE")) {
302                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
303                 assertNotNull(notification.getMessage());
304                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
305             } else if (policyName.endsWith("GUARD_PERMITTED")) {
306                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
307                 assertNotNull(notification.getMessage());
308                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
309             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
310                 kieSession.halt();
311                 logger.debug("The operation timed out");
312                 fail("Operation Timed Out");
313             } else if (policyName.endsWith("SDNR.RESPONSE")) {
314                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
315                 assertNotNull(notification.getMessage());
316                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
317             } else if (policyName.endsWith("EVENT.MANAGER")) {
318                 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
319                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
320                     kieSession.halt();
321                 } else {
322                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
323                     kieSession.halt();
324                 }
325             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
326                 kieSession.halt();
327                 logger.debug("The control loop timed out");
328                 fail("Control Loop Timed Out");
329             }
330         } else if (obj instanceof PciRequestWrapper) {
331             /*
332              * The request should be of type PciRequestWrapper and the subrequestid should
333              * be 1
334              */
335             PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
336             PciRequest pciRequest = dmaapRequest.getBody();
337             assertTrue(pciRequest.getCommonHeader().getSubRequestId().equals("1"));
338
339             logger.debug("\n============ SDNR received the request!!! ===========\n");
340             logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
341             logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
342
343             /*
344              * Simulate a success response from SDNR and insert the response into the
345              * working memory
346              */
347             PciResponse pciResponse = new PciResponse(pciRequest);
348             pciResponse.getStatus().setCode(200);
349             pciResponse.getStatus().setValue("SUCCESS");
350             StringBuilder sb = new StringBuilder();
351             sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
352                     + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
353                     + "\"Network1\", \"X0005b9Lte\" : { \"PnfName\" : \"cu1\" }, \"CellConfig\":"
354                     + "{ \"LTE\":{ \"RAN\":{ \"Common\":{ \"CellIdentity\":" + "\"1\" } } } } } } } ] }");
355
356             pciResponse.setPayload(sb.toString());
357             PciResponseWrapper dmaapResponse = new PciResponseWrapper();
358             dmaapResponse.setBody(pciResponse);
359             dmaapResponse.setType("response");
360             logger.debug("\n============ SDNR sending response!!! ===========\n");
361             logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
362             logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
363             kieSession.insert(dmaapResponse);
364         }
365     }
366
367     /**
368      * This method is used to simulate event messages from DCAE that start the
369      * control loop (onset message).
370      * 
371      * @param policy
372      *            the controlLoopName comes from the policy
373      * @param requestID
374      *            the requestId for this event
375      * @param status
376      *            could be onset
377      */
378     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
379             boolean isEnriched) {
380         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
382         event.setRequestId(requestId);
383         event.setTarget("generic-vnf.vnf-id");
384         event.setTargetType(ControlLoopTargetType.VNF);
385         event.setClosedLoopAlarmStart(Instant.now());
386         event.setAai(new HashMap<>());
387         if (isEnriched) {
388             event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
389             event.getAai().put("generic-vnf.prov-status", "ACTIVE");
390             event.getAai().put("generic-vnf.vnf-id", "notused");
391         } else {
392             event.getAai().put("generic-vnf.vnf-id", "getFail");
393         }
394         event.setClosedLoopEventStatus(status);
395         StringBuilder sb = new StringBuilder();
396         sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
397                 + " { \"alias\":\"Cell1\", \"X0005b9Lte\" : { \"PhyCellIdInUse\" :"
398                 + " \"35\", \"PnfName\" : \"cu1\" }, \"CellConfig\":{ \"LTE\":{ \"RAN\":"
399                 + "{ \"Common\":{ \"CellIdentity\":\"1\" } } } } } } } ] }");
400
401         event.setPayload(sb.toString());
402         logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
403         logger.debug("\n============ event ===========\n {}", event);
404         kieSession.insert(event);
405     }
406
407     /**
408      * This method will dump all the facts in the working memory.
409      * 
410      * @param kieSession
411      *            the session containing the facts
412      */
413     public void dumpFacts(KieSession kieSession) {
414         logger.debug("Fact Count: {}", kieSession.getFactCount());
415         for (FactHandle handle : kieSession.getFactHandles()) {
416             logger.debug("FACT: {}", handle);
417         }
418     }
419
420 }