527fd298ddd31f23f337659cafe765a03a151da7
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2019 Wipro Limited Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 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.time.Instant;
30 import java.util.HashMap;
31 import java.util.UUID;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
35 import org.onap.policy.common.endpoints.event.comm.TopicListener;
36 import org.onap.policy.common.endpoints.event.comm.TopicSink;
37 import org.onap.policy.controlloop.ControlLoopEventStatus;
38 import org.onap.policy.controlloop.ControlLoopNotificationType;
39 import org.onap.policy.controlloop.ControlLoopTargetType;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.VirtualControlLoopNotification;
42 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
43 import org.onap.policy.sdnr.PciRequest;
44 import org.onap.policy.sdnr.PciRequestWrapper;
45 import org.onap.policy.sdnr.PciResponse;
46 import org.onap.policy.sdnr.PciResponseWrapper;
47
48 public class VsonhControlLoopTest extends ControlLoopBase implements TopicListener {
49
50     /**
51      * Setup the simulator.
52      */
53     @BeforeClass
54     public static void setUpBeforeClass() {
55         ControlLoopBase.setUpBeforeClass(
56             "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
57                     + "/src/main/resources/__closedLoopControlName__.drl",
58             "src/test/resources/yaml/policy_ControlLoop_vSONH.yaml",
59             "type=operational",
60             "CL_vSONH",
61             "v4.0.0");
62     }
63
64     @Test
65     public void successTest() {
66
67         /*
68          * Allows the PolicyEngine to callback to this object to notify that there is an
69          * event ready to be pulled from the queue
70          */
71         for (TopicSink sink : noopTopics) {
72             assertTrue(sink.start());
73             sink.register(this);
74         }
75
76         /*
77          * Create a unique requestId
78          */
79         requestId = UUID.randomUUID();
80
81         /*
82          * Simulate an onset event the policy engine will receive from DCAE to kick off
83          * processing through the rules
84          */
85         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, true);
86
87         kieSession.fireUntilHalt();
88
89         // allow object clean-up
90         kieSession.fireAllRules();
91
92         /*
93          * The only fact in memory should be Params
94          */
95         assertEquals(1, kieSession.getFactCount());
96
97         /*
98          * Print what's left in memory
99          */
100         dumpFacts(kieSession);
101
102     }
103
104     @Test
105     public void aaiGetFailTest() {
106
107         /*
108          * Allows the PolicyEngine to callback to this object to notify that there is an
109          * event ready to be pulled from the queue
110          */
111         for (TopicSink sink : noopTopics) {
112             assertTrue(sink.start());
113             sink.register(this);
114         }
115
116         /*
117          * Create a unique requestId
118          */
119         requestId = UUID.randomUUID();
120
121         /*
122          * Simulate an onset event the policy engine will receive from DCAE to kick off
123          * processing through the rules
124          */
125         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, false);
126
127         kieSession.fireUntilHalt();
128
129         // allow object clean-up
130         kieSession.fireAllRules();
131
132         /*
133          * The only fact in memory should be Params
134          */
135         assertEquals(1, kieSession.getFactCount());
136
137         /*
138          * Print what's left in memory
139          */
140         dumpFacts(kieSession);
141
142     }
143
144     /*
145      * (non-Javadoc)
146      *
147      * @see
148      * org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.
149      * String)
150      */
151     @Override
152     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
153         logger.debug("\n============ onTopicEvent!!! ===========\n");
154         logger.debug("topic: {}, event: {}", topic, event);
155         /*
156          * Pull the object that was sent out to DMAAP and make sure it is a
157          * ControlLoopNoticiation of type active
158          */
159         Object obj = null;
160         if ("POLICY-CL-MGT".equals(topic)) {
161             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
162                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
163         } else if ("SDNR-CL".equals(topic)) {
164             obj = org.onap.policy.sdnr.util.Serialization.gsonJunit.fromJson(event,
165                     org.onap.policy.sdnr.PciRequestWrapper.class);
166         }
167         assertNotNull(obj);
168         if (obj instanceof VirtualControlLoopNotification) {
169             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
170             String policyName = notification.getPolicyName();
171             logger.debug("Rule Fired: {}", policyName);
172             if (policyName.endsWith("EVENT")) {
173                 assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification());
174             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
175                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
176                 assertNotNull(notification.getMessage());
177                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
178             } else if (policyName.endsWith("GUARD.RESPONSE")) {
179                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
180                 assertNotNull(notification.getMessage());
181                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
182             } else if (policyName.endsWith("GUARD_PERMITTED")) {
183                 assertEquals(ControlLoopNotificationType.OPERATION, notification.getNotification());
184                 assertNotNull(notification.getMessage());
185                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
186             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
187                 kieSession.halt();
188                 logger.debug("The operation timed out");
189                 fail("Operation Timed Out");
190             } else if (policyName.endsWith("SDNR.RESPONSE")) {
191                 assertEquals(ControlLoopNotificationType.OPERATION_SUCCESS, notification.getNotification());
192                 assertNotNull(notification.getMessage());
193                 assertTrue(notification.getMessage().startsWith("actor=SDNR"));
194             } else if (policyName.endsWith("EVENT.MANAGER")) {
195                 if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-id"))) {
196                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
197                     kieSession.halt();
198                 } else {
199                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
200                     kieSession.halt();
201                 }
202             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
203                 kieSession.halt();
204                 logger.debug("The control loop timed out");
205                 fail("Control Loop Timed Out");
206             }
207         } else if (obj instanceof PciRequestWrapper) {
208             /*
209              * The request should be of type PciRequestWrapper and the subrequestid should
210              * be 1
211              */
212             PciRequestWrapper dmaapRequest = (PciRequestWrapper) obj;
213             PciRequest pciRequest = dmaapRequest.getBody();
214             assertEquals("1", pciRequest.getCommonHeader().getSubRequestId());
215
216             logger.debug("\n============ SDNR received the request!!! ===========\n");
217             logger.debug("\n============ dmaapRequest ===========\n {} ", dmaapRequest);
218             logger.debug("\n============ pciRequest ===========\n {}", pciRequest);
219
220             /*
221              * Simulate a success response from SDNR and insert the response into the
222              * working memory
223              */
224             PciResponse pciResponse = new PciResponse(pciRequest);
225             pciResponse.getStatus().setCode(200);
226             pciResponse.getStatus().setValue("SUCCESS");
227             StringBuilder sb = new StringBuilder();
228             sb.append("{ \"Configurations\":[ { \"Status\": { \"Code\": 200, \"Value\":"
229                     + " \"SUCCESS\" }, \"data\":{ \"FAPService\":{ \"alias\":"
230                     + "\"Network1\", \"CellConfig\":{ \"LTE\":{ \"RAN\":{ \"Common\":"
231                                         + "{ \"CellIdentity\":\"1\" }, \"NeighborListInUse\" : "
232                                         + "{ \"LTECellNumberOfEntries\" : \"1\" , \"LTECell\" : "
233                                         + "[ { \"PLMNID\" :\"plmnid1\", \"CID\":\"Chn0001\", \"PhyCellID\":"
234                                         + "\"3\", \"PNFName\":\"ncserver01\", \"Blacklisted\":\"false\" "
235                                         + "} ] } } } } } } } ] }");
236
237             pciResponse.setPayload(sb.toString());
238             PciResponseWrapper dmaapResponse = new PciResponseWrapper();
239             dmaapResponse.setBody(pciResponse);
240             dmaapResponse.setType("response");
241             logger.debug("\n============ SDNR sending response!!! ===========\n");
242             logger.debug("\n============ dmaapResponse ===========\n {}", dmaapResponse);
243             logger.debug("\n============ pciResponse ===========\n {}", pciResponse);
244             kieSession.insert(dmaapResponse);
245         }
246     }
247
248     /**
249      * This method is used to simulate event messages from DCAE that start the
250      * control loop (onset message).
251      *
252      * @param policy
253      *            the controlLoopName comes from the policy
254      * @param requestId
255      *            the requestId for this event
256      * @param status
257      *            could be onset
258      */
259     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
260             boolean isEnriched) {
261         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
262         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
263         event.setRequestId(requestId);
264         event.setTarget("generic-vnf.vnf-id");
265         event.setTargetType(ControlLoopTargetType.VNF);
266         event.setClosedLoopAlarmStart(Instant.now());
267         event.setAai(new HashMap<>());
268         if (isEnriched) {
269             event.getAai().put("generic-vnf.is-closed-loop-disabled", "false");
270             event.getAai().put("generic-vnf.prov-status", "ACTIVE");
271             event.getAai().put("generic-vnf.vnf-id", "notused");
272             event.getAai().put("vserver.vserver-name", "OzVServer");
273         } else {
274             event.getAai().put("generic-vnf.vnf-id", "getFail");
275         }
276         event.setClosedLoopEventStatus(status);
277         StringBuilder sb = new StringBuilder();
278         sb.append("{ \"Configurations\":[ { \"data\":{ \"FAPService\":"
279                 + " { \"alias\":\"Cell1\", \"CellConfig\":{ \"LTE\":{ \"RAN\":{ \"Common\":"
280                                         + "{ \"CellIdentity\":\"1\" }, \"NeighborListInUse\" : "
281                                         + "{ \"LTECellNumberOfEntries\" : \"1\" , \"LTECell\" : "
282                                         + "[ { \"PLMNID\" :\"plmnid1\", \"CID\":\"Chn0001\", \"PhyCellID\":"
283                                         + "\"3\", \"PNFName\":\"ncserver01\", \"Blacklisted\":\"false\" "
284                                         + "} ] } } } } } } } ] }");
285
286         event.setPayload(sb.toString());
287         logger.debug("\n============ Policy receiving ONSET event !!! ===========\n");
288         logger.debug("\n============ event ===========\n {}", event);
289         kieSession.insert(event);
290     }
291 }