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