cbdf09c8daa945595ecae95e4a25deb07844e28a
[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.time.Instant;
29 import java.util.HashMap;
30 import java.util.UUID;
31 import org.junit.BeforeClass;
32 import org.junit.Test;
33 import org.onap.policy.appc.Request;
34 import org.onap.policy.appc.Response;
35 import org.onap.policy.appc.ResponseCode;
36 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
37 import org.onap.policy.common.endpoints.event.comm.TopicListener;
38 import org.onap.policy.common.endpoints.event.comm.TopicSink;
39 import org.onap.policy.controlloop.ControlLoopEventStatus;
40 import org.onap.policy.controlloop.ControlLoopNotificationType;
41 import org.onap.policy.controlloop.ControlLoopTargetType;
42 import org.onap.policy.controlloop.VirtualControlLoopEvent;
43 import org.onap.policy.controlloop.VirtualControlLoopNotification;
44 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
45
46 public class VfwControlLoopTest extends ControlLoopBase implements TopicListener {
47
48     /**
49      * Setup the simulator.
50      */
51     @BeforeClass
52     public static void setUpBeforeClass() {
53         ControlLoopBase.setUpBeforeClass(
54             "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/"
55                             + "main/resources/__closedLoopControlName__.drl",
56             "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
57             "service=ServiceDemo;resource=Res1Demo;type=operational",
58             "CL_vFW",
59             "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
60     }
61
62     @Test
63     public void successTest() {
64
65         /*
66          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
67          * to be pulled from the queue
68          */
69         for (TopicSink sink : noopTopics) {
70             assertTrue(sink.start());
71             sink.register(this);
72         }
73
74         /*
75          * Create a unique requestId
76          */
77         requestId = UUID.randomUUID();
78
79         /*
80          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
81          * through the rules
82          */
83         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
84
85         try {
86             kieSession.fireUntilHalt();
87
88             // allow object clean-up
89             kieSession.fireAllRules();
90
91         } catch (Exception e) {
92             e.printStackTrace();
93             logger.warn(e.toString());
94             fail("fail");
95         }
96
97
98         /*
99          * The only fact in memory should be Params
100          */
101         assertEquals(1, kieSession.getFactCount());
102
103         /*
104          * Print what's left in memory
105          */
106         dumpFacts(kieSession);
107     }
108
109     @Test
110     public void aaiFailTests() {
111
112         /*
113          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
114          * to be pulled from the queue
115          */
116         for (TopicSink sink : noopTopics) {
117             assertTrue(sink.start());
118             sink.register(this);
119         }
120
121         /*
122          * Create a unique requestId
123          */
124         requestId = UUID.randomUUID();
125
126         /*
127          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
128          * through the rules
129          */
130         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
131         try {
132             kieSession.fireUntilHalt();
133
134             // allow object clean-up
135             kieSession.fireAllRules();
136
137         } catch (Exception e) {
138             e.printStackTrace();
139             logger.warn(e.toString());
140             fail(e.getMessage());
141         }
142
143         /*
144          * The only fact in memory should be Params
145          */
146         assertEquals(1, kieSession.getFactCount());
147
148         /*
149          * Print what's left in memory
150          */
151         dumpFacts(kieSession);
152
153         /*
154          * Create a unique requestId
155          */
156         requestId = UUID.randomUUID();
157
158         /*
159          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
160          * through the rules
161          */
162
163         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
164
165         try {
166             kieSession.fireUntilHalt();
167
168             // allow object clean-up
169             kieSession.fireAllRules();
170
171         } catch (Exception e) {
172             e.printStackTrace();
173             logger.warn(e.toString());
174             fail(e.getMessage());
175         }
176
177         /*
178          * The only fact in memory should be Params
179          */
180         assertEquals(1, kieSession.getFactCount());
181
182         /*
183          * Print what's left in memory
184          */
185         dumpFacts(kieSession);
186     }
187
188     /*
189      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
190      */
191     @Override
192     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
193         /*
194          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
195          * of type active
196          */
197         Object obj = null;
198         if ("POLICY-CL-MGT".equals(topic)) {
199             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
200                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
201         } else if ("APPC-CL".equals(topic)) {
202             obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event,
203                     org.onap.policy.appc.Request.class);
204         }
205         assertNotNull(obj);
206         if (obj instanceof VirtualControlLoopNotification) {
207             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
208             String policyName = notification.getPolicyName();
209             if (policyName.endsWith("EVENT")) {
210                 logger.debug("Rule Fired: " + notification.getPolicyName());
211                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
212             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
213                 logger.debug("Rule Fired: " + notification.getPolicyName());
214                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
215                 assertNotNull(notification.getMessage());
216                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
217             } else if (policyName.endsWith("GUARD.RESPONSE")) {
218                 logger.debug("Rule Fired: " + notification.getPolicyName());
219                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
220                 assertNotNull(notification.getMessage());
221                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
222             } else if (policyName.endsWith("GUARD_PERMITTED")) {
223                 logger.debug("Rule Fired: " + notification.getPolicyName());
224                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
225                 assertNotNull(notification.getMessage());
226                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
227             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
228                 logger.debug("Rule Fired: " + notification.getPolicyName());
229                 kieSession.halt();
230                 logger.debug("The operation timed out");
231                 fail("Operation Timed Out");
232             } else if (policyName.endsWith("APPC.RESPONSE")) {
233                 logger.debug("Rule Fired: " + notification.getPolicyName());
234                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
235                 assertNotNull(notification.getMessage());
236                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
237                 sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED);
238             } else if (policyName.endsWith("EVENT.MANAGER")) {
239                 logger.debug("Rule Fired: " + notification.getPolicyName());
240                 if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
241                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
242                     assertEquals("Target vnf-id could not be found", notification.getMessage());
243                 } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) {
244                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
245                 } else {
246                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
247                 }
248                 kieSession.halt();
249             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
250                 logger.debug("Rule Fired: " + notification.getPolicyName());
251                 kieSession.halt();
252                 logger.debug("The control loop timed out");
253                 fail("Control Loop Timed Out");
254             }
255         } else if (obj instanceof Request) {
256             assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1"));
257             assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id"));
258
259             logger.debug("\n============ APPC received the request!!! ===========\n");
260
261             /*
262              * Simulate a success response from APPC and insert the response into the working memory
263              */
264             Response appcResponse = new Response((Request) obj);
265             appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue());
266             appcResponse.getStatus().setValue("SUCCESS");
267             kieSession.insert(appcResponse);
268         }
269     }
270
271     /**
272      * This method is used to simulate event messages from DCAE that start the control loop (onset
273      * message) or end the control loop (abatement message).
274      *
275      * @param policy the controlLoopName comes from the policy
276      * @param requestId the requestId for this event
277      * @param status could be onset or abated
278      */
279     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
280         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
281         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
282         event.setRequestId(requestId);
283         event.setTarget("generic-vnf.vnf-name");
284         event.setTargetType(ControlLoopTargetType.VNF);
285         event.setClosedLoopAlarmStart(Instant.now());
286         event.setAai(new HashMap<>());
287         event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID");
288         event.getAai().put("vserver.vserver-name", "testVserverName");
289         event.setClosedLoopEventStatus(status);
290         kieSession.insert(event);
291     }
292
293     /**
294      * This method is used to simulate event messages from DCAE that start the control loop (onset
295      * message) or end the control loop (abatement message).
296      *
297      * @param policy the controlLoopName comes from the policy
298      * @param requestId the requestId for this event
299      * @param status could be onset or abated
300      */
301     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) {
302         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
303         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
304         event.setRequestId(requestId);
305         event.setTarget("generic-vnf.vnf-name");
306         event.setTargetType(ControlLoopTargetType.VNF);
307         event.setClosedLoopAlarmStart(Instant.now());
308         event.setAai(new HashMap<>());
309         event.getAai().put("generic-vnf.vnf-name", vnfId);
310         event.getAai().put("vserver.vserver-name", vnfId);
311         event.setClosedLoopEventStatus(status);
312         kieSession.insert(event);
313     }
314 }