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